在 Jhipster 用户身份验证中添加自定义验证

Adding Custom Validation in Jhipster User Authentication

由于 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);
    }

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

现在,假设我还需要添加自定义验证。例如,我需要检查该用户的姓氏是否为 "Mike",然后抛出一个自定义错误 "Mike can't log in".

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

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

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

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

如有任何帮助,我们将不胜感激。

提前致谢。

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

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
    }

然而,在我看来,这并不推荐,因为当您使用 jhipster 更新或向您的应用程序添加一些功能时,他可能会重写您的 class,您将不得不处理此代码丢失,通过 git 精选或您喜欢的其他方式

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

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

你所要做的就是在这个过滤器中验证后抛出异常

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