首页 文章

基于Spring Boot角色的安全JWT

提问于
浏览
0

我正在使用Angular 2的Spring启动 . 我实现了一个JWT REST endpoints 进行身份验证 . 我的angular 2前端使用身份验证服务将用户名和密码发送到spring boot后端 . 在后端,我只希望具有LDAP角色的用户可以访问登录 . 我实现了以下内容:

@RestController
@RequestMapping("/api")
public class UserJWTController {

    @Inject
    private TokenProvider tokenProvider;

    @Inject
    private AuthenticationManager authenticationManager;



    @RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes="application/json")
    public ResponseEntity<?> authorize(@RequestBody User user, HttpServletResponse response) {


        UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        try {
            Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            Collection<SimpleGrantedAuthority> userAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
            for(SimpleGrantedAuthority authCheck: userAuthorities){
                if(authCheck.toString().equals(LDAP_USER_ROLE )){
                    String jwt = tokenProvider.createToken(authentication, true);
                    response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
                    return ResponseEntity.ok(new JWTToken(jwt));
                }


            }
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);    


        } catch (AuthenticationException exception) {
            return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
        }
    }
}

我有一个问题的代码是:

Collection<SimpleGrantedAuthority> userAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
                for(SimpleGrantedAuthority authCheck: userAuthorities){
                    if(authCheck.toString().equals(LDAP_USER_ROLE )){
                        String jwt = tokenProvider.createToken(authentication, true);
                        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
                        return ResponseEntity.ok(new JWTToken(jwt));
                    }


                }
                return new ResponseEntity<>(HttpStatus.FORBIDDEN);

我正在做的是将角色设置为我导入的常量调用: LDAP_USER_ROLE

我创建了一个集合变量来存储用户权限,并使用for循环来检查该用户角色是否在权限集合中 . 如果是,我返回一个JWT令牌,如果不是,我返回403 .

有一个更好的方法吗?它可以工作,但似乎不是检查用户是否拥有该角色的有效方法 .

1 回答

相关问题