I have spring boot REST API secured using OAuth2. My authentication server and resource server are two applications. All the REST API security properly working with REST client. Then I need to write security test cases. I generate access token using following code. Some end points need manually added claims inside REST method. Program given valid access token, but claims not include in this token.
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
tokenService.setTokenEnhancer(converter);
Collection<GrantedAuthority> grantAuthorities = new ArrayList<>();
if (authorities != null) {
for (String authority: authorities) {
grantAuthorities.add(new SimpleGrantedAuthority(authority));
}
}
Set<String> resourceIds = Collections.emptySet();
Set<String> scopes = Collections.emptySet();
Map<String, String> requestParameters = Collections.emptyMap();
boolean approved = true;
String redirectUrl = null;
Set<String> responseTypes = Collections.emptySet();
Map<String, Serializable> extensionProperties = Collections.emptyMap();
OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, "web-client", grantAuthorities,
approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);
User userPrincipal = new User("user", "", true, true,
true, true, grantAuthorities);
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(userPrincipal, null, grantAuthorities);
OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken.getValue();
}
How I add claims to this token.