[英]Spring Boot and security: How to extend response for 302 status code?
[英]Spring Boot: disable security for status exception code
我有一个安全的Spring Boot应用程序。 我已删除此“/ login”网址的身份验证。
我的安全配置
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JwtFilter jwtFilter;
@Autowired
public SecurityConfiguration(JwtFilter jwtFilter) {
this.jwtFilter = jwtFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.anonymous().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.apply(new JwtConfigurerAdapter(jwtFilter)).and()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs");
web.ignoring().antMatchers("/login");
}
}
我的NotFound异常
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFound extends RuntimeException {
public NotFound(String message) {
super(message);
}
}
我的休息控制器有登录URL和异常返回值
@RestController
public class LoginController implements LoginService {
@Override
@GetMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
public UserInfo loginUsingJson(String username, String password) {
return findUser(username, password)).orElseThrow(() -> new NotFound("There does not exist any user by those credentials"));
}
}
好的,这是我的问题。 当我在“/ login”上调用GET并且UserInfo存在时,它将以JSON的形式返回用户。 这是因为web.ignoring().antMatchers("/login");
,但如果用户不存在,则与HTTP错误代码404的异常NOTFOUND,将不显示。 它现在返回错误代码401 Not Authorized。
我猜它有一些与HttpSecurity有关的东西,我必须添加一些异常或其他东西才能返回异常代码。 但是,在HttpSecurity的授权中,我在哪里允许忽略异常处理?
我找到了答案,并希望在同样的情况下帮助其他人。
我的问题是,当使用错误代码404 NotFound返回一个休息异常时,Spring Boot会自动重定向到url“/ error”。 但是这个网址映射需要为业务开放。 所以我不得不忽略这个网址的授权。
这里的解决方案是添加:
web.ignoring().antMatchers("/error");
这是改变的类:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final JwtFilter jwtFilter;
@Autowired
public SecurityConfiguration(JwtFilter jwtFilter) {
this.jwtFilter = jwtFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.anonymous().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.apply(new JwtConfigurerAdapter(jwtFilter)).and()
.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs");
web.ignoring().antMatchers("/login");
web.ignoring().antMatchers("/error");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.