Generate generate OAuth2 access token with additional claims to JUnit test

Multi tool use
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.
spring-boot spring-security-oauth2 spring-security-test
|
show 3 more comments
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.
spring-boot spring-security-oauth2 spring-security-test
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
if you get some token, likeaaaa1
, and you want to add here somerole
likeadmin
, new token with new claim will not beaaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can storepayload
data about user
– BSeitkazin
Jan 3 at 5:34
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
look at yourOAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspectcreateAccessToken
method, and make modification, to add claims in your token
– BSeitkazin
Jan 3 at 5:53
|
show 3 more comments
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.
spring-boot spring-security-oauth2 spring-security-test
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.
spring-boot spring-security-oauth2 spring-security-test
spring-boot spring-security-oauth2 spring-security-test
asked Jan 3 at 4:01
Nuwan SameeraNuwan Sameera
257
257
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
if you get some token, likeaaaa1
, and you want to add here somerole
likeadmin
, new token with new claim will not beaaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can storepayload
data about user
– BSeitkazin
Jan 3 at 5:34
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
look at yourOAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspectcreateAccessToken
method, and make modification, to add claims in your token
– BSeitkazin
Jan 3 at 5:53
|
show 3 more comments
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
if you get some token, likeaaaa1
, and you want to add here somerole
likeadmin
, new token with new claim will not beaaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can storepayload
data about user
– BSeitkazin
Jan 3 at 5:34
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
look at yourOAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspectcreateAccessToken
method, and make modification, to add claims in your token
– BSeitkazin
Jan 3 at 5:53
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
if you get some token, like
aaaa1
, and you want to add here some role
like admin
, new token with new claim will not be aaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can store payload
data about user– BSeitkazin
Jan 3 at 5:34
if you get some token, like
aaaa1
, and you want to add here some role
like admin
, new token with new claim will not be aaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can store payload
data about user– BSeitkazin
Jan 3 at 5:34
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
look at your
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspect createAccessToken
method, and make modification, to add claims in your token– BSeitkazin
Jan 3 at 5:53
look at your
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspect createAccessToken
method, and make modification, to add claims in your token– BSeitkazin
Jan 3 at 5:53
|
show 3 more comments
1 Answer
1
active
oldest
votes
Finally found the solution. Add TokenEnhancerChain to code
Following is the final code
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
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);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(new CustomTokenEnhancer(), converter));
accessToken = tokenEnhancerChain.enhance(accessToken, auth);
return accessToken.getValue();
}
IMPORTANT : Add JwtAccessTokenConverter as final element of token enhancer list
Following is the CustomTokenEnhancer class.
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
claims.put("userId", "admin@abc.com");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken;
}
}
what isDefaultTokenServices
? HowOAuth2Request
behaviour? HowOAuth2Authentication
works and where it authenticate? In suggested answer, you say, just addtokenEnhancerChain
, but inside you useCustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.
– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016183%2fgenerate-generate-oauth2-access-token-with-additional-claims-to-junit-test%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Finally found the solution. Add TokenEnhancerChain to code
Following is the final code
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
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);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(new CustomTokenEnhancer(), converter));
accessToken = tokenEnhancerChain.enhance(accessToken, auth);
return accessToken.getValue();
}
IMPORTANT : Add JwtAccessTokenConverter as final element of token enhancer list
Following is the CustomTokenEnhancer class.
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
claims.put("userId", "admin@abc.com");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken;
}
}
what isDefaultTokenServices
? HowOAuth2Request
behaviour? HowOAuth2Authentication
works and where it authenticate? In suggested answer, you say, just addtokenEnhancerChain
, but inside you useCustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.
– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
add a comment |
Finally found the solution. Add TokenEnhancerChain to code
Following is the final code
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
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);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(new CustomTokenEnhancer(), converter));
accessToken = tokenEnhancerChain.enhance(accessToken, auth);
return accessToken.getValue();
}
IMPORTANT : Add JwtAccessTokenConverter as final element of token enhancer list
Following is the CustomTokenEnhancer class.
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
claims.put("userId", "admin@abc.com");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken;
}
}
what isDefaultTokenServices
? HowOAuth2Request
behaviour? HowOAuth2Authentication
works and where it authenticate? In suggested answer, you say, just addtokenEnhancerChain
, but inside you useCustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.
– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
add a comment |
Finally found the solution. Add TokenEnhancerChain to code
Following is the final code
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
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);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(new CustomTokenEnhancer(), converter));
accessToken = tokenEnhancerChain.enhance(accessToken, auth);
return accessToken.getValue();
}
IMPORTANT : Add JwtAccessTokenConverter as final element of token enhancer list
Following is the CustomTokenEnhancer class.
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
claims.put("userId", "admin@abc.com");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken;
}
}
Finally found the solution. Add TokenEnhancerChain to code
Following is the final code
private String generateToken(String... authorities) {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
tokenService = new DefaultTokenServices();
JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
tokenService.setTokenStore(jwtTokenStore);
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);
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(
Arrays.asList(new CustomTokenEnhancer(), converter));
accessToken = tokenEnhancerChain.enhance(accessToken, auth);
return accessToken.getValue();
}
IMPORTANT : Add JwtAccessTokenConverter as final element of token enhancer list
Following is the CustomTokenEnhancer class.
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> claims = new HashMap<>();
List<Long> tenantIds = new ArrayList<>();
tenantIds.add(1L);
claims.put("role", 1L);
claims.put("tenants", tenantIds);
claims.put("userId", "admin@abc.com");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
return accessToken;
}
}
edited Jan 3 at 9:06
answered Jan 3 at 6:46
Nuwan SameeraNuwan Sameera
257
257
what isDefaultTokenServices
? HowOAuth2Request
behaviour? HowOAuth2Authentication
works and where it authenticate? In suggested answer, you say, just addtokenEnhancerChain
, but inside you useCustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.
– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
add a comment |
what isDefaultTokenServices
? HowOAuth2Request
behaviour? HowOAuth2Authentication
works and where it authenticate? In suggested answer, you say, just addtokenEnhancerChain
, but inside you useCustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.
– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
what is
DefaultTokenServices
? How OAuth2Request
behaviour? How OAuth2Authentication
works and where it authenticate? In suggested answer, you say, just add tokenEnhancerChain
, but inside you use CustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.– BSeitkazin
Jan 3 at 7:29
what is
DefaultTokenServices
? How OAuth2Request
behaviour? How OAuth2Authentication
works and where it authenticate? In suggested answer, you say, just add tokenEnhancerChain
, but inside you use CustomTokenEnhancer
class, how it works? It looks like, you just posted question, to answer on it by yourself.– BSeitkazin
Jan 3 at 7:29
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
Sorry. I edit answer with CutomTokenEnhancer code. This is only for the testing. Create JWT token with claims for the testing.
– Nuwan Sameera
Jan 3 at 9:09
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016183%2fgenerate-generate-oauth2-access-token-with-additional-claims-to-junit-test%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
PQdb44TpxpGiHz,R4ccWDycKyqAl vObvHpgL2jOGo,AfAiH7ugkmegUjhI2
what do you mean by "claims"? is it grand authorities?
– BSeitkazin
Jan 3 at 4:40
Not grant authorities. They are OK. But other parameters like "role", "tenants" etc..
– Nuwan Sameera
Jan 3 at 5:31
if you get some token, like
aaaa1
, and you want to add here somerole
likeadmin
, new token with new claim will not beaaaa1
. so, you need to generate token once, with all information inside, tokens live without modification. look at JWT, where you can storepayload
data about user– BSeitkazin
Jan 3 at 5:34
Is there any way to generate token with claims one time.
– Nuwan Sameera
Jan 3 at 5:45
look at your
OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);
code line. inspectcreateAccessToken
method, and make modification, to add claims in your token– BSeitkazin
Jan 3 at 5:53