Я использую Spring Security с Oauth2 для защиты RESTful API. Мой класс WebSecurityConfig
выглядит так:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RestAuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(
SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/logout").permitAll()
.antMatchers("/ristore/**").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler());
http.logout().permitAll();
http.logout().logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)));
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public RestAuthenticationSuccessHandler mySuccessHandler(){
return new RestAuthenticationSuccessHandler();
}
@Bean
public SimpleUrlAuthenticationFailureHandler myFailureHandler(){
return new SimpleUrlAuthenticationFailureHandler();
}
@Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://ldap.mdanderson.edu:389/dc=mdanderson,dc=edu");
contextSource.setUserDn("cn=ris_flow,ou=service accounts,ou=institution,ou=service accounts,dc=mdanderson,dc=edu");
contextSource.setPassword("!BMpl@tform2O15");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.userDnPatterns("cn={0},ou=institution,ou=people")
.userSearchBase("")
.contextSource(contextSource);
}
}
}
Чтобы отключить перенаправление для выхода из системы, я добавил файл logoutSuceessHandler
.
Во внешнем интерфейсе я написал следующую функцию для обработки события выхода из системы с помощью AngularJS:
$scope.logout = function() {
$http.post(SERVER + '/logout', {}).success(function() {
$rootScope.authenticated = false;
$window.localStorage.removeItem("access_token");
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
};
Тем не менее, я все еще получаю следующую ошибку при выходе из системы:
XMLHttpRequest cannot load http://localhost:8080/logout. The request was redirected to 'http://localhost:8080/login?logout', which is disallowed for cross-origin requests that require preflight.
Я пробовал каждое решение в следующих похожих сообщениях, и, кажется, ничто не останавливает перенаправление. spring security/logout не работает с запросами между источниками и Безопасность Spring — отключить перенаправление выхода из системы.
Что мне не хватает?
ИЗМЕНИТЬ
После того, как я включил режим отладки в журнале весенней безопасности, вот вывод запроса на выход из системы. Почему он пытается сопоставить запрос /logout с /oauth/token?