Browse Source

用github做oauth2认证

yufeng0528 4 years ago
parent
commit
21a8adacea

+ 10 - 0
spring5-auth/README.md

@@ -0,0 +1,10 @@
1
+# spring5_oauth2.0
2
+
3
+## github 认证
4
+1. [https://www.baeldung.com/spring-oauth-login-webflux](https://www.baeldung.com/spring-oauth-login-webflux)
5
+
6
+
7
+
8
+
9
+
10
+

+ 43 - 1
spring5-auth/pom.xml

@@ -15,7 +15,49 @@
15 15
     </parent>
16 16
     
17 17
 	<dependencies>
18
-	   
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.oauth</groupId> -->
25
+<!--             <artifactId>spring-security-oauth2</artifactId> -->
26
+<!--             <version>[2.2.4,)</version> -->
27
+<!--         </dependency> -->
28
+<!--         <dependency> -->
29
+<!--             <groupId>org.springframework.security</groupId> -->
30
+<!--             <artifactId>spring-security-jwt</artifactId> -->
31
+<!--             <version>RELEASE</version> -->
32
+<!--         </dependency> -->
33
+        <dependency>
34
+            <groupId>org.springframework.security</groupId>
35
+            <artifactId>spring-security-oauth2-client</artifactId>
36
+        </dependency>
37
+<!--         <dependency> -->
38
+<!--             <groupId>org.springframework.security</groupId> -->
39
+<!--             <artifactId>spring-security-oauth2-jose</artifactId> -->
40
+<!--         </dependency> -->
41
+<!--         <dependency> -->
42
+<!--             <groupId>org.springframework.security</groupId> -->
43
+<!--             <artifactId>spring-security-config</artifactId> -->
44
+<!--         </dependency> -->
45
+        
46
+        <!-- Spring Boot Web 依赖 -->
47
+        <dependency>
48
+            <groupId>org.springframework.boot</groupId>
49
+            <artifactId>spring-boot-starter-web</artifactId>
50
+        </dependency>
51
+        
52
+        <dependency>
53
+            <groupId>org.springframework.boot</groupId>
54
+            <artifactId>spring-boot-starter-thymeleaf</artifactId>
55
+        </dependency>
56
+        
57
+        <dependency>
58
+            <groupId>org.thymeleaf.extras</groupId>
59
+            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
60
+        </dependency>
19 61
 		
20 62
 	</dependencies>
21 63
 </project>

+ 12 - 0
spring5-auth/src/main/java/com/yaozhitech/spring5/Oauth2Application.java

@@ -0,0 +1,12 @@
1
+package com.yaozhitech.spring5;
2
+
3
+import org.springframework.boot.SpringApplication;
4
+import org.springframework.boot.autoconfigure.SpringBootApplication;
5
+
6
+
7
+@SpringBootApplication
8
+public class Oauth2Application {
9
+    public static void main(String[] args) {
10
+        SpringApplication.run(Oauth2Application.class, args);
11
+    }
12
+}

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

@@ -0,0 +1,145 @@
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
+}

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

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

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

@@ -0,0 +1,22 @@
1
+server:
2
+  port: 8080
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
+  security:
15
+    oauth2:
16
+      client:
17
+        registration:
18
+          github:
19
+            client-id: 7b9c752378a3d95a4529
20
+            client-secret: f635d8c7d44a50bdf12f2055e7e44b2bbc9c1043
21
+            authorization-grant-type: authorization_code
22
+            scope: read:user,public_repo

+ 34 - 0
spring5-auth/src/main/resources/templates/index.html

@@ -0,0 +1,34 @@
1
+<!DOCTYPE html>
2
+<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
3
+<head>
4
+    <title>Spring Security - OAuth 2.0 Login</title>
5
+    <meta charset="utf-8" />
6
+</head>
7
+<body>
8
+<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()">
9
+    <div style="float:left">
10
+        <span style="font-weight:bold">User: </span><span sec:authentication="name"></span>
11
+    </div>
12
+    <div style="float:none">&nbsp;</div>
13
+    <div style="float:right">
14
+        <form action="#" th:action="@{/logout}" method="post">
15
+            <input type="submit" value="Logout" />
16
+        </form>
17
+    </div>
18
+</div>
19
+<h1>OAuth 2.0 Login with Spring Security</h1>
20
+<div>
21
+    You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>
22
+    via the OAuth 2.0 Client <span style="font-weight:bold" th:text="${clientName}"></span>
23
+</div>
24
+<div>&nbsp;</div>
25
+<div>
26
+    <span style="font-weight:bold">User Attributes:</span>
27
+    <ul>
28
+        <li th:each="userAttribute : ${userAttributes}">
29
+            <span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span>
30
+        </li>
31
+    </ul>
32
+</div>
33
+</body>
34
+</html>

+ 55 - 0
spring5-gateway/README.md

@@ -0,0 +1,55 @@
1
+# spring5_demo1
2
+
3
+spring5_demo
4
+
5
+
6
+spring5 -> webflux ->spring gateway
7
+
8
+## 版本
9
+* 2.2.* -> Hoxton
10
+* 2.1.* -> Greenwich
11
+* 2.0.* -> Finchley
12
+
13
+## 路由配置参考
14
+1. [https://www.jianshu.com/p/86660b8b24c4](https://www.jianshu.com/p/86660b8b24c4)
15
+2. [https://www.jdon.com/51642](https://www.jdon.com/51642)
16
+3.  
17
+
18
+## gateway filter
19
+1. AddRequestHeader 添加header给下流接口
20
+2. AddRequestParameter 
21
+3. AddResponseHeader 
22
+4. DedupeResponseHeader 剔除重复的响应头
23
+5. Hystrix 未来,Hystrix会被Spring Cloud移除掉,取而代之的是Alibaba Sentinel/Resilience4J
24
+6. PrefixPath 为匹配的路由添加前缀
25
+7. PreserveHostHeader
26
+8. RequestRateLimiter
27
+9. RedirectTo
28
+10. RemoveRequestHeader
29
+11. RemoveResponseHeader
30
+12. RewritePath
31
+13. RewriteResponseHeader
32
+14. SaveSession 
33
+15. RequestSize 为后端服务设置收到的最大请求包大小
34
+16. CircuitBreaker
35
+17. ...
36
+
37
+## 全局过滤器
38
+1. ReactiveLoadBalancerClientFilter
39
+2. Gateway Metrics
40
+3. 
41
+
42
+## 单元测试
43
+1. wiremock
44
+2. [https://www.infoq.com/articles/stubbing-mocking-service-virtualization-differences](https://www.infoq.com/articles/stubbing-mocking-service-virtualization-differences/)
45
+
46
+## 其他
47
+1. spring.cloud.gateway.discovery.locator.enabled=true
48
+2. actuator 配置
49
+3. 
50
+
51
+
52
+
53
+
54
+
55
+