Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add access token attributes integration test #21446

Merged
merged 9 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.wso2.identity.integration.test.utils.DataExtractUtil.KeyValue;
import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ public ApplicationResponseModel addApplication(ApplicationConfig applicationConf
accessTokenConfiguration.type(applicationConfig.getTokenType().getTokenTypeProperty());
accessTokenConfiguration.applicationAccessTokenExpiryInSeconds(applicationConfig.getExpiryTime());
accessTokenConfiguration.userAccessTokenExpiryInSeconds(applicationConfig.getExpiryTime());
// Add access token claim list.
List<String> accessTokenClaimList = applicationConfig.getRequestedClaimList().stream()
.map(UserClaimConfig::getOidcClaimUri).collect(Collectors.toList());
accessTokenConfiguration.accessTokenAttributes(accessTokenClaimList);
oidcConfig.accessToken(accessTokenConfiguration);

if (applicationConfig.getAudienceList() != null && !applicationConfig.getRequestedClaimList().isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,8 @@ private OAuthConsumerAppDTO getOAuthConsumerAppDTO(OIDCApplication application)
appDTO.setTokenType("JWT");
appDTO.setGrantTypes("authorization_code implicit password client_credentials refresh_token " +
"urn:ietf:params:oauth:grant-type:token-exchange");
String[] accessTokenClaims = {"username", "email"};
appDTO.setAccessTokenClaims(accessTokenClaims);

return appDTO;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,14 @@ private void validateUserClaims(OIDCTokens oidcTokens) throws JSONException, Par
accessToken = oidcTokens.getAccessToken().getValue();
refreshToken = oidcTokens.getRefreshToken().getValue();

// Get the user info from the JWT access token.
// Check if user claims are present in access token.
JSONObject jwtJsonObject = new JSONObject(new String(Base64.decodeBase64(accessToken.split("\\.")[1])));
String email = jwtJsonObject.getString(EMAIL_OIDC_CLAIM);
Assert.assertEquals(USER_EMAIL, email, "Requested user claim (Email) is not present in the JWT access "
+ "token.");
Assert.assertTrue(jwtJsonObject.isNull(ADDRESS_OIDC_CLAIM), "Non-consented user claim (address) is"
+ " present in the JWT access token.");
try {
Object emailClaim = jwtJsonObject.get(EMAIL_OIDC_CLAIM);
Assert.fail("Requested user claim (email) is present in the JWT access token.");
shashimalcse marked this conversation as resolved.
Show resolved Hide resolved
} catch (JSONException e) {
Assert.assertTrue(true, "Requested user claim (email) is present in the JWT access token.");
}

// Get the user info from the ID token.
Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_OIDC_CLAIM).toString(), USER_EMAIL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ public void testRegisterApplication() throws Exception {
registerApplication();
}


@Test(description = "This test case tests the JWT access token generation using password grant type.",
dependsOnMethods = "testRegisterApplication")
public void testPasswordGrantBasedAccessTokenGeneration() throws IOException, URISyntaxException, ParseException,
Expand Down Expand Up @@ -139,13 +138,14 @@ private void validateUserClaims(OIDCTokens oidcTokens) throws JSONException, jav
// Get the user info from the JWT access token.
JSONObject jwtJsonObject = new JSONObject(new String(Base64.decodeBase64(accessToken.split(
"\\.")[1])));
String email = jwtJsonObject.get(EMAIL_OIDC_CLAIM).toString();
String country = ((JSONObject) jwtJsonObject.get(ADDRESS_OIDC_CLAIM)).get(COUNTRY_OIDC_CLAIM).toString();

// Check the user info of the JWT access token.
Assert.assertEquals(USER_EMAIL, email, "Requested user claim (email) is not present in the JWT access token.");
Assert.assertEquals(COUNTRY, country, "Requested user claim (country) is not present in the JWT "
+ "access token.");
// Check if user claims are present in access token.
try {
Object emailClaim = jwtJsonObject.get(EMAIL_OIDC_CLAIM);
Assert.fail("Requested user claim (email) is present in the JWT access token.");
} catch (JSONException e) {
Assert.assertTrue(true, "Requested user claim (email) is present in the JWT access token.");
}

Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_OIDC_CLAIM), USER_EMAIL,
"Requested user claims is not returned back with the ID token.");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.wso2.identity.integration.test.oidc;

import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.apache.http.HttpStatus;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.identity.integration.test.oidc.bean.OIDCApplication;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AccessTokenConfiguration;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationModel;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocols;
import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration;
import org.wso2.identity.integration.test.utils.OAuth2Constant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.notNullValue;

public class OIDCAccessTokenAttributesTestCase extends OIDCAbstractIntegrationTest {

private static final String OAUTH2_TOKEN_ENDPOINT_URI = "/oauth2/token";
private static final String SERVICES = "/services";
private OIDCApplication application;
private OpenIDConnectConfiguration oidcInboundConfig;
protected String refreshToken;
protected String sessionDataKey;

@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {

super.init();

RestAssured.baseURI = backendURL.replace(SERVICES, "");

// Create a user
OIDCUtilTest.initUser();
createUser(OIDCUtilTest.user);

// Create application
OIDCUtilTest.initApplications();
application = OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppTwoAppName);
createApplication(application);
}

@AfterClass(alwaysRun = true)
public void testClear() throws Exception {

deleteUser(OIDCUtilTest.user);
deleteApplication(application);
clear();
}

@Test(groups = "wso2.is", description = "Validate access token attributes with password grant")
public void testValidateAccessTokenAttributesWithPasswordGrant() throws Exception {

Map<String, String> params = new HashMap<>();
params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER);
params.put("scope", "");
params.put("username", OIDCUtilTest.user.getUserName());
params.put("password", OIDCUtilTest.user.getPassword());

Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(),
application.getClientId(), application.getClientSecret());

response.then()
.log().ifValidationFails()
.assertThat()
.statusCode(HttpStatus.SC_OK)
.body("access_token", notNullValue())
.body("refresh_token", notNullValue());

String accessToken = response.then().extract().path("access_token");
refreshToken = response.then().extract().path("refresh_token");
Assert.assertNotNull(accessToken, "Access token is null");
JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet();
Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null.");

}

@Test(groups = "wso2.is", description = "Validate access token attributes with refresh grant",
dependsOnMethods = "testValidateAccessTokenAttributesWithPasswordGrant")
public void testValidateAccessTokenAttributesWithRefreshGrant() throws Exception {

Map<String, String> params = new HashMap<>();
params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN);
params.put(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken);

Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(),
application.getClientId(), application.getClientSecret());

response.then()
.log().ifValidationFails()
.assertThat()
.statusCode(HttpStatus.SC_OK)
.body("access_token", notNullValue())
.body("refresh_token", notNullValue());

String accessToken = response.then().extract().path("access_token");
refreshToken = response.then().extract().path("refresh_token");
Assert.assertNotNull(accessToken, "Access token is null");
JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet();
Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null.");
}

@Test(groups = "wso2.is", description = "Update access token attributes of the application",
dependsOnMethods = "testValidateAccessTokenAttributesWithRefreshGrant")
public void testUpdateAccessTokenAttributes() throws Exception {

AccessTokenConfiguration accessTokenConfig = new AccessTokenConfiguration().type("JWT");
accessTokenConfig.setUserAccessTokenExpiryInSeconds(3600L);
accessTokenConfig.setApplicationAccessTokenExpiryInSeconds(3600L);
// Add access token attributes
accessTokenConfig.setAccessTokenAttributes(new ArrayList<>());
oidcInboundConfig.setAccessToken(accessTokenConfig);
updateApplicationInboundConfig(application.getApplicationId(), oidcInboundConfig, OIDC);

OpenIDConnectConfiguration updatedOidcInboundConfig =
getOIDCInboundDetailsOfApplication(application.getApplicationId());
Assert.assertFalse(updatedOidcInboundConfig.getAccessToken().getAccessTokenAttributes().isEmpty(),
"Access token attribute should not be empty.");
}

@Test(groups = "wso2.is", description = "Validate access token attributes for empty allowed attributes",
dependsOnMethods = "testUpdateAccessTokenAttributes")
public void testValidateAccessTokenAttributesForEmptyAllowedAttributes() throws Exception {

Map<String, String> params = new HashMap<>();
params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER);
params.put("scope", "");
params.put("username", OIDCUtilTest.user.getUserName());
params.put("password", OIDCUtilTest.user.getPassword());

Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(),
application.getClientId(), application.getClientSecret());

response.then()
.log().ifValidationFails()
.assertThat()
.statusCode(HttpStatus.SC_OK)
.body("access_token", notNullValue())
.body("refresh_token", notNullValue());

String accessToken = response.then().extract().path("access_token");
refreshToken = response.then().extract().path("refresh_token");
Assert.assertNotNull(accessToken, "Access token is null");
JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet();
Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null.");
}

