Browse Source

验证客户端jar

yufeng0528 4 years ago
parent
commit
b0386c0337
21 changed files with 846 additions and 221 deletions
  1. 1 0
      pom.xml
  2. 1 0
      spring5-admin/.gitignore
  3. 2 2
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/Oauth2Application.java
  4. 23 0
      spring5-admin/java/com/yaozhitech/spring5/config/RoleResourceConfiguration.java
  5. 17 0
      spring5-admin/java/com/yaozhitech/spring5/controller/AdminController.java
  6. 92 0
      spring5-admin/pom.xml
  7. 22 0
      spring5-admin/src/main/resources/application.yml
  8. 10 29
      spring5-auth/spring5-auth-client/pom.xml
  9. 0 145
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/config/AuthorizationServerConfig.java
  10. 139 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/config/ShiroConfiguration.java
  11. 0 23
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/controller/LoginController.java
  12. 16 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/dto/UserDto.java
  13. 43 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/filter/AnyRolesAuthorizationFilter.java
  14. 157 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/filter/JwtAuthFilter.java
  15. 41 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTCredentialsMatcher.java
  16. 58 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTShiroRealm.java
  17. 44 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTToken.java
  18. 82 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/service/UserService.java
  19. 82 0
      spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/utils/JwtUtils.java
  20. 15 15
      spring5-auth/spring5-auth-client/src/main/resources/application.yml
  21. 1 7
      spring5-auth/spring5-auth-server/src/main/java/com/yaozhitech/spring5/filter/JwtAuthFilter.java

+ 1 - 0
pom.xml

@@ -14,6 +14,7 @@
14 14
     <modules>
15 15
         <module>spring5-auth</module>
16 16
         <module>spring5-gateway</module>
17
+        <module>spring5-admin</module>
17 18
     </modules>
18 19
 
19 20
 	<properties>

+ 1 - 0
spring5-admin/.gitignore

@@ -0,0 +1 @@
1
+/target/

+ 2 - 2
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/Oauth2Application.java

@@ -5,8 +5,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
5 5
 
6 6
 
7 7
 @SpringBootApplication
