Spring 安全性:如果未经授权,请勿重定向到登录页面



我有oAuth2授权的Spring Security。

我将它用于REST API。

我配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.authorizeRequests()
.antMatchers("/health").permitAll()
.antMatchers("/**").authenticated()
.and()
.oauth2Login()
.and()
.httpBasic();
}
}

当我没有授权时,我需要使所有请求返回给我401

但是现在当我没有被授权时,我被重定向到/login页。

我需要像使用普通的REST API一样使用它:如果我授权了,那么获取内容,否则得到401未授权。

我怎样才能做到呢?

谢谢你的帮助。

基本上你需要配置一个AuthenticationEntryPoint,当Spring Security检测到一个未经身份验证的请求时调用。Spring还提供了一个方便的实现,使您能够返回所需的任何HttpStatus:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
//rest of your config...
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}

最新更新