cloud + security+ jwt + oauth2 整合示例
时间: 2023-06-16 15:04:01 浏览: 169
oauth2:spring boot security oauth2 jwt整合,搭建一个SSO单点登录系统,认证服务和资源服务分离.....
这里提供一个基于Spring Boot的Cloud+Security+JWT+OAuth2整合示例:
1. 首先添加依赖:
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
```
2. 在application.yml配置文件中添加以下配置:
```
spring:
security:
oauth2:
client:
registration:
client-id:
client-id: client-id
client-secret: client-secret
scope: read,write
provider: custom-provider
redirect-uri: http://localhost:8080/login/oauth2/code/custom-provider
provider:
custom-provider:
token-uri: http://localhost:8080/oauth/token
authorization-uri: http://localhost:8080/oauth/authorize
user-info-uri: http://localhost:8080/user
user-name-attribute: username
jwt:
secret: mySecretKey
```
3. 创建一个SecurityConfig类来配置security:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorize -> authorize
.antMatchers("/oauth/**").permitAll()
.anyRequest().authenticated()
)
.oauth2Login(oauth2 -> oauth2
.loginPage("/oauth2/authorization/custom-provider")
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withSecretKey(new SecretKeySpec("mySecretKey".getBytes(), SignatureAlgorithm.HS256.getJcaName())).build();
}
}
```
4. 创建一个RestController来测试:
```
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return "Hello World!";
}
@GetMapping("/user")
public Principal user(Principal principal) {
return principal;
}
}
```
5. 运行应用并尝试访问http://localhost:8080/test,应该会跳转到登录页面并要求输入自定义提供程序的凭据。成功登录后,应该会显示“Hello World!”的消息。
阅读全文