8
-public class Oauth2Application {
8
+public class Application {
9 9
     public static void main(String[] args) {
10
-        SpringApplication.run(Oauth2Application.class, args);
10
+        SpringApplication.run(Application.class, args);
11 11
     }
12 12
 }

+ 23 - 0
spring5-admin/java/com/yaozhitech/spring5/config/RoleResourceConfiguration.java

@@ -0,0 +1,23 @@
1
+package com.yaozhitech.spring5.config;
2
+
3
+import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
4
+import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
5
+import org.springframework.context.annotation.Bean;
6
+import org.springframework.context.annotation.Configuration;
7
+
8
+@Configuration
9
+public class RoleResourceConfiguration {
10
+
11
+//	@Bean
12
+	public ShiroFilterChainDefinition shiroFilterChainDefinition() {
13
+		DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
14
+//    chainDefinition.addPathDefinition("/login", "noSessionCreation,anon");  //login不做认证,noSessionCreation的作用是用户在操作session时会抛异常
15
+//    chainDefinition.addPathDefinition("/logout", "noSessionCreation,authcToken[permissive]"); //做用户认证,permissive参数的作用是当token无效时也允许请求访问,不会返回鉴权未通过的错误
16
+//    chainDefinition.addPathDefinition("/image/**", "anon");
17
+		chainDefinition.addPathDefinition("/admin/**", "noSessionCreation,authcToken,anyRole[admin,manager]"); // 只允许admin或manager角色的用户访问
18
+		chainDefinition.addPathDefinition("/article/list", "noSessionCreation,authcToken");
19
+		chainDefinition.addPathDefinition("/article/*", "noSessionCreation,authcToken[permissive]");
20
+		chainDefinition.addPathDefinition("/**", "noSessionCreation,authcToken"); // 默认进行用户鉴权
21
+		return chainDefinition;
22
+	}
23
+}

+ 17 - 0
spring5-admin/java/com/yaozhitech/spring5/controller/AdminController.java

@@ -0,0 +1,17 @@
1
+package com.yaozhitech.spring5.controller;
2
+
3
+import org.springframework.http.ResponseEntity;
4
+import org.springframework.web.bind.annotation.GetMapping;
5
+import org.springframework.web.bind.annotation.PathVariable;
6
+import org.springframework.web.bind.annotation.RequestMapping;
7
+import org.springframework.web.bind.annotation.RestController;
8
+
9
+@RestController
10
+@RequestMapping("/admin")
11
+public class AdminController {
12
+
13
+	@GetMapping("/{id}")
14
+	public ResponseEntity<String> read(@PathVariable Long id) {
15
+		return ResponseEntity.ok("ok");
16
+	}
17
+}

+ 92 - 0
spring5-admin/pom.xml

@@ -0,0 +1,92 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4
+	<modelVersion>4.0.0</modelVersion>
5
+	
6
+	<artifactId>spring5-admin</artifactId>
7
+	<packaging>jar</packaging>
8
+	<name>${project.artifactId}</name>
9
+    <description>spring5 demo</description>
10
+	
11
+	<!-- Spring Boot 启动父依赖 -->
12
+	<parent>
13
+        <groupId>com.yaozhitech</groupId>
14
+        <artifactId>spring5</artifactId>
15
+        <version>0.1.0</version>
16
+    </parent>
17
+
18
+	<dependencies>
19
+        
20
+		<!-- Spring Boot Web 依赖 -->
21
+		<dependency>
22
+			<groupId>org.springframework.boot</groupId>
23
+			<artifactId>spring-boot-starter-web</artifactId>
24
+		</dependency>
25
+	
26
+		<!-- Spring Boot Redis 依赖 -->
27
+		<dependency>
28
+			<groupId>org.springframework.boot</groupId>
29
+			<artifactId>spring-boot-starter-data-redis</artifactId>
30
+		</dependency>
31
+		
32
+<!-- 		<dependency> -->
33
+<!--             <groupId>com.alicp.jetcache</groupId> -->
34
+<!--             <artifactId>jetcache-starter-redis</artifactId> -->
35
+<!--             <version>2.6.0.M3</version> -->
36
+<!--         </dependency> -->
37
+
38
+<!-- 		<dependency> -->
39
+<!-- 			<groupId>com.alicp.jetcache</groupId> -->
40
+<!-- 			<artifactId>jetcache-redis-lettuce</artifactId> -->
41
+<!-- 			<version>2.6.0.M3</version> -->
42
+<!-- 		</dependency> -->
43
+			
44
+		<!-- Spring test 依赖 -->
45
+        <dependency>
46
+            <groupId>org.springframework.boot</groupId>
47
+            <artifactId>spring-boot-starter-test</artifactId>
48
+            <scope>test</scope>
49
+        </dependency>
50
+        
51
+        <dependency>
52
+            <groupId>junit</groupId>
53
+            <artifactId>junit</artifactId>
54
+            <scope>test</scope>
55
+        </dependency>
56
+        
57
+        <!-- 集成wireMock来实现mock请求响应。wireMock会自动构建一个虚拟远程服务 -->
58
+		<dependency>
59
+		   <groupId>org.springframework.cloud</groupId>
60
+		   <artifactId>spring-cloud-contract-wiremock</artifactId>
61
+		   <scope>test</scope>
62
+		</dependency>
63
+		
64
+		<!-- 提供打包预定义数据服务 -->
65
+		<dependency>
66
+		   <groupId>org.springframework.cloud</groupId>
67
+		   <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
68
+		   <scope>test</scope>
69
+		</dependency>
70
+		
71
+		<!-- 自动生成单元测试代码 -->
72
+		<dependency>
73
+		   <groupId>org.springframework.cloud</groupId>
74
+		   <artifactId>spring-cloud-starter-contract-verifier</artifactId>
75
+		   <scope>test</scope>
76
+		</dependency>
77
+
78
+
79
+		<dependency>
80
+			<groupId>com.github.tomakehurst</groupId>
81
+			<artifactId>wiremock-standalone</artifactId>
82
+			<scope>test</scope>
83
+		</dependency>
84
+		
85
+		<dependency>
86
+            <groupId>com.yaozhitech</groupId>
87
+            <artifactId>spring5-auth-client</artifactId>
88
+            <version>0.1.0</version>
89
+        </dependency>
90
+
91
+	</dependencies>
92
+</project>

+ 22 - 0
spring5-admin/src/main/resources/application.yml

@@ -0,0 +1,22 @@
1
+server:
2
+  port: 8752
3
+
4
+logging:
5
+  level:
6
+    root: INFO
7
+    org.springframework.web: INFO
8
+    org.springframework.security: INFO
9
+#    org.springframework.boot.autoconfigure: DEBUG
10
+
11
+spring:
12
+  thymeleaf:
13
+    cache: false
14
+  redis:
15
+    host: 120.55.124.69
16
+    port: 6280
17
+    password: bbztx123456
18
+    timeout: 5000
19
+  
20
+password:
21
+  salt: k12829WhsvnEV$#03b2n          
22
+  

+ 10 - 29
spring5-auth/spring5-auth-client/pom.xml

@@ -15,43 +15,24 @@
15 15
     </parent>
16 16
     
17 17
 	<dependencies>
18
-	    <!--oauth2认证-->
19
-        <dependency>
20
-            <groupId>org.springframework.cloud</groupId>
21
-            <artifactId>spring-cloud-security</artifactId>
22
-        </dependency>
23
-        <dependency>
24
-            <groupId>org.springframework.security</groupId>
25
-            <artifactId>spring-security-jwt</artifactId>
26
-            <version>RELEASE</version>
27
-        </dependency>
28
-        <dependency>
29
-            <groupId>org.springframework.security</groupId>
30
-            <artifactId>spring-security-oauth2-client</artifactId>
31
-        </dependency>
32
-        <dependency>
33
-            <groupId>org.springframework.security</groupId>
34
-            <artifactId>spring-security-oauth2-jose</artifactId>
35
-        </dependency>
36
-        <dependency>
37
-            <groupId>org.springframework.security</groupId>
38
-            <artifactId>spring-security-config</artifactId>
39
-        </dependency>
40
-        
41
-        <!-- Spring Boot Web 依赖 -->
18
+	    <!-- Spring Boot 响应式 Redis 依赖 -->
42 19
         <dependency>
43 20
             <groupId>org.springframework.boot</groupId>
44
-            <artifactId>spring-boot-starter-webflux</artifactId>
21
+            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
45 22
         </dependency>
46 23
         
24
+	    <!-- shrio -->
47 25
         <dependency>
48
-            <groupId>org.springframework.boot</groupId>
49
-            <artifactId>spring-boot-starter-thymeleaf</artifactId>
26
+            <groupId>org.apache.shiro</groupId>
27
+            <artifactId>shiro-spring-boot-web-starter</artifactId>
28
+            <version>1.4.0</version>
50 29
         </dependency>
51 30
         
31
+        <!-- jwt -->
52 32
         <dependency>
53
-            <groupId>org.thymeleaf.extras</groupId>
54
-            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
33
+            <groupId>com.auth0</groupId>
34
+            <artifactId>java-jwt</artifactId>
35
+            <version>3.2.0</version>
55 36
         </dependency>
56 37
 		
57 38
 	</dependencies>

+ 0 - 145
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/config/AuthorizationServerConfig.java

@@ -1,145 +0,0 @@
1
-package com.yaozhitech.spring5.config;
2
-
3
-import org.springframework.context.annotation.Configuration;
4
-
5
-@Configuration
6
-public class AuthorizationServerConfig {
7
-	
8
-//	@Bean
9
-//	SecurityWebFilterChain configure(ServerHttpSecurity http) throws Exception {
10
-//	    http
11
-//	        // ...
12
-//	        .oauth2Client(withDefaults());
13
-//	    return http.build();
14
-//	}
15
-
16
-//    @Autowired
17
-//    @Qualifier("authenticationManagerBean")
18
-//    private AuthenticationManager authenticationManager;
19
-//
20
-//    @Qualifier("dataSource")
21
-//    @Autowired
22
-//    DataSource dataSource;
23
-//
24
-//    @Autowired
25
-//    @Qualifier("userDetailsService")
26
-//    UserDetailsService userDetailsService;
27
-//
28
-//    /**
29
-//     * jwt 对称加密密钥
30
-//     */
31
-//    @Value("${spring.security.oauth2.jwt.signingKey}")
32
-//    private String signingKey;
33
-//
34
-//    @Override
35
-//    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
36
-//        // 支持将client参数放在header或body中
37
-//        oauthServer.allowFormAuthenticationForClients();
38
-//        oauthServer.tokenKeyAccess("isAuthenticated()")
39
-//                .checkTokenAccess("permitAll()");
40
-//    }
41
-//
42
-//    @Override
43
-//    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
44
-//        // 配置客户端信息,从数据库中读取,对应oauth_client_details表
45
-//        clients.jdbc(dataSource);
46
-//    }
47
-//
48
-//    @Override
49
-//    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
50
-//        // 配置token的数据源、自定义的tokenServices等信息,配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
51
-//        endpoints.tokenStore(tokenStore())
52
-//                .authorizationCodeServices(authorizationCodeServices())
53
-//                .approvalStore(approvalStore())
54
-//                .exceptionTranslator(customExceptionTranslator())
55
-//                .tokenEnhancer(tokenEnhancerChain())
56
-//                .authenticationManager(authenticationManager)
57
-//                .userDetailsService(userDetailsService)
58
-//                //update by joe_chen add  granter
59
-//                .tokenGranter(tokenGranter(endpoints));
60
-//
61
-//    }
62
-//
63
-//    /**
64
-//     * 自定义OAuth2异常处理
65
-//     *
66
-//     * @return CustomWebResponseExceptionTranslator
67
-//     */
68
-//    @Bean
69
-//    public WebResponseExceptionTranslator<OAuth2Exception> customExceptionTranslator() {
70
-//        return new CustomWebResponseExceptionTranslator();
71
-//    }
72
-//
73
-//    /**
74
-//     * 授权信息持久化实现
75
-//     *
76
-//     * @return JdbcApprovalStore
77
-//     */
78
-//    @Bean
79
-//    public ApprovalStore approvalStore() {
80
-//        return new JdbcApprovalStore(dataSource);
81
-//    }
82
-//
83
-//    /**
84
-//     * 授权码模式持久化授权码code
85
-//     *
86
-//     * @return JdbcAuthorizationCodeServices
87
-//     */
88
-//    @Bean
89
-//    protected AuthorizationCodeServices authorizationCodeServices() {
90
-//        // 授权码存储等处理方式类,使用jdbc,操作oauth_code表
91
-//        return new JdbcAuthorizationCodeServices(dataSource);
92
-//    }
93
-//
94
-//    /**
95
-//     * token的持久化
96
-//     *
97
-//     * @return JwtTokenStore
98
-//     */
99
-//    @Bean
100
-//    public TokenStore tokenStore() {
101
-//        return new JwtTokenStore(accessTokenConverter());
102
-//    }
103
-//
104
-//    /**
105
-//     * 自定义token
106
-//     *
107
-//     * @return tokenEnhancerChain
108
-//     */
109
-//    @Bean
110
-//    public TokenEnhancerChain tokenEnhancerChain() {
111
-//        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
112
-//        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));
113
-//        return tokenEnhancerChain;
114
-//    }
115
-//
116
-//    /**
117
-//     * jwt token的生成配置
118
-//     *
119
-//     * @return
120
-//     */
121
-//    @Bean
122
-//    public JwtAccessTokenConverter accessTokenConverter() {
123
-//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
124
-//        converter.setSigningKey(signingKey);
125
-//        return converter;
126
-//    }
127
-//
128
-//    /**
129
-//     * 配置自定义的granter,手机号验证码登陆
130
-//     *
131
-//     * @param endpoints
132
-//     * @return
133
-//     * @auth joe_chen
134
-//     */
135
-//    public TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
136
-//        List<TokenGranter> granters = Lists.newArrayList(endpoints.getTokenGranter());
137
-//        granters.add(new MobileTokenGranter(
138
-//                authenticationManager,
139
-//                endpoints.getTokenServices(),
140
-//                endpoints.getClientDetailsService(),
141
-//                endpoints.getOAuth2RequestFactory()));
142
-//        return new CompositeTokenGranter(granters);
143
-//    }
144
-
145
-}

+ 139 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/config/ShiroConfiguration.java

@@ -0,0 +1,139 @@
1
+package com.yaozhitech.spring5.config;
2
+
3
+import java.util.Arrays;
4
+import java.util.HashMap;
5
+import java.util.Map;
6
+
7
+import javax.servlet.DispatcherType;
8
+import javax.servlet.Filter;
9
+
10
+import org.apache.shiro.authc.Authenticator;
11
+import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
12
+import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
13
+import org.apache.shiro.authz.AuthorizationException;
14
+import org.apache.shiro.mgt.SecurityManager;
15
+import org.apache.shiro.mgt.SessionStorageEvaluator;
16
+import org.apache.shiro.realm.Realm;
17
+import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
18
+import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
19
+import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
20
+import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
21
+import org.springframework.beans.factory.annotation.Value;
22
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
23
+import org.springframework.context.annotation.Bean;
24
+import org.springframework.context.annotation.Configuration;
25
+import org.springframework.http.HttpStatus;
26
+import org.springframework.ui.Model;
27
+import org.springframework.web.bind.annotation.ExceptionHandler;
28
+import org.springframework.web.bind.annotation.ResponseStatus;
29
+
30
+import com.yaozhitech.spring5.filter.AnyRolesAuthorizationFilter;
31
+import com.yaozhitech.spring5.filter.JwtAuthFilter;
32
+import com.yaozhitech.spring5.jwt.JWTShiroRealm;
33
+import com.yaozhitech.spring5.service.UserService;
34
+
35
+@Configuration
36
+public class ShiroConfiguration {
37
+	
38
+	@Value("${password.salt}")
39
+	private String encryptSalt;
40
+
41
+	/**
42
+	 * 注册shiro的Filter,拦截请求
43
+	 */
44
+	@Bean
45
+    public FilterRegistrationBean<Filter> filterRegistrationBean(SecurityManager securityManager,UserService userService) throws Exception{
46
+        FilterRegistrationBean<Filter> filterRegistration = new FilterRegistrationBean<Filter>();
47
+        filterRegistration.setFilter((Filter)shiroFilter(securityManager, userService).getObject());
48
+        filterRegistration.addInitParameter("targetFilterLifecycle", "true");
49
+        filterRegistration.setAsyncSupported(true);
50
+        filterRegistration.setEnabled(true);
51
+        filterRegistration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
52
+
53
+        return filterRegistration;
54
+    }
55
+
56
+    @Bean
57
+    public Authenticator authenticator(UserService userService) {
58
+        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
59
+        authenticator.setRealms(Arrays.asList(jwtShiroRealm(userService)));
60
+        authenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
61
+        return authenticator;
62
+    }
63
+
64
+	/**
65
+	 * 禁用session, 不保存用户登录状态。保证每次请求都重新认证。
66
+	 * 需要注意的是,如果用户代码里调用Subject.getSession()还是可以用session,如果要完全禁用,要配合下面的noSessionCreation的Filter来实现
67
+	 */
68
+    @Bean
69
+    protected SessionStorageEvaluator sessionStorageEvaluator(){
70
+        DefaultWebSessionStorageEvaluator sessionStorageEvaluator = new DefaultWebSessionStorageEvaluator();
71
+        sessionStorageEvaluator.setSessionStorageEnabled(false);
72
+        return sessionStorageEvaluator;
73
+    }
74
+
75
+    /**
76
+          * 用于JWT token认证的realm
77
+     */
78
+    @Bean("jwtRealm")
79
+    public Realm jwtShiroRealm(UserService userService) {
80
+        JWTShiroRealm myShiroRealm = new JWTShiroRealm(userService);
81
+        return myShiroRealm;
82
+    }
83
+
84
+    /**
85
+          * 设置过滤器,将自定义的Filter加入
86
+     */
87
+    @Bean("shiroFilter")
88
+    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager, UserService userService) {
89
+    	ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
90
+        factoryBean.setSecurityManager(securityManager);
91
+        Map<String, Filter> filterMap = factoryBean.getFilters();
92
+        filterMap.put("authcToken", createAuthFilter(userService));
93
+//        filterMap.put("anyRole", createRolesFilter());
94
+        factoryBean.setFilters(filterMap);
95
+        factoryBean.setFilterChainDefinitionMap(shiroFilterChainDefinition().getFilterChainMap());
96
+
97
+        return factoryBean;
98
+    }
99
+
100
+    @Bean
101
+    protected ShiroFilterChainDefinition shiroFilterChainDefinition() {
102
+        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
103
+//        chainDefinition.addPathDefinition("/login", "noSessionCreation,anon");  //login不做认证,noSessionCreation的作用是用户在操作session时会抛异常
104
+//        chainDefinition.addPathDefinition("/logout", "noSessionCreation,authcToken[permissive]"); //做用户认证,permissive参数的作用是当token无效时也允许请求访问,不会返回鉴权未通过的错误
105
+//        chainDefinition.addPathDefinition("/image/**", "anon");
106
+//        chainDefinition.addPathDefinition("/admin/**", "noSessionCreation,authcToken,anyRole[admin,manager]"); //只允许admin或manager角色的用户访问
107
+        chainDefinition.addPathDefinition("/article/list", "noSessionCreation,authcToken");
108
+        chainDefinition.addPathDefinition("/admin/**", "noSessionCreation,authcToken");
109
+//        chainDefinition.addPathDefinition("/article/*", "noSessionCreation,authcToken[permissive]");
110
+        chainDefinition.addPathDefinition("/**", "noSessionCreation,authcToken"); // 默认进行用户鉴权
111
+        return chainDefinition;
112
+    }
113
+
114
+   //注意不要加@Bean注解,不然spring会自动注册成filter
115
+    protected JwtAuthFilter createAuthFilter(UserService userService){
116
+        return new JwtAuthFilter(userService);
117
+    }
118
+
119
+//    protected AnyRolesAuthorizationFilter createRolesFilter(){
120
+//        return new AnyRolesAuthorizationFilter();
121
+//    }
122
+    
123
+    @ExceptionHandler(AuthorizationException.class)
124
+    @ResponseStatus(HttpStatus.FORBIDDEN)
125
+    public String handleException(AuthorizationException e, Model model) {
126
+
127
+        // you could return a 404 here instead (this is how github handles 403, so the user does NOT know there is a
128
+        // resource at that location)
129
+//        log.debug("AuthorizationException was thrown", e);
130
+
131
+        Map<String, Object> map = new HashMap<String, Object>();
132
+        map.put("status", HttpStatus.FORBIDDEN.value());
133
+        map.put("message", "No message available");
134
+        model.addAttribute("errors", map);
135
+
136
+        return "error";
137
+    }
138
+    
139
+}

