Java Spring:登录后基于角色的重定向

Java Spring:登录后基于角色的重定向,java,spring,security,Java,Spring,Security,我有三个用户角色{ADMIN、MANAGER、EMPLOYEE}。它已经可以工作,例如管理员可以访问/Admin/**等等。但我真正想做的是,当刚刚使用角色ADMIN登录的用户被重定向到例如welcome2.xhtml,而所有其他非角色ADMIN的用户被重定向到例如welcome.xhtml时 下面的代码我已经有了 http.authorizeRequests() //Permit access to the H2 console

我有三个用户角色{ADMIN、MANAGER、EMPLOYEE}。它已经可以工作,例如管理员可以访问/Admin/**等等。但我真正想做的是,当刚刚使用角色ADMIN登录的用户被重定向到例如welcome2.xhtml,而所有其他非角色ADMIN的用户被重定向到例如welcome.xhtml时

下面的代码我已经有了

http.authorizeRequests()
                //Permit access to the H2 console
                .antMatchers("/h2-console/**").permitAll()
                //Permit access for all to error pages
                .antMatchers("/error/**")
                .permitAll()
                // Only access with admin role
                .antMatchers("/admin/**")
                .hasAnyAuthority("ADMIN")
                //Permit access only for some roles
                .antMatchers("/secured/**")
                .hasAnyAuthority("ADMIN", "MANAGER", "EMPLOYEE")
                //If user doesn't have permission, forward him to login page
                .and()
                .formLogin()
                .loginPage("/login.xhtml")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/secured/welcome.xhtml");

您需要有一个自定义的身份验证成功处理程序,该处理程序将检查角色并重定向到适当的页面。试试这样的:

public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

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

        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }

    protected void handle(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {

        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            logger.debug(
              "Response has already been committed. Unable to redirect to "
              + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {        
        boolean isAdmin = false;
        boolean isManager = false;
        boolean isEmployee = false;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_MANAGER")) {
                isManager = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_EMPLOYEEE")) {
                isEmployee = true;
                break;
            }
        }

        if (isAdmin) {
            return "/welcome2.xhtml";
        } else if (isManager) {
            return "/welcome.xhtml";
        } else if (isEmployee) {
            return "/welcome.xhtml";
        } else {
            throw new IllegalStateException();
        }
    }

    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}

您需要有一个自定义的身份验证成功处理程序,该处理程序将检查角色并重定向到适当的页面。试试这样的:

public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    protected Log logger = LogFactory.getLog(this.getClass());

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

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

        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }

    protected void handle(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication)
      throws IOException {

        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            logger.debug(
              "Response has already been committed. Unable to redirect to "
              + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {        
        boolean isAdmin = false;
        boolean isManager = false;
        boolean isEmployee = false;
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_MANAGER")) {
                isManager = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_EMPLOYEEE")) {
                isEmployee = true;
                break;
            }
        }

        if (isAdmin) {
            return "/welcome2.xhtml";
        } else if (isManager) {
            return "/welcome.xhtml";
        } else if (isEmployee) {
            return "/welcome.xhtml";
        } else {
            throw new IllegalStateException();
        }
    }

    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}

谢谢你,这很有效。你能解释一下
Collectionthank you-它是如何工作的吗。你能解释一下如何收集信息吗