java - 如何使用 AuthenticationProvider 显示登录错误

标签 java spring authentication

我对 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/

相关文章:

Asp.Net MVC3 - FormsAuthentication,如何在浏览器关闭时使 cookie 过期?

java - 跨平台 "Global"Java 中的 KeyListener

java - 如何为 StdDraw 导入正确的包?

java - 从 Spring Cloud Config Server 获取配置时 Spring 配置文件排序不正确

java - 为什么将 Spring DI 添加到 Jersey 1.19.1 会使我的资源成为单例?

spring - 将 OAuth2RestTemplate 公开为 AsyncRestTemplate

WordPress 总是重定向到/wp-login.php

java - 自定义 hibernate 标准(一对多关系)

java - 如何使用 lucene 进行词形还原和消除空法语单词

c# - 断言签名验证失败