【问题标题】:Adding Custom Validation in Jhipster User Authentication在 Jhipster 用户身份验证中添加自定义验证
【发布时间】:2019-11-03 01:00:37
【问题描述】:

由于 Jhipster(Angular + Springboot Scaffolding) 使用 JWT 进行身份验证,我们有一个自定义登录模型来检查用户身份验证。现在代码变成了这样(UserJWTController.java):

   @PostMapping("/authenticate")
    @Timed
    public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {

        UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
    }

据观察,当用户输入无效凭据时,会引发错误。前端(角度)通过在模态本身中显示文本来处理错误。

现在,假设我还需要添加自定义验证。例如,我需要检查该用户的姓氏是否为“Mike”,然后抛出一个自定义错误,提示“Mike 无法登录”。

问题是 authenticate() (org.springframework.security.authentication.AuthenticationManager) 方法默认抛出 DisabledException,LockedException 和 BadCredentialsException。

我对 Spring Security 没有经验,所以我真的不明白我们如何覆盖类并添加所需的功能。

此外,Angular 捕获了一个通用异常,所以我的猜测是我们需要添加另一个约束:

.catch(() => {
                this.authenticationError = true;
            });

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: angular spring spring-boot spring-security jhipster


    【解决方案1】:

    正如我的回答 here 你所要做的就是

    1- 更改您的authorize 请求方法,添加所需的验证并使用此伪代码中的以下内容

     if(!userService.checkUsername(username)){
            throw new CustomParameterizedException("error.EK_L_C01", username);
            // or use the BadRequestAlertException  you can see how to use it in the UserResource.java
        }
    

    但是,这不是我对 vue 的建议,因为当您使用 jhipster 更新或向您的应用程序添加一些功能时,他可能会重写您的类,您将不得不通过 git cherry-pick 处理此代码丢失或者你喜欢的其他方式

    所以我相信使用过滤器是一种更好的方法,因为我使用 JHipster 的最佳实践是永远不要不惜一切代价更改生成的代码

    您可以使用本教程创建过滤器:using a bean@WebFilter annotation

    您所要做的就是在此过滤器中验证后抛出异常

    不要忘记在 webapp 国际化文件夹 i18n 中为所有语言更新您的错误消息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-01
      • 2022-12-10
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多