Spring Security conditional default-target-url

后端 未结 2 1457
慢半拍i
慢半拍i 2021-02-05 16:00

I\'ve noticed that there are a couple of questions asking about this topic. I looked through them and I was unable to apply them to my specific Spring setup. I would like to con

2条回答
  •  不要未来只要你来
    2021-02-05 16:17

    I have tested the code and it works, there's no rocket science in it

    public class MySuccessHandler implements AuthenticationSuccessHandler {
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            Set roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            if (roles.contains("ROLE_ADMIN")){
                response.sendRedirect("/Admin.html");   
                return;
            }
            response.sendRedirect("/User.html");
        }    
    }
    

    Changes in your security context:

    
        
    
    
    

    update if you want to use default-target-url approach, it will work equally well, but will be triggered when your user first accesses the login page:

    @Controller
    public class WelcomeController {
        @RequestMapping(value = "/welcome.htm")
        protected View welcome() {
    
            Set roles = AuthorityUtils
                    .authorityListToSet(SecurityContextHolder.getContext()
                            .getAuthentication().getAuthorities());
            if (roles.contains("ROLE_ADMIN")) {
                return new RedirectView("Admin.htm");
            }
            return new RedirectView("User.htm");
        }
    }
    

提交回复
热议问题