【发布时间】:2017-04-04 03:24:59
【问题描述】:
我正在使用带有 Angular 2 的 spring boot。我实现了一个 JWT REST 端点进行身份验证。我的 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 each 循环检查该用户角色是否在权限集合中。如果是,我返回一个 JWT 令牌,如果不是,我返回一个 403。
有没有更好的方法来做到这一点?它有效,但似乎不是检查用户是否拥有该角色的有效方法。
【问题讨论】:
标签: java spring-security spring-boot jwt