我对 Java 相当陌生,我有一个 Spring 应用程序。对于登录功能,我使用 AuthenticationProvider。但是,如果身份验证不成功,我无法显示自定义错误消息。它记录了正确的消息,但我无法将其传递到 View 。
// CustomAuthenticationProvider.java
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
UserAuthenticationRequest loginRequest = new UserAuthenticationRequest(name, password);
Client client = ClientBuilder.newBuilder()
.register(JacksonConfig.class)
.register(JacksonFeature.class)
.build();
Invocation.Builder request = client.target(apiBaseUrl)
.path("login")
.request(MediaType.APPLICATION_JSON);
Response response = request.post(Entity.json(loginRequest));
if (response.getStatus() == 200) {
return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
} else {
ExceptionResponse errorResponse = response.readEntity(ExceptionResponse.class);
return null;
}
}
}
如果我记录 errorResponse.getMessage()
- 我收到了我需要的消息,但如何将其传递到 View ?如果有参数 ?error
,我已经显示了一条通用消息。
到目前为止,我尝试将其添加到模型中,将其保存到 session 中,但每次都会抛出错误 500。
最佳答案
就您而言,您可能应该自定义AuthenticationFailureHandler
来处理AuthenticationProvider
中抛出的AuthenticationException
。
public class CustomHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
// logic here
}
}
然后您可以操纵响应。
您必须在安全配置中注册它http.formLogin().failureHandler(new CustomHandler());
。
编辑 1
抛出 AuthenticationException
的实现之一。
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new BadCredentialsException("Wrong credentials");
}
关于java - 如何使用 AuthenticationProvider 显示登录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62644206/