+ 0 - 23
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/controller/LoginController.java

@@ -1,23 +0,0 @@
1
-package com.yaozhitech.spring5.controller;
2
-
3
-import org.springframework.security.core.annotation.AuthenticationPrincipal;
4
-import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
5
-import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
6
-import org.springframework.security.oauth2.core.user.OAuth2User;
7
-import org.springframework.stereotype.Controller;
8
-import org.springframework.ui.Model;
9
-import org.springframework.web.bind.annotation.GetMapping;
10
-
11
-@Controller
12
-public class LoginController {
13
-
14
-	@GetMapping("/")
15
-	public String index(Model model,
16
-						@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
17
-						@AuthenticationPrincipal OAuth2User oauth2User) {
18
-		model.addAttribute("userName", oauth2User.getName());
19
-		model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
20
-		model.addAttribute("userAttributes", oauth2User.getAttributes());
21
-		return "index";
22
-	}
23
-}

+ 16 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/dto/UserDto.java

@@ -0,0 +1,16 @@
1
+package com.yaozhitech.spring5.dto;
2
+
3
+import java.util.List;
4
+
5
+import lombok.Data;
6
+
7
+@Data
8
+public class UserDto {
9
+
10
+	private String username;
11
+    private char[] password;
12
+    private String encryptPwd;
13
+    private Long userId;
14
+    private String salt;
15
+    private List<String> roles;
16
+}

+ 43 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/filter/AnyRolesAuthorizationFilter.java

@@ -0,0 +1,43 @@
1
+package com.yaozhitech.spring5.filter;
2
+
3
+import java.io.IOException;
4
+
5
+import javax.servlet.ServletRequest;
6
+import javax.servlet.ServletResponse;
7
+import javax.servlet.http.HttpServletResponse;
8
+
9
+import org.apache.shiro.subject.Subject;
10
+import org.apache.shiro.web.filter.authz.AuthorizationFilter;
11
+import org.apache.shiro.web.util.WebUtils;
12
+import org.springframework.http.HttpStatus;
13
+
14
+public class AnyRolesAuthorizationFilter  extends AuthorizationFilter {
15
+	
16
+	@Override
17
+    protected void postHandle(ServletRequest request, ServletResponse response){
18
+	}
19
+
20
+    @Override
21
+    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
22
+        Subject subject = getSubject(servletRequest, servletResponse);
23
+        String[] rolesArray = (String[]) mappedValue;
24
+        if (rolesArray == null || rolesArray.length == 0) { //没有角色限制,有权限访问
25
+            return true;
26
+        }
27
+        for (String role : rolesArray) {
28
+            if (subject.hasRole(role)) //若当前用户是rolesArray中的任何一个,则有权限访问
29
+                return true;
30
+        }
31
+        return false;
32
+    }
33
+
34
+    @Override
35
+    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
36
+        HttpServletResponse httpResponse = WebUtils.toHttp(response);
37
+        httpResponse.setCharacterEncoding("UTF-8");
38
+        httpResponse.setContentType("application/json;charset=utf-8");
39
+        httpResponse.setStatus(HttpStatus.UNAUTHORIZED.ordinal());
40
+        return false;
41
+    }
42
+
43
+}

