项目代码:https://github.com/hankuikuide/microservice-spring-security-oauth2
网上多数的项目客户端都是采用纯js写,或用postman发请求,和实际项目的应用还是有差距的,这里也是采用spring boot的实现。 主要功能在于:
- 使用授权码模式进行认证。
- 使用OAuth2RestTemplate发送请求给认证服务器和资源服务器,
- 结合Feign实现loadbalance.
先进行security的配置:
@Configuration @EnableOAuth2Sso public class UiSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter; @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**") .permitAll().anyRequest().authenticated() .and() .addFilterBefore(oauth2ClientAuthenticationProcessingFilter,BasicAuthenticationFilter.class) .csrf().disable(); } }
在BasicAuthenticationFilter之前添加了一个过滤器。
客户端中最关键的代码,如下:
核心功能是
1. 注册OAuth2RestTemplate,
2.注册处理redirect uri的filter.也就是上面说的过滤器。
3. 注册check token服务
有了这个类,使用授权码模式,就可以把登录成功后的授权码接收到,并自动发给认证服务器请求token,并在后续的请求中自动添加token了。
@Configuration public class Oauth2ClientConfig { private String redirectUri ="http://localhost:9001/login"; private String checkTokenUrl ="http://localhost:9002/auth/oauth/check_token"; @Bean public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext context, OAuth2ProtectedResourceDetails details) { OAuth2RestTemplate template = new OAuth2RestTemplate(details, context); AuthorizationCodeAccessTokenProvider authCodeProvider = new</