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: security.oauth2.client.user-authorization-uri=http:
security.oauth2.resource.user-info-uri=http:
|
授权层
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/") ; }
}
|
有验证服务器当然是授权码模式,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 { http.requestMatchers() .antMatchers("/login", "/oauth/authorize") .and() .authorizeRequests() .anyRequest() .authenticated() .and() .formLogin() .permitAll() .and().csrf().disable(); }
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin")) .roles("USER"); }
@Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
|
@Order(1)因为上一个文件中用到了这里的ECryptPasswordEncoder,所以这里要优先装配。/oauth/authorize
是oauth默认的校验地址。
详细代码托管在github: