[英]Spring Boot Role Based Security JWT
我在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
我创建了一个收集变量来存储用户权限,并为每个循环使用a来检查该用户角色是否在权限集中。 如果是,则返回JWT令牌,如果不是,则返回403。
有一个更好的方法吗? 它可以工作,但似乎不是检查用户是否拥有该角色的有效方法。
使用来自springboot安全性的@PreAuthorize
注释。
示例: https : //github.com/bfwg/springboot-jwt-starter/blob/master/src/main/java/com/bfwg/rest/UserController.java#L48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.