+ 157 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/filter/JwtAuthFilter.java

@@ -0,0 +1,157 @@
1
+package com.yaozhitech.spring5.filter;
2
+
3
+
4
+import java.time.LocalDateTime;
5
+import java.time.ZoneId;
6
+import java.util.Date;
7
+
8
+import javax.servlet.ServletRequest;
9
+import javax.servlet.ServletResponse;
10
+import javax.servlet.http.HttpServletRequest;
11
+import javax.servlet.http.HttpServletResponse;
12
+
13
+import org.apache.shiro.authc.AuthenticationException;
14
+import org.apache.shiro.authc.AuthenticationToken;
15
+import org.apache.shiro.subject.Subject;
16
+import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
17
+import org.apache.shiro.web.util.WebUtils;
18
+import org.springframework.beans.factory.annotation.Value;
19
+import org.springframework.util.StringUtils;
20
+import org.springframework.web.bind.annotation.RequestMethod;
21
+
22
+import com.yaozhitech.spring5.dto.UserDto;
23
+import com.yaozhitech.spring5.jwt.JWTToken;
24
+import com.yaozhitech.spring5.service.UserService;
25
+import com.yaozhitech.spring5.utils.JwtUtils;
26
+
27
+import lombok.extern.slf4j.Slf4j;
28
+
29
+@Slf4j
30
+public class JwtAuthFilter extends AuthenticatingFilter {
31
+	
32
+	@Value("${jwt.header}")
33
+    private String tokenHeader;
34
+
35
+    @Value("${jwt.tokenHead}")
36
+    private String tokenHead;
37
+
38
+    private static final int tokenRefreshInterval = 300;
39
+    private UserService userService;
40
+
41
+    public JwtAuthFilter(UserService userService){
42
+        this.userService = userService;
43
+        this.setLoginUrl("/login");
44
+    }
45
+
46
+    @Override
47
+    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
48
+        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
49
+        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) //对于OPTION请求做拦截,不做token校验
50
+            return false;
51
+
52
+        return super.preHandle(request, response);
53
+    }
54
+
55
+    @Override
56
+    protected void postHandle(ServletRequest request, ServletResponse response){
57
+        this.fillCorsHeader(WebUtils.toHttp(request), WebUtils.toHttp(response));
58
+        request.setAttribute("jwtShiroFilter.FILTERED", true);
59
+    }
60
+
61
+    /**
62
+          * 父类会在请求进入拦截器后调用该方法,返回true则继续,返回false则会调用onAccessDenied()。这里在不通过时,还调用了isPermissive()方法,
63
+     */
64
+    @Override
65
+    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
66
+        if(this.isLoginRequest(request, response))
67
+            return true;
68
+
69
+        Boolean afterFiltered = (Boolean)(request.getAttribute("jwtShiroFilter.FILTERED"));
70
+        if(afterFiltered != null && afterFiltered)
71
+        	return true;
72
+        
73
+        boolean allowed = false;
74
+        try {
75
+            allowed = executeLogin(request, response);
76
+        } catch(IllegalStateException e){ //not found any token
77
+            log.error("Not found any token", e);
78
+        }catch (Exception e) {
79
+            log.error("Error occurs when login", e);
80
+        }
81
+        return allowed;// || super.isPermissive(mappedValue);
82
+    }
83
+
84
+    /**
85
+          * 这里重写了父类的方法,使用我们自己定义的Token类,提交给shiro。这个方法返回null的话会直接抛出异常,进入isAccessAllowed()的异常处理逻辑。
86
+     */
87
+    @Override
88
+    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
89
+        String jwtToken = getAuthzHeader(servletRequest);
90
+        if(!StringUtils.isEmpty(jwtToken)&&!JwtUtils.isTokenExpired(jwtToken))
91
+            return new JWTToken(jwtToken);
92
+
93
+        return null;
94
+    }
95
+
96
+    @Override
97
+    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
98
+        
99
+    	HttpServletRequest httpServletRequest = WebUtils.toHttp(servletRequest);
100
+        HttpServletResponse httpResponse = WebUtils.toHttp(servletResponse);
101
+        // 返回401
102
+        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
103
+        httpResponse.getOutputStream().println("401 UNAUTHORIZED");
104
+        // 设置响应码为401或者直接输出消息
105
+        String url = httpServletRequest.getRequestURI();
106
+        log.error("onAccessDenied url:{}", url);
107
+
108
+    	return false;
109
+    }
110
+
111
+    /**
112
+          *  如果Shiro Login认证成功,会进入该方法,等同于用户名密码登录成功,我们这里还判断了是否要刷新Token
113
+     */
114
+    @Override
115
+    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
116
+        HttpServletResponse httpResponse = WebUtils.toHttp(response);
117
+        String newToken = null;
118
+        if(token instanceof JWTToken){
119
+            JWTToken jwtToken = (JWTToken)token;
120
+            UserDto user = (UserDto) subject.getPrincipal();
121
+            boolean shouldRefresh = shouldTokenRefresh(JwtUtils.getIssuedAt(jwtToken.getToken()));
122
+            if(shouldRefresh) {
123
+                newToken = userService.generateJwtToken(user.getUsername());
124
+            }
125
+        }
126
+        if(!StringUtils.isEmpty(newToken))
127
+            httpResponse.setHeader("x-auth-token", newToken);
128
+
129
+        return true;
130
+    }
131
+
132
+    @Override
133
+    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
134
+        log.error("Validate token fail, token:{}, error:{}", token.toString(), e.getMessage());
135
+        return false;
136
+    }
137
+
138
+    protected String getAuthzHeader(ServletRequest request) {
139
+        HttpServletRequest httpRequest = WebUtils.toHttp(request);
140
+        String header = httpRequest.getHeader("x-auth-token");
141
+        if (StringUtils.startsWithIgnoreCase(header, "Bearer ")) {
142
+			return StringUtils.replace(header, "Bearer ", "");
143
+		}
144
+        return header;
145
+    }
146
+
147
+    protected boolean shouldTokenRefresh(Date issueAt){
148
+        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
149
+        return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
150
+    }
151
+
152
+    protected void fillCorsHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
153
+        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
154
+        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,HEAD");
155
+        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
156
+    }
157
+}

+ 41 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTCredentialsMatcher.java

@@ -0,0 +1,41 @@
1
+package com.yaozhitech.spring5.jwt;
2
+
3
+import java.io.UnsupportedEncodingException;
4
+
5
+import org.apache.shiro.authc.AuthenticationInfo;
6
+import org.apache.shiro.authc.AuthenticationToken;
7
+import org.apache.shiro.authc.credential.CredentialsMatcher;
8
+
9
+import com.auth0.jwt.JWT;
10
+import com.auth0.jwt.JWTVerifier;
11
+import com.auth0.jwt.algorithms.Algorithm;
12
+import com.auth0.jwt.exceptions.JWTVerificationException;
13
+import com.yaozhitech.spring5.dto.UserDto;
14
+
15
+import lombok.extern.slf4j.Slf4j;
16
+
17
+@Slf4j
18
+public class JWTCredentialsMatcher implements CredentialsMatcher {
19
+	
20
+    @Override
21
+    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
22
+        String token = (String) authenticationToken.getCredentials();
23
+        Object stored = authenticationInfo.getCredentials();
24
+        String salt = stored.toString();
25
+
26
+        UserDto user = (UserDto)authenticationInfo.getPrincipals().getPrimaryPrincipal();
27
+        try {
28
+            Algorithm algorithm = Algorithm.HMAC256(salt);
29
+            JWTVerifier verifier = JWT.require(algorithm)
30
+                    .withClaim("username", user.getUsername())
31
+                    .build();
32
+            verifier.verify(token);
33
+            return true;
34
+        } catch (UnsupportedEncodingException | JWTVerificationException e) {
35
+            log.error("Token Error:{}", e.getMessage());
36
+        }
37
+
38
+        return false;
39
+    }
40
+
41
+}

+ 58 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTShiroRealm.java

