• 用户登录权限验证链接跳转处理关键代码


    package com.tszr.security;
    
    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.SimpleUrlAuthenticationSuccessHandler;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    @Component
    public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        //Spring Security的重定向策略
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        /**
         * 重写handle方法,通过RedirectStrategy重定向到指定的URL
         */
        @Override
        protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            //根据当前认证用户的角色返回适当的URL
            String tagetURL = getTargetURL(authentication);
            //重定向到指定的URL
            redirectStrategy.sendRedirect(request, response, tagetURL);
        }
    
        /**
         * 从Authentication对象中提取当前登录用户的角色,并根据其角色返回适当的URL
         */
        protected String getTargetURL(Authentication authentication) {
            String url = "";
            //获得当前登录用户的权限(角色)集合
            Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();
            List<String> roles = new ArrayList<String>();
            //将权限(角色)名称添加到List集合
            for (GrantedAuthority au : authorities) {
                roles.add(au.getAuthority());
            }
            //判断不同角色的用户跳转到不同的URL
            //这里的URL是控制器的请求匹配路径
            if(roles.contains("ROLE_USER")) {
                url = "/user/loginSuccess";
            }else if(roles.contains("ROLE_ADMIN")) {
                url = "/admin/main";
            }else {
                url = "/deniedAccess";
            }
            return url;
        }
    }
  • 相关阅读:
    无名信号量在多线程间的同步
    ftok函数例子
    strerror和perror函数详解
    lockf函数的使用
    背包问题-2动态规划【正解】
    递归思想即背包问题
    生产者消费者问题(基于线程和无名信号量)
    eclipse 安装python后pydev不出现
    Eclipse+pydev解决中文显示和注释问题的方法大全
    MyEclipse10配置PyDev进行Python开发
  • 原文地址:https://www.cnblogs.com/tszr/p/15984566.html
Copyright © 2020-2023  润新知