最近拿oauth2練手,搭了oauth2的demo。
服務端配置
/**
* oauth2配置
* @author hao
* @Date 2018-04-19
*/
public class OAuth2ServerConfig {
/**
* oauth2資源服務器配置
* @author kdlq-hao
*/
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/auth/**", "/user/me")// 由oauth2攔截檢驗,根據token驗證登錄
.and()
.authorizeRequests()
.antMatchers("/auth/**")// /auth路徑的資源需要token
.authenticated();
}
}
/**
* oauth2授權服務器配置
* @author kdlq-hao
*/
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String finalSecret = new BCryptPasswordEncoder().encode("123456");
// 創建兩個客戶端,client_1使用授權碼模式,client_2使用密碼模式
clients.inMemory()
.withClient("client_1")
.authorizedGrantTypes("authorization_code", "refresh_token", "implicit")
.scopes("get_user_info")
.secret(finalSecret)
.autoApprove(true)
.and()
.withClient("client_2")
.authorizedGrantTypes("password", "refresh_token")
.scopes("get_user_info")
.secret(finalSecret);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.tokenStore(new InMemoryTokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
//允許表單認證
oauthServer.allowFormAuthenticationForClients();
}
}
}
注意:
1,clientdetails繼承userdtails,如果client時如果驗證失敗,會進入userdetailsservice驗證,要注意密碼encode。
2,由resourceserver攔截的請求才會進行token權限驗證。
3,配置sessionId,避免session衝突。server.servlet.session.cookie.name: AUTH_SESSION
4,攔截後登陸頁面一定要form表單提交才能重定向
客戶端配置:
@SpringBootApplication
@RestController
@EnableOAuth2Client
public class Oauth2clientApplication extends WebSecurityConfigurerAdapter {
@Autowired
OAuth2ClientContext oauth2ClientContext;
@RequestMapping("/user")
public Principal user(Principal principal) {
return principal;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**", "/error**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
.logoutSuccessUrl("/").permitAll()
.and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
}
public static void main(String[] args) {
SpringApplication.run(Oauth2clientApplication.class, args);
}
@Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
"/login/facebook");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
facebook().getClientId());
tokenServices.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(tokenServices);
return facebookFilter;
}
@Bean
@ConfigurationProperties("security.oauth2.client")
public AuthorizationCodeResourceDetails facebook() {
return new AuthorizationCodeResourceDetails();
}
@Bean
@ConfigurationProperties("security.oauth2.resource")
public ResourceServerProperties facebookResource() {
return new ResourceServerProperties();
}
}
客戶端配置主要參考官方TUTORIAL。把oauth2client攔截器置前實現攔截請求,授權後自動重定向。