@@ -0,0 +1,58 @@
1
+package com.yaozhitech.spring5.jwt;
2
+
3
+import org.apache.shiro.authc.AuthenticationException;
4
+import org.apache.shiro.authc.AuthenticationInfo;
5
+import org.apache.shiro.authc.AuthenticationToken;
6
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
7
+import org.apache.shiro.authz.AuthorizationInfo;
8
+import org.apache.shiro.authz.SimpleAuthorizationInfo;
9
+import org.apache.shiro.realm.AuthorizingRealm;
10
+import org.apache.shiro.subject.PrincipalCollection;
11
+
12
+import com.yaozhitech.spring5.dto.UserDto;
13
+import com.yaozhitech.spring5.service.UserService;
14
+import com.yaozhitech.spring5.utils.JwtUtils;
15
+
16
+
17
+/**
18
+ * 自定义身份认证
19
+ * 基于HMAC( 散列消息认证码)的控制域
20
+ */
21
+
22
+public class JWTShiroRealm extends AuthorizingRealm {
23
+
24
+    protected UserService userService;
25
+
26
+    public JWTShiroRealm(UserService userService){
27
+        this.userService = userService;
28
+        this.setCredentialsMatcher(new JWTCredentialsMatcher());
29
+    }
30
+
31
+    @Override
32
+    public boolean supports(AuthenticationToken token) {
33
+        return token instanceof JWTToken;
34
+    }
35
+
36
+    /**
37
+     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
38
+     * 默认使用此方法进行用户名正确与否验证,错误抛出异常即可。
39
+     */
40
+    @Override
41
+    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {    
42
+        JWTToken jwtToken = (JWTToken) authcToken;
43
+        String token = jwtToken.getToken();
44
+        
45
+        UserDto user = userService.getJwtTokenInfo(JwtUtils.getUsername(token));
46
+        if(user == null)
47
+            throw new AuthenticationException("token过期,请重新登录");
48
+
49
+        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getSalt(), "jwtRealm");
50
+
51
+        return authenticationInfo;
52
+    }
53
+
54
+    @Override
55
+    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
56
+        return new SimpleAuthorizationInfo();
57
+    }
58
+}

+ 44 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/jwt/JWTToken.java

@@ -0,0 +1,44 @@
1
+package com.yaozhitech.spring5.jwt;
2
+
3
+import org.apache.shiro.authc.HostAuthenticationToken;
4
+
5
+import lombok.Data;
6
+
7
+@Data
8
+public class JWTToken implements HostAuthenticationToken {
9
+
10
+	/**
11
+	 * 
12
+	 */
13
+	private static final long serialVersionUID = -6910437116441110747L;
14
+	
15
+	private String token;
16
+    private String host;
17
+    
18
+    public JWTToken(String token) {
19
+        this(token, null);
20
+    }
21
+
22
+    public JWTToken(String token, String host) {
23
+        this.token = token;
24
+        this.host = host;
25
+    }
26
+    
27
+	@Override
28
+	public Object getPrincipal() {
29
+		return token;
30
+	}
31
+	@Override
32
+	public Object getCredentials() {
33
+		return token;
34
+	}
35
+	@Override
36
+	public String getHost() {
37
+		return host;
38
+	}
39
+    
40
+	@Override
41
+    public String toString(){
42
+        return token + ':' + host;
43
+    }
44
+}

+ 82 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/service/UserService.java

@@ -0,0 +1,82 @@
1
+package com.yaozhitech.spring5.service;
2
+
3
+import java.time.Duration;
4
+import java.util.Arrays;
5
+import java.util.List;
6
+
7
+import org.apache.shiro.crypto.hash.Sha256Hash;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.beans.factory.annotation.Value;
10
+import org.springframework.data.redis.core.StringRedisTemplate;
11
+import org.springframework.stereotype.Service;
12
+
13
+import com.yaozhitech.spring5.dto.UserDto;
14
+import com.yaozhitech.spring5.utils.JwtUtils;
15
+
16
+@Service
17
+public class UserService {
18
+
19
+	@Value("${password.salt}")
20
+	private String encryptSalt;
21
+
22
+	@Autowired
23
+	private StringRedisTemplate redisTemplate;
24
+
25
+	/**
26
+	 * 保存user登录信息,返回token
27
+	 * 
28
+	 * @param userDto
29
+	 */
30
+	public String generateJwtToken(String username) {
31
+		String salt = JwtUtils.generateSalt();
32
+		redisTemplate.opsForValue().set("token:"+username, salt, Duration.ofSeconds(3600));
33
+		return JwtUtils.sign(username, salt, 3600); // 生成jwt token,设置过期时间为1小时
34
+	}
35
+
36
+	/**
37
+	 * 获取上次token生成时的salt值和登录用户信息
38
+	 * 
39
+	 * @param username
40
+	 * @return
41
+	 */
42
+	public UserDto getJwtTokenInfo(String username) {
43
+		String salt = redisTemplate.opsForValue().get("token:"+username);
44
+		UserDto user = getUserInfo(username);
45
+		user.setSalt(salt);
46
+		return user;
47
+	}
48
+
49
+	/**
50
+	 * 清除token信息
51
+	 * 
52
+	 * @param userName 登录用户名
53
+	 * @param terminal 登录终端
54
+	 */
55
+	public void deleteLoginInfo(String username) {
56
+		redisTemplate.delete("token:"+username);
57
+	}
58
+
59
+	/**
60
+	 * 获取数据库中保存的用户信息,主要是加密后的密码
61
+	 * 
62
+	 * @param userName
63
+	 * @return
64
+	 */
65
+	public UserDto getUserInfo(String userName) {
66
+		UserDto user = new UserDto();
67
+		user.setUserId(1L);
68
+		user.setUsername("admin");
69
+		user.setEncryptPwd(new Sha256Hash("123456", encryptSalt).toHex());
70
+		return user;
71
+	}
72
+
73
+	/**
74
+	 * 获取用户角色列表,强烈建议从缓存中获取
75
+	 * 
76
+	 * @param userId
77
+	 * @return
78
+	 */
79
+	public List<String> getUserRoles(Long userId) {
80
+		return Arrays.asList("admin");
81
+	}
82
+}

+ 82 - 0
spring5-auth/spring5-auth-client/src/main/java/com/yaozhitech/spring5/utils/JwtUtils.java

