Extending a Jhipster JWT (Spring) monolith application to support impersonation

你离开我真会死。 提交于 2019-12-08 03:33:01

问题


I have generated a jhipster angular/java application that is using JWT authentication.

I now want to extend the application to support impersonation.

I am interested in achieving the following:

  • Impersonation by admin: Allowing the admin user to login as any other user

  • Impersonation granted to user: Allowing another user that has been granted the right to impersonate a user (granted by the user itself) to login as that other user.

  • Audit - recording changes (audit function) - the audit trail must be able to distinguish between the actual user and an impersonated user and record this in the audit trail.

I see that Spring supports impersonation but it is unclear to me how I can implement it properly in my Jhipster application given that JWT is used. I am not sure if the Spring route is appropriate for JHipster-JWT-Monolith application - I am of the opinion that it not the right approach.

While there are some incomplete information on various other posts, after an extensive search I have been unable to find a post that can provide clear step by step guide on this. If somebody can do that for me it would be greatly appreciated. I expect others would also find such an answer very useful.

Thanks in advance. Fergal


回答1:


You just need to add below method in UserJwtController.java

@PostMapping("/authenticate-externalnodes")
    public ResponseEntity<JWTToken> authenticateExternalnodes(@Valid @RequestBody LoginVM loginVM) {
        // Get Roles for user via username
        Set<Authority> authorities = userService.getUserWithAuthoritiesByLogin(loginVM.getUsername()).get()
                .getAuthorities();
        // Create Granted Authority Rules
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Authority authority : authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginVM.getUsername(), "", grantedAuthorities);
        Authentication authentication = 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(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
    }


来源:https://stackoverflow.com/questions/58780481/extending-a-jhipster-jwt-spring-monolith-application-to-support-impersonation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!