springSecurity整合oauth2
# springSecurity整合oauth2
## 引入依赖
```xml
<dependencies>
<!-- 这个是自定义通用的工具类等 -->
<dependency>
<groupId>com.bs</groupId>
<artifactId>bs-framework-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.bs</groupId>
<artifactId>bs-start-mybatisplus</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
```
## 配置授权服务 AuthorizationServerConfig
```java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource(name="clientDetailsServiceImpl")
private ClientDetailsServiceImpl clientDetailsServiceImpl;
@Resource
private UserDetailsServiceImpl userDetailsServiceImpl;
@Resource
private AuthenticationManager authenticationManager;
/**
* 配置客户端
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsServiceImpl);
}
/**
* 配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
//使用密码模式需要配置
.authenticationManager(authenticationManager)
//指定token存储到内存 可改成redis
.tokenStore(new InMemoryTokenStore())
//refresh_token是否重复使用
.reuseRefreshTokens(false)
//刷新令牌授权包含对用户信息的检查
.userDetailsService(userDetailsServiceImpl)
//支持GET,POST请求
.allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.allowFormAuthenticationForClients();
}
```
Spring Security对OAuth2提供了默认可访问端点,即URL
/oauth/authorize :申请授权码code,涉及类 AuthorizationEndpoint
/oauth/token :获取令牌token,涉及类 TokenEndpoint
/oauth/check_token :用于资源服务器请求端点来检查令牌是否有效,涉及类 CheckTokenEndpoint
/oauth/confirm_access :用于确认授权提交,涉及类 WhitelabelApprovalEndpoint
/oauth/error :授权错误信息,涉及 WhitelabelErrorEndpoint
/oauth/token_key :提供公有密匙的端点,使用JWT令牌时会使用,涉及类 TokenKeyEndpoint