@@ -0,0 +1,82 @@
1
+package com.yaozhitech.spring5.utils;
2
+
3
+import java.io.UnsupportedEncodingException;
4
+import java.util.Calendar;
5
+import java.util.Date;
6
+
7
+import org.apache.shiro.crypto.SecureRandomNumberGenerator;
8
+
9
+import com.auth0.jwt.JWT;
10
+import com.auth0.jwt.algorithms.Algorithm;
11
+import com.auth0.jwt.exceptions.JWTDecodeException;
12
+import com.auth0.jwt.interfaces.DecodedJWT;
13
+
14
+public class JwtUtils {
15
+
16
+	/**
17
+          * 获得token中的信息无需secret解密也能获得
18
+     * @return token中包含的签发时间
19
+     */
20
+    public static Date getIssuedAt(String token) {
21
+        try {
22
+            DecodedJWT jwt = JWT.decode(token);
23
+            return jwt.getIssuedAt();
24
+        } catch (JWTDecodeException e) {
25
+            return null;
26
+        }
27
+    }
28
+
29
+    /**
30
+     * 获得token中的信息无需secret解密也能获得
31
+     * @return token中包含的用户名
32
+     */
33
+    public static String getUsername(String token) {
34
+        try {
35
+            DecodedJWT jwt = JWT.decode(token);
36
+            return jwt.getClaim("username").asString();
37
+        } catch (JWTDecodeException e) {
38
+            return null;
39
+        }
40
+    }
41
+
42
+    /**
43
+     * 生成签名,expireTime后过期
44
+     * @param username 用户名
45
+     * @param time 过期时间s
46
+     * @return 加密的token
47
+     */
48
+    public static String sign(String username, String salt, long time) {
49
+        try {
50
+            Date date = new Date(System.currentTimeMillis()+time*1000);
51
+            Algorithm algorithm = Algorithm.HMAC256(salt);
52
+            // 附带username信息
53
+            return JWT.create()
54
+                    .withClaim("username", username)
55
+                    .withExpiresAt(date)
56
+                    .withIssuedAt(new Date())
57
+                    .sign(algorithm);
58
+        } catch (UnsupportedEncodingException e) {
59
+            return null;
60
+        }
61
+    }
62
+
63
+    /**
64
+     * token是否过期
65
+     * @return true:过期
66
+     */
67
+    public static boolean isTokenExpired(String token) {
68
+        Date now = Calendar.getInstance().getTime();
69
+        DecodedJWT jwt = JWT.decode(token);
70
+        return jwt.getExpiresAt().before(now);
71
+    }
72
+
73
+    /**
74
+     * 生成随机盐,长度32位
75
+     * @return
76
+     */
77
+    public static String generateSalt(){
78
+        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
79
+        String hex = secureRandom.nextBytes(16).toHex();
80
+        return hex;
81
+    }
82
+}

+ 15 - 15
spring5-auth/spring5-auth-client/src/main/resources/application.yml

@@ -18,19 +18,19 @@ spring:
18 18
           github:
19 19
             client-id: 7b9c752378a3d95a4529
20 20
             client-secret: f635d8c7d44a50bdf12f2055e7e44b2bbc9c1043
21
-          google:
22
-            client-id: your-app-client-id
23
-            client-secret: your-app-client-secret
24
-          okta:
25
-            client-id: fooClientIdPassword
26
-            client-secret: secret
27
-            scopes: read,foo
28
-            authorization-grant-type: authorization_code
29
-            redirect-uri-template: http://localhost:8080/login/oauth2/code/custom
30
-        provider:
31
-          okta:
32
-            authorization-uri: http://localhost:8081/spring-security-oauth-server/oauth/authorize
33
-            token-uri: http://localhost:8081/spring-security-oauth-server/oauth/token
34
-            user-info-uri: http://localhost:8088/spring-security-oauth-resource/users/extra
35
-            user-name-attribute: user_name
21
+#           google:
22
+#             client-id: your-app-client-id
23
+#             client-secret: your-app-client-secret
24
+#           okta:
25
+#             client-id: fooClientIdPassword
26
+#             client-secret: secret
27
+#             scopes: read,foo
28
+#             authorization-grant-type: authorization_code
29
+#             redirect-uri-template: http://localhost:8080/login/oauth2/code/custom
30
+#         provider:
31
+#           okta:
32
+#             authorization-uri: http://localhost:8081/spring-security-oauth-server/oauth/authorize
33
+#             token-uri: http://localhost:8081/spring-security-oauth-server/oauth/token
34
+#             user-info-uri: http://localhost:8088/spring-security-oauth-resource/users/extra
35
+#             user-name-attribute: user_name
36 36
             

+ 1 - 7
spring5-auth/spring5-auth-server/src/main/java/com/yaozhitech/spring5/filter/JwtAuthFilter.java

@@ -15,7 +15,6 @@ import org.apache.shiro.authc.AuthenticationToken;
15 15
 import org.apache.shiro.subject.Subject;
16 16
 import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
17 17
 import org.apache.shiro.web.util.WebUtils;
18
-import org.springframework.beans.factory.annotation.Value;
19 18
 import org.springframework.http.HttpStatus;
20 19
 import org.springframework.util.StringUtils;
21 20
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -30,13 +29,8 @@ import lombok.extern.slf4j.Slf4j;
30 29
 @Slf4j
31 30
 public class JwtAuthFilter extends AuthenticatingFilter {
32 31
 	
33
-	@Value("${jwt.header}")
34
-    private String tokenHeader;
35
-
36
-    @Value("${jwt.tokenHead}")
37
-    private String tokenHead;
38
-
39 32
     private static final int tokenRefreshInterval = 300;
33
+    
40 34
     private UserService userService;
41 35
 
42 36
     public JwtAuthFilter(UserService userService){