# 1.授權服務
~~~
@Configuration
@EnableAuthorizationServer // 授權服務
public class AuthorizationConfigurerAdapter extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private TokenStore tokenStore;
/**
* 客戶端
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()// 內存
.withClient("client_id")// 客戶端id
.secret(passwordEncoder.encode("123"))//客戶端密鑰
.resourceIds("add")// 客戶端可以訪問的資源列表
// 申請令牌的方式
.authorizedGrantTypes("password","authorization_code","implicit","client_credentials","refresh_token")
.scopes("adm")// 授權范圍
.autoApprove(false) // 申請授權碼的時候不跳轉到授權
.redirectUris("https://www.baidu.com");//授權碼回調地址
}
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
/**
* 配置令牌端點
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
// 密碼模式需要配置這個
.authenticationManager(authenticationManager)
// 授權碼模式
.authorizationCodeServices(authorizationCodeServices)
//令牌服務 不管什么模式都需要
.tokenServices(authorizationServerTokenServices())
// 允許post提交
.allowedTokenEndpointRequestMethods(HttpMethod.POST);
}
/**
* 令牌安全
*
* @param security
* @throws Exception
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.
// 公鑰公開
tokenKeyAccess("permitAll()")
// 認證token公開
.checkTokenAccess("permitAll()")
// 允許表單申請令牌
.allowFormAuthenticationForClients();
}
@Autowired
public ClientDetailsService clientDetailsService;
// 令牌管理服務
@Bean
public AuthorizationServerTokenServices authorizationServerTokenServices() {
DefaultTokenServices services = new DefaultTokenServices();
services.setClientDetailsService(clientDetailsService);// k+客戶端信息服務
services.setSupportRefreshToken(true);// 是否產生刷新令牌
services.setTokenStore(tokenStore);//令牌存儲策略
services.setAccessTokenValiditySeconds(7200);//令牌有效期 2小時 單位秒
services.setRefreshTokenValiditySeconds(259200);//刷新令牌有效期3天
return services;
}
}
~~~
# 2.密碼模式配置
~~~
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JdbcUserDetailsServiceImpl jdbcUserDetailsService;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(jdbcUserDetailsService);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
~~~
3.其他配置
~~~
@Bean
public TokenStore tokenStore(){
return new InMemoryTokenStore();
}
@Bean //授權碼服務
public AuthorizationCodeServices authorizationCodeServices(){
return new InMemoryAuthorizationCodeServices();
}
~~~