Shiro过滤器Filter的实战使用

1.自定义Realm

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    /**
     * 授权信息
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("授权开始.......doGetAuthorizationInfo");
        // 获取用户名
        User user = (User) principals.getPrimaryPrincipal();
        User userInfo = userService.findAllUserInfoByUsername(user.getUsername());
        // 获取角色名称
        Set<String> roleList = new HashSet<>();
        Set<String> stringPermission = new HashSet<>();
        // 获取权限名称
        userInfo.getRoleList().forEach(role -> {
            roleList.add(role.getName());
            if(role.getPermissionList() != null) {
                stringPermission.addAll(role.getPermissionList().stream().map(Permission::getName).collect(Collectors.toList()));
            }
        });

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roleList);
        authorizationInfo.setStringPermissions(stringPermission);
        return authorizationInfo;
    }

    /**
     * 用于认证信息
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始........doGetAuthenticationInfo");
        // 获取用户名
        String username = (String) token.getPrincipal();
        // 获取用户密码
        User user = userService.findSimpleUserInfoByUsername(username);
        String pwd = user.getPassword();
        if (pwd==null || "".equals(pwd)){
            return null;
        }
        // 自动验证
        return new SimpleAuthenticationInfo(user,pwd,this.getClass().getName());
    }
}

2.自定义角色权限CustomRolesOrAuthorizationFilter

public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        // 如果未设置角色列表
        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        Set<String> roles = CollectionUtils.asSet(rolesArray);
        // 有其中一个角色就可以
        for (String role : roles){
            if (subject.hasRole(role)){
                return true;
            }
        }
        return false;
    }
}

3.自定义SessionId生成

public class CustomSessionIdGenerator implements SessionIdGenerator {

    @Override
    public Serializable generateId(Session session) {
        return "xxx"+ UUID.randomUUID().toString().replace("-","");
    }
}

4.自定义会话管理器CustomSessionManager

public class CustomSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION = "token";

    public CustomSessionManager() {
        super();
    }


    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if (sessionId != null) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
                    ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);

            //automatically mark it valid here.  If it is invalid, the
            //onUnknownSession method below will be invoked and we'll remove the attribute at that time.
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        } else {
            return super.getSessionId(request, response);
        }
    }
}

5.shiro过滤器配置

@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        System.out.println("执行... ShiroFilterFactoryBean");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //必须设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 需要登录的接口,如果访问某个接口,需要登录却没登录时,则调用此接口(如果不是前后端分离,则跳转页面)
        shiroFilterFactoryBean.setLoginUrl("/pub/need_login");

        // 登录成功,跳转url,如果前后端分离,则没这个调用
        shiroFilterFactoryBean.setSuccessUrl("/");

        // 没有权限,未授权就会调用此方法, 先验证登录-》再验证是否有权限
        shiroFilterFactoryBean.setUnauthorizedUrl("/pub/not_permit");

        Map<String, Filter> filterChainMap = new HashMap<>();
        filterChainMap.put("roleOrAuth",new CustomRolesOrAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filterChainMap);

        // 拦截器路径,坑一,部分路径无法进行拦截,时有时无;因为使用的是hashmap, 无序的,应该改为LinkedHashMap
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 退出过滤器
        filterChainDefinitionMap.put("/logout",DefaultFilter.logout.name());
        // 匿名访问,游客模式
        filterChainDefinitionMap.put("/pub/**", DefaultFilter.anon.name());
        // 登录用户才可访问
        filterChainDefinitionMap.put("/authc/**",DefaultFilter.authc.name());
        // 管理员角色才可访问
        filterChainDefinitionMap.put("/admin/**","roleOrAuth[admin,root]");
//        filterChainDefinitionMap.put("/admin/**","roles[admin,root]");
        // 有相关权限才可访问
        filterChainDefinitionMap.put("/order/**","perms[order_update]");

        // 坑二: 过滤链是顺序执行,从上而下,一般将/** 放到最下面
        //authc : url定义必须通过认证才可以访问
        //anon  : url可以匿名访问
        filterChainDefinitionMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 设置会话管理器,前后端分离需要设置
        securityManager.setSessionManager(customSessionManager());

        // 设置缓存
        securityManager.setCacheManager(cacheManager());

        // 设置realm
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    @Bean
    public CustomRealm customRealm(){
        CustomRealm customRealm = new CustomRealm();
        // 对密码进行加密
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置散列算法
        credentialsMatcher.setHashAlgorithmName("md5");
        // 双重md5加密
        credentialsMatcher.setHashIterations(2);
        return credentialsMatcher;
    }

    @Bean
    public CustomSessionManager customSessionManager(){
        CustomSessionManager customSessionManager = new CustomSessionManager();
        // 设置会话超时时间为20秒,单位是毫秒,默认30分钟
        customSessionManager.setGlobalSessionTimeout(200000);
        customSessionManager.setSessionDAO(redisSessionDAO());
        return customSessionManager;
    }

    // 增加redis缓存
    @Bean
    public RedisManager getRedisManager(){
        RedisManager redisManager = new RedisManager();
        redisManager.setHost("localhost");
        redisManager.setPort(6379);
        return redisManager;
    }

    @Bean
    public CacheManager cacheManager(){
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(getRedisManager());
        // 设置缓存过期时间 单位s
        redisCacheManager.setExpire(20);
        return redisCacheManager;
    }

    /**
     * 使会话层持久
     * @return
     */
    @Bean
    public RedisSessionDAO redisSessionDAO(){
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(getRedisManager());
        // 设置自定义sessionId生成
        redisSessionDAO.setSessionIdGenerator(new CustomSessionIdGenerator());
        return redisSessionDAO;
    }

    /**
     * lifecycleBeanPostProcessor
     * 作用:管理shiro一些bean的生命周期 即bean初始化 与销毁
     * @return
     */
    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * AuthorizationAttributeSourceAdvisor
     * 作用:加入注解的使用,不加入这个AOP注解不生效(shiro的注解 例如 @RequiresGuest)
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor()
    {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new
                AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * DefaultAdvisorAutoProxyCreator
     * 作用: 用来扫描上下文寻找所有的Advistor(通知器), 将符合条件的Advisor应用到切入点的Bean中,需
     * 要在LifecycleBeanPostProcessor创建后才可以创建
     * @return
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator=new
                DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
        return defaultAdvisorAutoProxyCreator;
    }
}

你可能感兴趣的:(#,Apache,Shiro权限框架,java,前端,spring)