配置shiro框架

基本认识

  1. shiro自带了几种默认的拦截器
    1. authc [需要登录,rememberMeAuthentiationToken] 进行登录
    2. anon 不需要登录
    3. roles 需要相关的 角色才能登陆
  2. 这里我也可以自己实现一个拦截器 【jwtFilter 】 ,然后注册到 shiro里面使用
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

package org.apache.shiro.authz.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Requires the current Subject to have been authenticated <em>during their current session</em> for the annotated
 * class/instance/method to be accessed or invoked.  This is <em>more</em> restrictive than the
 * {@link RequiresUser RequiresUser} annotation.
 * <p/>
 * This annotation basically ensures that
 * <code>{@link org.apache.shiro.subject.Subject subject}.{@link org.apache.shiro.subject.Subject#isAuthenticated() isAuthenticated()} === true</code>
 * <p/>
 * See the {@link RequiresUser RequiresUser} and
 * {@link org.apache.shiro.authc.RememberMeAuthenticationToken RememberMeAuthenticationToken} JavaDoc for an
 * explaination of why these two states are considered different.
 *
 * @see RequiresUser
 * @see RequiresGuest
 *
 * @since 0.9.0
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresAuthentication {
}
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package io.github.lyr2000.dissertation.config;

import io.github.lyr2000.common.dto.Maps;
import io.github.lyr2000.common.shiro.config.EnableShiroAutoConfig;
import io.github.lyr2000.common.shiro.config.ShiroCustomProperties;
import io.github.lyr2000.common.shiro.filter.JwtFilter;
import io.github.lyr2000.common.shiro.util.JwtUtil;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author LYR666
 * @description shiro权限框架配置
 * @create 2021-11-03 20:16
 */
@EnableShiroAutoConfig
@Configuration
public class ShiroConfig {
    @Bean
    // @Profile({"prod","dev"})
    public ShiroCustomProperties shiroCustomProperties() {
        LinkedHashMap map  = (LinkedHashMap)
                Maps.linkedHashMap()
                        .put("/**","jwt")
                        // .put("/backend/login","anon")
                        // .put("/backend/login11","anon")
                        // .put("/backend/code","anon")
                        // .put("/css/**","anon")
                        // .put("/js/**","anon")
                        //
                        // .put("/**","roles[admin]")
                        // .put("/backendxxx/**","roles[admin]")
                        .getMap();
        return new ShiroCustomProperties("lyr-2000.github.io","token")
                // .setLoginUrl("/backend/login")
                // .setUnauthorizedUrl("/backend/login")
                // .setSuccessUrl("/backend/")
                .setCustomFilterChain(
                        map
                );
    }

    /**
     * jwt工具类
     * @return
     */
    @Bean
    @Primary
    @Scope("prototype")
    public JwtUtil jwtUtil() {
        return new JwtUtil(shiroCustomProperties());
    }


    @Bean
    @Scope("prototype")
    public JwtUtil refreshTokenUtil() {
        return new JwtUtil(new ShiroCustomProperties("www.lyr-2000.xyz","token"));
    }

    /**
     * jwt 拦截器
     * @return
     */
    // @Bean
    // public JwtFilter jwtFilter() {
    //     return new JwtFilter(shiroCustomProperties(),jwtUtil());
    // }

    @Bean
    // @ConditionalOnMissingBean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager,
                                                         JwtUtil jwtUtil,
                                                         @Autowired JwtFilter jwtFilter,
                                                         ShiroCustomProperties shiroCustomProperties,
                                                         ShiroCustomProperties properties) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        Map<String, Filter> filterMap = new HashMap<>(16);
        filterMap.put("jwt", jwtFilter/*new JwtFilter(shiroCustomProperties, jwtUtil)*/);
        factoryBean.setFilters(filterMap);
        factoryBean.setSecurityManager(securityManager);
        if (properties.getLoginUrl() != null) {
            factoryBean.setLoginUrl(properties.getLoginUrl());
        }
        if (properties.getUnauthorizedUrl() != null) {
            factoryBean.setUnauthorizedUrl(properties.getUnauthorizedUrl());
        }
        if (properties.getSuccessUrl() != null) {
            factoryBean.setSuccessUrl(properties.getSuccessUrl());
        }
        // 添加自己的过滤器取名为jwt
        //
        // System.out.println("---------------------------------------------");
        // System.out.println(properties.getCustomFilterChain());

        // 自定义url规则使用LinkedHashMap有序Map
        // LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(16);
        // JwtProperties properties = jwtProperties();
        // 登录接口放开
        // filterChainDefinitionMap.put("/user/login", "anon");
        // "/api/getToken","/api/login/**","/api/register/**"
        // filterChainDefinitionMap.put("/api/login/email", ShiroConstants.Anon.getContent());
        // filterChainDefinitionMap.put("/api/register/email",ShiroConstants.Anon.getContent());
        // filterChainDefinitionMap.put("/api/login/**","anon");
        // filterChainDefinitionMap.put("/api/login","anon");
        // filterChainDefinitionMap.put("/api/register/**",ShiroConstants.Anon.getContent());
        // filterChainDefinitionMap.put("/api/video/_search",ShiroConstants.Anon.getContent());
        // // 所有请求通过我们自己的JWTFilter
        // filterChainDefinitionMap.put("/api/**", "jwt");
        if (properties.getCustomFilterChain() != null) {
            factoryBean.setFilterChainDefinitionMap(properties.getCustomFilterChain());
        }

        // factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);


        // factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return factoryBean;
    }
}

requireRoles 和 requirePermission

1
2
3
4
5
   @org.springframework.web.bind.annotation.ExceptionHandler(value = {org.apache.shiro.authz.UnauthenticatedException.class})
    public Result noToken(UnauthenticatedException e) {
        log.info("require authenticate = {}",e.getMessage());
        return Result.of(DefaultApiCode.NO_TOKEN,"没有登录,出现异常");
    }