I'm using spring boot with Angular 2. I implemented a JWT REST endpoint for authentication. My angular 2 front end using an authentication service to send the username and password to the spring boot backend. On the backend I only want a user with an LDAP role to have access to login. I implemented the following:
@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);
}
}
}
The piece of code that I have a question on is:
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);
What I'm doing is setting the role in a constant that I import called: LDAP_USER_ROLE
I create a collection variable to store the user authorities and use a for each loop to check if that user role is in the authorities collection. If it is, I return a JWT token, if it is not, I return a 403.
Is there a better way to do this? It works, but doesn't seem like an efficient way to check if the user possesses that role.
Use @PreAuthorize
annotation from springboot security.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.