springboot整合oauth2
时间: 2023-04-21 13:03:29 浏览: 210
Spring Boot可以很方便地与OAuth2集成,使得我们可以快速地构建安全的RESTful API。下面是整合OAuth2的步骤:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
```
2. 配置OAuth2
在application.yml文件中添加以下配置:
```
security:
oauth2:
client:
clientId: client
clientSecret: secret
accessTokenUri: http://localhost:808/oauth/token
userAuthorizationUri: http://localhost:808/oauth/authorize
resource:
userInfoUri: http://localhost:808/user
```
3. 配置Security
创建一个Security配置类,继承WebSecurityConfigurerAdapter,并重写configure方法:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.csrf().disable();
}
}
```
4. 配置OAuth2客户端
创建一个OAuth2客户端配置类,继承AuthorizationServerConfigurerAdapter,并重写configure方法:
```
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password", "refresh_token")
.scopes("read", "write")
.accessTokenValiditySeconds(360)
.refreshTokenValiditySeconds(86400);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
```
5. 配置用户认证
创建一个用户认证配置类,继承GlobalAuthenticationConfigurerAdapter,并重写init方法:
```
@Configuration
public class UserConfig extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> {
User user = userRepository.findByUsername(username);
if (user != null) {
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), Collections.emptyList());
} else {
throw new UsernameNotFoundException("User not found");
}
});
}
}
```
6. 创建RESTful API
创建一个RESTful API,使用OAuth2保护它:
```
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
@GetMapping("/user")
public Principal user(Principal principal) {
return principal;
}
}
```
现在,我们可以使用OAuth2保护我们的RESTful API了。我们可以使用以下命令获取访问令牌:
```
curl -X POST \
http://localhost:808/oauth/token \
-H 'Authorization: Basic Y2xpZW50OnNlY3JldA==' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=password&username=user&password=password'
```
然后,我们可以使用以下命令访问受保护的RESTful API:
```
curl -X GET \
http://localhost:808/api/hello \
-H 'Authorization: Bearer <access_token>'
```
以上就是Spring Boot整合OAuth2的步骤。
阅读全文