【发布时间】:2020-09-08 19:26:25
【问题描述】:
我正在使用 Spring Security 使用 jwt 令牌对用户进行身份验证。
身份验证工作正常,当令牌格式错误或过期时,我得到 403 Http 状态,如下面的配置所示:
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http
.exceptionHandling()
.authenticationEntryPoint((swe, e) -> {
return Mono.fromRunnable(() -> {
swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
});
}).accessDeniedHandler((swe, e) -> {
return Mono.fromRunnable(() -> {
swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
});
}).and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/**").permitAll()
.anyExchange().authenticated()
.and().build();
}
但是,当我使用 Spring 安全上下文中的 Principal 或 Authentication 从 jwt 令牌中获取用户信息时,如下代码所示:
@ResponseStatus(HttpStatus.OK)
@GetMapping("/me")
public Mono<ClientDTO> find(final Principal principal) {
return this.clientService.findByMail(principal.getName());
}
如果令牌格式错误或过期,我会从 Principal 对象中获得空指针异常和 500 https 状态。
【问题讨论】:
-
不是 .pathMatchers("/**").permitAll() 禁用端点的 jwt 检查吗?
-
正如@Lacuno 指出的那样, permitAll 然后假设会有一个有效的委托人会适得其反。如果匿名委托人已过期或格式不正确,您似乎想要一个匿名委托人。
标签: java spring spring-boot spring-security