springsecurity5.8+oauth2.0搭建auth完整服务代码
时间: 2024-09-19 11:07:24 浏览: 73
验证服务:Spring Security + OAuth2.0 + JWT
5星 · 资源好评率100%
Spring Security 5.8版本结合OAuth 2.0可以构建强大的身份验证和授权服务。以下是使用这两个框架搭建完整授权服务的基本步骤:
1. 添加依赖:首先,在你的Maven或Gradle项目中添加Spring Security OAuth2的相关依赖:
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<!-- Gradle (Kotlin) -->
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
```
2. 配置OAuth2客户端:在`application.yml`或`application.properties`中配置客户端ID、秘钥和授权服务器地址:
```yaml
security:
oauth2:
client:
registration:
example:
providerId: your-provider-id
clientId: your-client-id
clientSecret: your-client-secret
authorizationUri: http://your-auth-server/authorize
tokenUrl: http://your-auth-server/token
```
3. 定义Security配置:创建`WebSecurityConfigurerAdapter`并启用OAuth2自动配置:
```java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").authenticated();
http.oauth2Login().successHandler(new CustomAuthenticationSuccessHandler());
}
// 自定义成功处理程序
public class CustomAuthenticationSuccessHandler extends DefaultRedirectStrategy {
// 实现你的登录成功后的逻辑,例如重定向到特定资源
}
}
```
4. 用户认证:如果需要用户注册和登录,可以考虑使用如Spring Boot Actuator等库提供的管理端功能,或者自己实现。
5. 授权访问:对需要保护的API资源添加@PreAuthorize注解,如:
```java
@RestController
@PreAuthorize("#oauth2.hasScope('read')")
public class ProtectedController {
// API方法...
}
```
这里`#oauth2.hasScope('read')`表示只有拥有"read"权限的用户才能访问。
6.
阅读全文