springboot项目加入spring security其实是很简单的事情,主要就是config方法的重写。

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@EnableOAuth2Sso
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**")
.authorizeRequests()
.antMatchers("/updateResult**","/getOneAccount**","/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}

login在校验oauth服务器的时候要用到,所以这里需要放行。注解@EnableOAuth2Sso就是开启客户端sso

springboot的配置文件中增加对oauth校验服务器的访问配置

1
2
3
4
5
6
7
#security
security.oauth2.client.client-id=SampleClientId
security.oauth2.client.client-secret=secret
security.oauth2.client.access-token-uri=http://localhost:8081/auth/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:8081/auth/oauth/authorize

security.oauth2.resource.user-info-uri=http://localhost:8081/auth/user/me

授权层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

@Resource
private BCryptPasswordEncoder passwordEncoder;

@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret(passwordEncoder.encode("secret"))
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true)
.redirectUris("http://localhost:8848/login","http://localhost:8849/login","http://localhost:8850/login","http://localhost:8082/ui/login","http://localhost:8083/ui2/login","http://localhost:8082/login","http://www.example.com/")
// .accessTokenValiditySeconds(3600)
; // 1 hour
}


}

有验证服务器当然是授权码模式,redirectUris中加入所有重定向的地址,也就是客户端的url,因为通过验证服务器成功后需要重定向到客户端。

接下来就是SecurityConfig的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Configuration
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception { // @formatter:off
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll()
.and().csrf().disable();
} // @formatter:on

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.roles("USER");
} // @formatter:on

@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}

@Order(1)因为上一个文件中用到了这里的ECryptPasswordEncoder,所以这里要优先装配。/oauth/authorize是oauth默认的校验地址。

详细代码托管在github: