Generate generate OAuth2 access token with additional claims to JUnit test












0















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.










share|improve this question























  • 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 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











  • 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
















0















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.










share|improve this question























  • 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 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











  • 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














0












0








0








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.










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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, 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











  • 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



















  • 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 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











  • 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

















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












1 Answer
1






active

oldest

votes


















-1














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;

}
}





share|improve this answer


























  • 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











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
});


}
});














draft saved

draft discarded


















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









-1














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;

}
}





share|improve this answer


























  • 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
















-1














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;

}
}





share|improve this answer


























  • 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














-1












-1








-1







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;

}
}





share|improve this answer















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;

}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 3 at 9:06

























answered Jan 3 at 6:46









Nuwan SameeraNuwan Sameera

257




257













  • 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



















  • 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

















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




















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

generate and download xml file after input submit (php and mysql) - JPK

Angular Downloading a file using contenturl with Basic Authentication

Can't read property showImagePicker of undefined in react native iOS