Сервер авторизации, разработанный на основе SpringSecurity 5.0 OAuth.
После того, как я добавлю конфигурацию сервера ресурсов в свой проект.Я отправляю запрос по коду
Запрос на
http://127.0.0.1/oauth/authorize?client_id=testclient&redirect_uri=http://127.0.0.1:8072/client/oauth/login&response_type=code&scope=all
После входа в систему вы сразу переходите в систему (После успешного входа в систему перешли на "/«вместо» http://127.0.0.1:8072/client...")and не перезванивать на http://127.0.0.1:8072/client/oauth/login Если я отменяю конфигурацию сервера ресурсов (@ EnableAuthorizationServer), аутентификация Authorization_code может быть завершена, и обратный вызов на http://127.0.0.1:8072/client/oauth/login успешен
@Configuration
@EnableAuthorizationServer
public class SsoAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Resource
private SsoSecurityProperties ssoSecurityProperties;
@Autowired
private AuthenticationManager authenticationManager;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/**
* 令牌生成器 (需要令牌转换器 jwtTokenConverter)
* */
@Bean
public JwtTokenStore jwtTokenStore(){
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Autowired
private UserDetailsService myUserDetailsService;
/**
* 令牌转换器
* */
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
// (设置秘钥)
jwtAccessTokenConverter.setSigningKey(ssoSecurityProperties.getServer().getSingleKey());
return jwtAccessTokenConverter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(jwtTokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
/**
* @author:xjc
* @date:2018/11/30
* @description: 自定义token 规则
* @params:
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// 重要*************设置认证方式************
//// 设置令牌生成器 设置令牌转换器
endpoints.tokenStore(jwtTokenStore())
.accessTokenConverter(jwtAccessTokenConverter())
.authenticationManager(authenticationManager); // authenticationManager认证时需要,必须有.获得请求参数
}
/**
* @author:xjc
* @date:2018/11/30
* @description: 认证服务器安全配置
* @params:
*/
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients()
.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("testclient")
.secret(encoder.encode("testclient"))
.scopes("all").authorizedGrantTypes("authorization_code", "refresh_token","password")
.redirectUris("http://127.0.0.1:8072/client/oauth/login");
}
}
ResourceServer
@Configuration
@EnableResourceServer
public class SsoResourceConfig extends ResourceServerConfigurerAdapter{
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/authorize","/user/auth","/oauth/**","/oauth/authorize","/login.html","/login/**","/code/image","/authentication/form").permitAll() //定义不要拦截
.and()
.authorizeRequests()
.anyRequest().authenticated()//permitAll() //任何请求都需要拦截
.and()
.csrf().disable();
}
}
SecurityConfig
@Configuration
@EnableWebSecurity
public class SsoSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SsoSecurityProperties ssoSecurityProperties;
@Autowired
private SpringSocialConfigurer socialSecurityConfig;
@Autowired
private LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new MyUserDetailsService();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* @author:xjc
* @date:2018/11/30
* @description: 配置登录认证方式 (form,basic...)
* @params:
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置图片验证码过滤器
ImageValidateFilter imageValidateFilter = new ImageValidateFilter();
// 配置过滤器成功和失败触发器 authenticationHandler
imageValidateFilter.setLoginAuthenticationFailureHandler(loginAuthenticationFailureHandler);
imageValidateFilter.setProperties(ssoSecurityProperties);
imageValidateFilter.afterPropertiesSet();
http
.apply(socialSecurityConfig) //拦截某些特定请求,引导三方登录
.and()
.addFilterBefore(imageValidateFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin() //定义表单登录
.loginPage("/login.html")
.loginProcessingUrl("/authentication/form")
// .successHandler(loginAuthenticationSuccessHandler)
// .failureHandler(loginAuthenticationFailureHandler)
.and().authorizeRequests().antMatchers("/oauth/*","/login.html","/authentication/require","/login","/code/image","/register.html","/user/register").permitAll() //定义不要拦截
.and()
.authorizeRequests()
.anyRequest().authenticated() //任何请求都需要拦截
.and()
.csrf().disable();
}
/**
* @author:xjc
* @date:2018/11/30
* @description: 自定义认证逻辑 userDetailsService
* @params:
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean()) //自定义认证逻辑
.passwordEncoder(bCryptPasswordEncoder()); //自定义密码加密器
}
}