Kur*_*urt 1 java exception-handling spring-security spring-boot spring-security-rest
我有一个安全的 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");
}
}
Run Code Online (Sandbox Code Playgroud)
我的 NotFound 异常
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFound extends RuntimeException {
public NotFound(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
我的带有登录 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"));
}
}
Run Code Online (Sandbox Code Playgroud)
好的,这是我的问题。当我在“/login”上调用 GET 并且 UserInfo 存在时,它会将用户作为 JSON 返回。因为这个作品web.ignoring().antMatchers("/login");,但如果用户不存在,则与HTTP错误代码404的异常NOTFOUND,将不显示。它现在返回错误代码 401 Not Authorized。
我猜它与 HttpSecurity 有关系,我必须在其中添加一些异常或其他内容,以便可以返回异常代码。但是我在哪里允许在 HttpSecurity 的授权中忽略异常处理?
我找到了答案,并希望帮助处于相同情况的其他人。
我的问题是,当返回错误代码为 404 NotFound 的休息异常时,Spring Boot 会自动重定向到 url "/error"。但是这个url map需要开通业务。所以我也不得不忽略这个 url 的授权。
这里的解决方案是添加这个:
web.ignoring().antMatchers("/error");
Run Code Online (Sandbox Code Playgroud)
这是更改后的类:
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
826 次 |
| 最近记录: |