2016-11-20 106 views
0

我對Angular 2使用了spring引導。我實現了JWT REST端點進行身份驗證。我的角2前端使用身份驗證服務將用戶名和密碼發送到spring boot後端。在後端,我只希望具有LDAP角色的用戶有權訪問登錄。我實現了以下內容:基於Spring Boot角色的安全性JWT

@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

我創建了一個集合變量來存儲用戶權限,並使用每個循環來檢查用戶角色是否在權限集合中。如果是,我將返回一個JWT令牌,如果不是,我將返回一個403.

有沒有更好的方法來做到這一點?它的工作原理,但似乎不是一種有效的方式來檢查用戶是否擁有該角色。

回答