Skip to content

Commit c392710

Browse files
author
YunaiV
committed
增加 OAuth2 授权码模式
1 parent 61a6106 commit c392710

File tree

7 files changed

+212
-0
lines changed

7 files changed

+212
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>lab-68</artifactId>
7+
<groupId>cn.iocoder.springboot.labs</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>lab-68-demo02-authorization-server-with-authorization-code</artifactId>
13+
14+
<properties>
15+
<!-- 依赖相关配置 -->
16+
<spring.boot.version>2.2.4.RELEASE</spring.boot.version>
17+
<!-- 插件相关配置 -->
18+
<maven.compiler.target>1.8</maven.compiler.target>
19+
<maven.compiler.source>1.8</maven.compiler.source>
20+
</properties>
21+
22+
<dependencyManagement>
23+
<dependencies>
24+
<dependency>
25+
<groupId>org.springframework.boot</groupId>
26+
<artifactId>spring-boot-starter-parent</artifactId>
27+
<version>${spring.boot.version}</version>
28+
<type>pom</type>
29+
<scope>import</scope>
30+
</dependency>
31+
</dependencies>
32+
</dependencyManagement>
33+
34+
<dependencies>
35+
<!-- 实现对 Spring MVC 的自动配置 -->
36+
<dependency>
37+
<groupId>org.springframework.boot</groupId>
38+
<artifactId>spring-boot-starter-web</artifactId>
39+
</dependency>
40+
41+
<!-- 实现对 Spring Security 的自动配置 -->
42+
<!-- <dependency>-->
43+
<!-- <groupId>org.springframework.boot</groupId>-->
44+
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
45+
<!-- </dependency>-->
46+
47+
<!-- 实现对 Spring Security OAuth2 的自动配置 -->
48+
<dependency>
49+
<groupId>org.springframework.security.oauth.boot</groupId>
50+
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
51+
<version>${spring.boot.version}</version>
52+
</dependency>
53+
</dependencies>
54+
55+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package cn.iocoder.springboot.lab68.authorizationserverdemo;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class AuthorizationServerApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(AuthorizationServerApplication.class, args);
11+
}
12+
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package cn.iocoder.springboot.lab68.authorizationserverdemo.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.authentication.AuthenticationManager;
6+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
7+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
8+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
9+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
10+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
11+
12+
/**
13+
* 授权服务器配置
14+
*/
15+
@Configuration
16+
@EnableAuthorizationServer
17+
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
18+
19+
/**
20+
* 用户认证 Manager
21+
*/
22+
@Autowired
23+
private AuthenticationManager authenticationManager;
24+
25+
@Override
26+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
27+
endpoints.authenticationManager(authenticationManager);
28+
}
29+
30+
@Override
31+
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
32+
oauthServer.checkTokenAccess("isAuthenticated()")
33+
// .tokenKeyAccess("permitAll()")
34+
;
35+
}
36+
37+
@Override
38+
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
39+
clients.inMemory()
40+
.withClient("clientapp").secret("112233") // Client 账号、密码。
41+
.authorizedGrantTypes("authorization_code") // 授权码模式
42+
.redirectUris("http://127.0.0.1:9090/callback") // 配置回调地址,选填。TODO 待修改
43+
.scopes("read_userinfo", "read_contacts") // 可授权的 Scope
44+
// .and().withClient() // 可以继续配置新的 Client
45+
;
46+
}
47+
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package cn.iocoder.springboot.lab68.authorizationserverdemo.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.authentication.AuthenticationManager;
6+
import org.springframework.security.config.BeanIds;
7+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
11+
12+
@Configuration
13+
@EnableWebSecurity
14+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
15+
16+
@Override
17+
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
18+
public AuthenticationManager authenticationManagerBean() throws Exception {
19+
return super.authenticationManagerBean();
20+
}
21+
22+
@Bean
23+
public static NoOpPasswordEncoder passwordEncoder() {
24+
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
25+
}
26+
27+
@Override
28+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
29+
auth.
30+
// 使用内存中的 InMemoryUserDetailsManager
31+
inMemoryAuthentication()
32+
// 不使用 PasswordEncoder 密码编码器
33+
.passwordEncoder(passwordEncoder())
34+
// 配置 yunai 用户
35+
.withUser("yunai").password("1024").roles("USER");
36+
}
37+
38+
// @Override
39+
// protected void configure(HttpSecurity http) throws Exception {
40+
// http
41+
// .authorizeRequests()
42+
// .antMatchers("/oauth/**").permitAll() // 允许无权限访问
43+
// .anyRequest().authenticated()
44+
// .and()
45+
// .formLogin().and()
46+
// .httpBasic();
47+
// }
48+
49+
}

lab-68/lab-68-demo02-resource-server/src/main/java/cn/iocoder/springboot/lab68/resourceserverdemo/config/OAuth2ResourceServerConfig.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ public void configure(HttpSecurity http) throws Exception {
1717
http.authorizeRequests()
1818
// 设置 /login 无需权限访问
1919
.antMatchers("/login").permitAll()
20+
/// 设置 /callback 无需权限访问
21+
.antMatchers("/callback").permitAll()
2022
// 设置其它请求,需要认证后访问
2123
.anyRequest().authenticated()
2224
;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package cn.iocoder.springboot.lab68.resourceserverdemo.controller;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
6+
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
7+
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
8+
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
9+
import org.springframework.security.oauth2.common.OAuth2AccessToken;
10+
import org.springframework.web.bind.annotation.GetMapping;
11+
import org.springframework.web.bind.annotation.RequestMapping;
12+
import org.springframework.web.bind.annotation.RequestParam;
13+
import org.springframework.web.bind.annotation.RestController;
14+
15+
@RestController
16+
@RequestMapping("/")
17+
public class CallbackController {
18+
19+
@Autowired
20+
private OAuth2ClientProperties oauth2ClientProperties;
21+
22+
@Value("${security.oauth2.access-token-uri}")
23+
private String accessTokenUri;
24+
25+
@GetMapping("/callback")
26+
public OAuth2AccessToken login(@RequestParam("code") String code) {
27+
// 创建 ResourceOwnerPasswordResourceDetails 对象
28+
AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();
29+
resourceDetails.setAccessTokenUri(accessTokenUri);
30+
resourceDetails.setClientId(oauth2ClientProperties.getClientId());
31+
resourceDetails.setClientSecret(oauth2ClientProperties.getClientSecret());
32+
// resourceDetails.setPreEstablishedRedirectUri();
33+
// 创建
34+
// 创建 OAuth2RestTemplate 对象
35+
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
36+
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setAuthorizationCode(code); // 设置 code
37+
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setPreservedState("http://127.0.0.1:9090/callback"); // 设置 state
38+
restTemplate.setAccessTokenProvider(new AuthorizationCodeAccessTokenProvider());
39+
// 获取访问令牌
40+
return restTemplate.getAccessToken();
41+
}
42+
43+
44+
}

lab-68/pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
<module>lab-68-demo01-resource-owner-password-credentials-server</module>
1616
<module>lab-68-demo02-resource-server</module>
1717
<module>lab-68-demo02-authorization-server-with-resource-owner-password-credentials</module>
18+
<module>lab-68-demo02-authorization-server-with-authorization-code</module>
1819
</modules>
1920

2021

0 commit comments

Comments
 (0)