一、搭建Oauth2服务器
本次搭建oauth2服务器全程使用IntelliJ IDEA。
1、创建springboot工程
1、初始相关依赖如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
2、创建Authorication
认证中心
1、在config
包下创建AuthoricationServerConfig
配置类,继承AuthorizationServerConfigurerAdapter
类。
2、加上@Configuration
注解 使其成为一个配置类
3、加上@EnableAuthorizationServer
注解 使其作为认证中心
@Configuration
@EnableAuthorizationServer
public class AuthoricationServerConfig extends AuthorizationServerConfigurerAdapter {
}
在该类中主要重写
//配置客户端(应用)信息
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
super.configure(clients);
}
//配置授权服务器端点的属性和增强的功能。
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
}
//配置授权服务器安全信息
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
}
三个方法配置授权服务器认证中心
2.1、配置客户端信息
这里配置哪些客户端可以获得授权、授权范围、授权方式、令牌有效期及刷新令牌有效期等信息,详细代码实现及相关解释如下
/**
* 客户端相关配置
* 2、配置客户端(应用)信息 非用户信息
* 客户端详细信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//super.configure(clients);
// 在内存中存储客户端信息
clients.inMemory()
// 配置客户端Id
.withClient("client")
// 客户端密钥 “{}”为加密方式 noop为不加密
// 现如今Spring Security中密钥的存储格式是“{id}…………” 所以“{}”必要 否则报错:There is no PasswordEncoder mapped for the id “null”
.secret("{noop}123456")
// 配置授权范围 read、write、all
.scopes("all")
// 配置该客户端支持的授权方式
.authorizedGrantTypes("authorization_code","password","client_credentials","refresh_token","implicit")
// token令牌有效期 单位s
.accessTokenValiditySeconds(1800)
// refreshtoken刷新令牌有效期 单位s 一般来说刷新令牌比令牌有效期长 便于使用刷新令牌换取令牌
.refreshTokenValiditySeconds(3600);
// 基本上来说 到这一步就完成了一个客户端的配置了
// 如果想要配置多个客户端 往下使用.and()连接
//.and()
//.withClient()
//.secret()
//.scopes()
//.authorizedGrantTypes()
//.accessTokenValiditySeconds()
//.refreshTokenValiditySeconds();
}
2.2、配置AuthenticationManager
(第一次搭建忽略这一步,后续说明原因)
3、创建webSecurity
配置中心
1、在config
包下创建WebSecurityConfig
配置类,继承WebSecurityConfigurerAdapter
类。
2、加上@Configuration
注解 使其成为一个配置类
3、加上@EnableWebSecurity
注解 使其作为websecurity配置中心