如何设置Spring Security返回401而不是登录页面



我有一个Spring Security配置如下:

@Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasAuthority("Business_User")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password");
http.headers().frameOptions().disable();
}

验证工作正常。但是,如果由于用户无效或密码错误导致身份验证失败,则返回标准Spring登录页面,返回码为200。

这不是我想要的。

如果用户登录失败,我如何配置Spring安全返回401和空响应体?

如果身份验证失败,spring security通过将您重定向到登录页面来处理它,但是您可以通过添加以下代码来管理它:

http
.exceptionHandling()
.authenticationEntryPoint(new org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint("headerValue"));

你也可以像这样使用HttpStatusEntryPoint

http
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))

最新更新