Spring Security之实现登录后跳转到登录前页面

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1.通过登录页登录后,跳转到后台首页 。例如,直接打开login.htm登录,登录成功后应跳转到admin/adminIndex.htm

2.直接访问后台其他需要权限的页面,因为权限控制的原因会被跳转到登录页,登录成功后,应在此跳转到想直接访问的页面。例如,admin/b.htm需要权限才可以访问,未登录的无权限用户直接访问改页面,会被跳转到登录页login.htm,登陆成功后,应自动跳转到admin/b.htm页。

借用其他人画的流程图

Spring Security之实现登录后跳转到登录前页面_第1张图片

    当在ExceptionTranslationFilter中拦截时,会调用HttpSessionRequestCache保存原始的请求信息。在UsernamePasswordAuthenticationFilter过滤器登录成功后,会调用SavedRequestAwareAuthenticationSuccessHandler。我创建一个MyAuthenticationSuccessHandler类,继承自SavedRequestAwareAuthenticationSuccessHandler,并在其中的onAuthenticationSuccess将页面重定向至需要的URL。

public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;
    
    private final static Logger logger = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        RequestCache requestCache = new HttpSessionRequestCache();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        User user = null;
        try {
            
            user = userService.getUserByMail(userDetails.getUsername());
            request.getSession().setAttribute("username",user.getUsername());
            request.getSession().setAttribute("userId",user.getId());
            logService.addLog("myUserDetailsService.loadUserByUsername","认证模块","低",
                    "登录","成功","邮箱为" + user.getMail() + "的用户登录成功,登录IP为" + request.getRemoteAddr(),user.getId());
        }catch (Exception e){
            logService.addLog("MyAuthenticationSuccessHandler.onAuthenticationSuccess","认证模块","高","登录","失败","保存session失败,mail为" + user.getMail(),user.getId());
        }
        String url = null;
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest != null){
            url = savedRequest.getRedirectUrl();
        }
        if(url == null){
            getRedirectStrategy().sendRedirect(request,response,"/admin/adminIndex.htm");
        }
        super.onAuthenticationSuccess(request, response, authentication);
    }
}

若URL为空,表明用户直接访问 的登录页,则跳转到后台首页,否则跳转到之前的页面中。

配置文件中需要设置authentication-success-handler-ref


    
    
    
    
    

 

转载于:https://my.oschina.net/jiyufei/blog/1635118

你可能感兴趣的:(java,python)