определить целевой URL-адрес на основе ролей в весенней безопасности 3.1

В весенней безопасности 3.0 у нас есть класс AuthenticationProcessingFilter, в котором мы использовали метод determineTargetUrl(), который возвращал URL-адрес на основе разных ролей.

Теперь мы переходим на весеннюю безопасность 3.1.0.RC3, и я застрял, как мне теперь определить URL-адрес на основе разных ролей, поскольку класс AuthenticationProcessingFilter был удален из новой версии. Может ли кто-нибудь дать мне краткие инструкции с некоторым кодом, чтобы я мог реализовать собственный фильтр для перенаправления на разные страницы для разных ролей.


person Mital Pritmani    schedule 30.11.2011    source источник


Ответы (2)


Лучший способ определить целевой URL-адрес на основе ролей — указать целевой URL-адрес в конфигурации Spring Security, как показано ниже. Это будет работать в Spring 3.0 или 3.1.

<http>
    ... 
    <form-login login-page="/login" default-target-url="/default"/>
</http>

Затем создайте контроллер, который обрабатывает целевой URL-адрес по умолчанию. Контроллер должен перенаправлять или перенаправлять на основе бросков. Ниже приведен пример использования Spring MVC, но подойдет любой тип контроллера (например, Struts, сервлет и т. д.).

@Controller
public class DefaultController {
    @RequestMapping("/default")
    public String defaultAfterLogin(HttpServletRequest request) {
        if (request.isUserInRole("ROLE_ADMIN")) {
            return "redirect:/users/sessions";
        }
        return "redirect:/messages/inbox";
    }
}

Преимущества этого подхода заключаются в том, что он не связан с какой-либо конкретной реализацией Security, он не связан с какой-либо конкретной реализацией MVC и легко работает с конфигурацией пространства имен Spring Security. Полный пример можно найти в проекте SecureMail, который я представил на SpringOne в этом году.

В качестве альтернативы вы можете создать собственный AuthenticationSuccessHandler. Реализация может расширить SavedRequestAwareAuthenticationSuccessHandler, который является AuthenticationSuccessHandler по умолчанию. затем его можно подключить, используя пространство имен, как показано ниже.

<sec:http>
    <sec:form-login authentication-success-handler-ref="authSuccessHandler"/>
</sec:http>
<bean:bean class="example.MyCustomAuthenticationSuccessHandler"/>

Я бы не рекомендовал делать это, так как это связано с API Spring Security, и по возможности этого лучше избегать.

person Rob Winch    schedule 30.11.2011

Использование пользовательского обработчика успеха аутентификации для указания перенаправления на основе роли пользователя после успешной аутентификации.

Вам необходимо создать собственный обработчик успешной аутентификации следующим образом:

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

public class CustomeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException {
        handle(request, response, authentication);
    }

    protected void handle(HttpServletRequest request,
                          HttpServletResponse response, Authentication authentication)
            throws IOException {
        String targetUrl = determineTargetUrl(authentication);
        if (response.isCommitted()) {
            return;
        }
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        boolean isTeacher = false;
        boolean isAdmin = false;
        Collection<? extends GrantedAuthority> authorities
                = authentication.getAuthorities();

        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                isTeacher = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            }
        }

        if (isTeacher) {
            return "/user/account";
        } else if (isAdmin) {
            return "/admin/account";
        } else {
            throw new IllegalStateException();
        }
    }
    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}

Затем измените xml-файл Spring Security, определите свой bean-компонент и используйте его

   <bean id="customeAuthenticationSuccessHandler"
          class="com.test.CustomeAuthenticationSuccessHandler"/>
    <security:http auto-config="true" use-expressions="false">
        <security:form-login login-page="/sign-in" login-processing-url="/sign-in" username-parameter="username"
                             password-parameter="password"
                             authentication-success-handler-ref="customeAuthenticationSuccessHandler"
                             always-use-default-target="true"
                             authentication-failure-url="/sign-in?error=true"/>

        <security:logout logout-url="/logout" logout-success-url="/"/>
     ..
     ..
    </security:http>
person Ahmad Al-Kurdi    schedule 15.08.2018