是金子在哪都会发光的——每个说这句话的人都误以为自己是金子。
在Spring Security源码分析十一:Spring Security OAuth2整合JWT中,我们使用Spring Boot 1.5.6.RELEASE
版本整合Spring Security Oauth2
实现了授权码模式、密码模式以及用户自定义登录返回token
。但更新至Spring Boot 2.0.1.RELEASE
版本时会出现一些小问题。在此,帮大家踩一下坑。关于OAuth2
请参考理解OAuth 2.0
更新Spring Boot
版本为Spring Boot 2.0.1.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
新增SecurityConfig
用于暴露AuthenticationManager
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// .formLogin().and()
.httpBasic().and()
.csrf().disable();
}
}
修改MerryyouAuthorizationServerConfig
用于加密clientsecret
和设置重定向地址
......
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
InMemoryClientDetailsServiceBuilder build = clients.inMemory();
if (ArrayUtils.isNotEmpty(oAuth2Properties.getClients())) {
for (OAuth2ClientProperties config : oAuth2Properties.getClients()) {
build.withClient(config.getClientId())
.secret(passwordEncoder.encode(config.getClientSecret()))
.accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())
.refreshTokenValiditySeconds(60 * 60 * 24 * 15)
.authorizedGrantTypes("refresh_token", "password", "authorization_code")//OAuth2支持的验证模式
.redirectUris("http://www.merryyou.cn")
.scopes("all");
}
}
......
由于在2.x版本中由于引入了不同的客户端,需要指定配置哪种连接池。
server:
port: 8888
redis:
host: localhost
port: 6379
jedis:
pool:
max-active: 8
max-wait: -1
min-idle: 0
max-idle: 8
logging:
level:
org.springframework: info
merryyou:
security:
oauth2:
storeType: redis #或者jwt
jwtSigningKey: merryyou
clients[0]:
clientId: merryyou
clientSecret: merryyou
clients[1]:
clientId: merryyou1
clientSecret: merryyou1