@Test(groups = "wso2.is", description = "Validate access token attributes for empty allowed attributes with " +
"refresh grant", dependsOnMethods = "testValidateAccessTokenAttributesForEmptyAllowedAttributes")
public void testValidateAccessTokenAttributesForEmptyAllowedAttributesWithRefreshGrant() throws Exception {

Map<String, String> params = new HashMap<>();
params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN);
params.put(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken);

Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(),
application.getClientId(), application.getClientSecret());

response.then()
.log().ifValidationFails()
.assertThat()
.statusCode(HttpStatus.SC_OK)
.body("access_token", notNullValue())
.body("refresh_token", notNullValue());

String accessToken = response.then().extract().path("access_token");
refreshToken = response.then().extract().path("refresh_token");
Assert.assertNotNull(accessToken, "Access token is null");
JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet();
Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null.");
}

/**
* Invoke given endpointUri for Form POST request with given body, headers and Basic authentication credentials.
*
* @param endpointUri endpoint to be invoked.
* @param params map of parameters to be added to the request.
* @param headers map of headers to be added to the request.
* @param username basic auth username.
* @param password basic auth password.
* @return response.
*/
protected Response getResponseOfFormPostWithAuth(String endpointUri, Map<String, String> params, Map<String, String>
headers, String username, String password) {

return given().auth().preemptive().basic(username, password)
.headers(headers)
.params(params)
.when()
.post(endpointUri);
}

/**
* Create an OIDC application.
*
* @param application application instance.
* @throws Exception If an error creating an application.
*/
public void createApplication(OIDCApplication application) throws Exception {

ApplicationModel applicationModel = new ApplicationModel();
createAccessTokenAttributesEnabledApplication(applicationModel, application);
}

private void createAccessTokenAttributesEnabledApplication(ApplicationModel applicationModel,
OIDCApplication application) throws Exception {

List<String> grantTypes = new ArrayList<>();
Collections.addAll(grantTypes, OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER,
OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN);

OpenIDConnectConfiguration oidcConfig = new OpenIDConnectConfiguration();
oidcConfig.setGrantTypes(grantTypes);
oidcConfig.addCallbackURLsItem(application.getCallBackURL());

AccessTokenConfiguration accessTokenConfig = new AccessTokenConfiguration().type("JWT");
accessTokenConfig.setUserAccessTokenExpiryInSeconds(3600L);
accessTokenConfig.setApplicationAccessTokenExpiryInSeconds(3600L);
// Add access token attributes
List<String> accessTokenAttributes = new ArrayList<>();
Collections.addAll(accessTokenAttributes, "username", "email");
accessTokenConfig.setAccessTokenAttributes(accessTokenAttributes);

oidcConfig.setAccessToken(accessTokenConfig);

applicationModel.setName(application.getApplicationName());
applicationModel.setInboundProtocolConfiguration(new InboundProtocols().oidc(oidcConfig));

String applicationId = addApplication(applicationModel);
oidcConfig = getOIDCInboundDetailsOfApplication(applicationId);
oidcInboundConfig = oidcConfig;

application.setApplicationId(applicationId);
application.setClientId(oidcConfig.getClientId());
application.setClientSecret(oidcConfig.getClientSecret());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
<class name="org.wso2.identity.integration.test.actions.PreIssueAccessTokenClientCredentialsGrantTestCase"/>
<class name="org.wso2.identity.integration.test.actions.PreIssueAccessTokenCodeGrantTestCase"/>
<class name="org.wso2.identity.integration.test.oauth2.Oauth2ImpersonationTestCase"/>
<class name="org.wso2.identity.integration.test.oidc.OIDCAccessTokenAttributesTestCase"/>
<class name="org.wso2.identity.integration.test.oauth2.OAuth2AuthorizationCodeGrantJWTTokenTestCase"/>
<class name="org.wso2.identity.integration.test.recovery.PasswordRecoveryTestCase"/>
<class name="org.wso2.identity.integration.test.oidc.OIDCIdentityFederationTestCase"/>
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2365,7 +2365,7 @@
<properties>

<!--Carbon Identity Framework Version-->
<carbon.identity.framework.version>7.6.3</carbon.identity.framework.version>
<carbon.identity.framework.version>7.6.7</carbon.identity.framework.version>
<carbon.identity.framework.version.range>[5.14.67, 8.0.0)</carbon.identity.framework.version.range>

<!--SAML Common Utils Version-->
Expand Down