【发布时间】:2022-08-16 14:24:14
【问题描述】:
我有自定义身份验证提供程序可以正常工作:
@Component
public class ApiAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (isAuthorizedDevice(name, password)) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(ApiInfo.Role.User));
final UserDetails principal = new User(name, password, grantedAuths);
return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
} else {
return null;
}
}
但它总是返回 401。我想在某些情况下将其更改为 429 以实现蛮力机制。我不想返回 null 我想返回错误:f.e.: 429。我认为不应该在这里完成。应该在配置中完成:WebSecurityConfig 但我不知道如何实现这一点。
我已经尝试抛出异常,例如:
throw new LockedException(\"InvalidCredentialsFilter\");
throw new AuthenticationCredentialsNotFoundException(\"Invalid Credentials!\");
或注入响应对象并设置其状态:
response.setStatus(429);
但没有一个奏效。它总是返回 401。
即:
curl http://localhost:8080/api/v1.0/time --header \"Authorization: Basic poaueiccrmpoawklerpo0i\"
{\"timestamp\":\"2022-08-12T20:58:42.236+00:00\",\"status\":401,\"error\":\"Unauthorized\",\"path\":\"/api/v1.0/time\"}%
与身体:
白标错误页面
此应用程序没有显式映射 /error,因此您将其视为后备。 2022 年 8 月 12 日星期五 22:58:17 CEST 出现意外错误(类型=未授权,状态=401)。
也找不到任何文档或 Baeldung 教程。
你能帮助我吗?
PS我的WebSecurityConfig:
@Configuration @EnableWebSecurity class WebSecurityConfig { AuthenticationProvider apiAuthenticationProvider; @Bean public SecurityFilterChain apiFilterChain(HttpSecurity http) throws Exception { return http .csrf().disable() .formLogin().disable() .httpBasic().and() .authenticationProvider(apiAuthenticationProvider) .authorizeRequests() .antMatchers(ApiInfo.BASE_URL + \"/**\") .fullyAuthenticated() .and() .build(); }
-
But non of it worked没用怎么办?预期什么,结果如何返回等?还。 spring security 的文档在他们的网页上。仅仅因为它没有 Baldung 页面,并不意味着没有信息。 Baeldung 不是官方文档。 -
F.E. 这里是与抛出错误相同的示例:marcobehler.com/guides/spring-security
-
我在回答问题,因为我每天都会有空闲时间回答问题。我不会花几个小时来解决你的问题,因为我没有得到报酬来解决你的问题。我投了反对票,因为如果您阅读了
architecture上的章节,那么如何处理异常在 spring security 官方文档中,这是您在 spring security 中编写代码之前应该阅读的章节,或者发布有关堆栈溢出的问题。但我要给你一个提示,他抛出什么异常,你抛出什么异常......并非所有异常都是相同的。
标签: spring spring-boot spring-security