-
Notifications
You must be signed in to change notification settings - Fork 727
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 comprehensive integration tests for Authorization Code Grant for JWT Access Tokens #21045
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
409 changes: 409 additions & 0 deletions
409
...g/wso2/identity/integration/test/oauth2/OAuth2AuthorizationCodeGrantJWTTokenTestCase.java
Large diffs are not rendered by default.
Oops, something went wrong.
222 changes: 222 additions & 0 deletions
222
...st/java/org/wso2/identity/integration/test/oauth2/OAuth2RefreshGrantJWTTokenTestCase.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,222 @@ | ||
/* | ||
* 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.oauth2; | ||
|
||
import com.nimbusds.jwt.JWTClaimsSet; | ||
import com.nimbusds.jwt.SignedJWT; | ||
import org.apache.http.Header; | ||
import org.apache.http.HttpResponse; | ||
import org.apache.http.NameValuePair; | ||
import org.apache.http.client.config.CookieSpecs; | ||
import org.apache.http.client.config.RequestConfig; | ||
import org.apache.http.config.Lookup; | ||
import org.apache.http.config.RegistryBuilder; | ||
import org.apache.http.cookie.CookieSpecProvider; | ||
import org.apache.http.impl.client.CloseableHttpClient; | ||
import org.apache.http.impl.client.DefaultRedirectStrategy; | ||
import org.apache.http.impl.client.HttpClientBuilder; | ||
import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; | ||
import org.apache.http.message.BasicHeader; | ||
import org.apache.http.message.BasicNameValuePair; | ||
import org.apache.http.util.EntityUtils; | ||
import org.json.JSONObject; | ||
import org.testng.annotations.Test; | ||
import org.wso2.carbon.automation.engine.context.TestUserMode; | ||
import org.wso2.identity.integration.test.oauth2.dataprovider.model.ApplicationConfig; | ||
import org.wso2.identity.integration.test.oauth2.dataprovider.model.AuthorizedAccessTokenContext; | ||
import org.wso2.identity.integration.test.oauth2.dataprovider.model.AuthorizingUser; | ||
import org.wso2.identity.integration.test.oauth2.dataprovider.model.TokenScopes; | ||
import org.wso2.identity.integration.test.utils.OAuth2Constant; | ||
|
||
import java.text.ParseException; | ||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
|
||
import static org.testng.Assert.assertEquals; | ||
import static org.testng.Assert.assertNotNull; | ||
import static org.testng.Assert.assertTrue; | ||
import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; | ||
import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; | ||
|
||
public class OAuth2RefreshGrantJWTTokenTestCase extends OAuth2ServiceAbstractIntegrationTest { | ||
|
||
private Lookup<CookieSpecProvider> cookieSpecRegistry; | ||
private RequestConfig requestConfig; | ||
private CloseableHttpClient client; | ||
|
||
private ApplicationConfig applicationConfig; | ||
private TokenScopes tokenScopes; | ||
private AuthorizingUser authorizingUser; | ||
private AuthorizedAccessTokenContext authorizedAccessTokenContext; | ||
|
||
private String accessToken; | ||
private JWTClaimsSet accessTokenClaims; | ||
|
||
public OAuth2RefreshGrantJWTTokenTestCase(ApplicationConfig applicationConfig, TokenScopes tokenScopes, | ||
AuthorizingUser authorizingUser, | ||
AuthorizedAccessTokenContext authorizedAccessTokenContext) | ||
throws Exception { | ||
|
||
this.applicationConfig = applicationConfig; | ||
this.tokenScopes = tokenScopes; | ||
this.authorizingUser = authorizingUser; | ||
this.authorizedAccessTokenContext = authorizedAccessTokenContext; | ||
|
||
super.init(TestUserMode.TENANT_ADMIN); | ||
|
||
cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create() | ||
.register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) | ||
.build(); | ||
requestConfig = RequestConfig.custom() | ||
.setCookieSpec(CookieSpecs.DEFAULT) | ||
.build(); | ||
client = HttpClientBuilder.create() | ||
.setDefaultRequestConfig(requestConfig) | ||
.setDefaultCookieSpecRegistry(cookieSpecRegistry) | ||
.setRedirectStrategy(new DefaultRedirectStrategy() { | ||
@Override | ||
protected boolean isRedirectable(String method) { | ||
|
||
return false; | ||
} | ||
}).build(); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Get access token from refresh token") | ||
public void testGetAccessTokenFromRefreshToken() throws Exception { | ||
|
||
List<NameValuePair> parameters = new ArrayList<>(); | ||
parameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN)); | ||
parameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, | ||
authorizedAccessTokenContext.getRefreshToken())); | ||
|
||
List<Header> headers = new ArrayList<>(); | ||
headers.add(new BasicHeader(AUTHORIZATION_HEADER, | ||
OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(authorizedAccessTokenContext.getClientId(), | ||
authorizedAccessTokenContext.getClientSecret()))); | ||
headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); | ||
headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); | ||
|
||
HttpResponse response = sendPostRequest(client, headers, parameters, | ||
getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); | ||
|
||
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); | ||
JSONObject jsonResponse = new JSONObject(responseString); | ||
|
||
assertTrue(jsonResponse.has("access_token"), "Access token not found in the token response."); | ||
assertTrue(jsonResponse.has("refresh_token"), "Refresh token not found in the token response."); | ||
assertTrue(jsonResponse.has("expires_in"), "Expiry time not found in the token response."); | ||
assertTrue(jsonResponse.has("token_type"), "Token type not found in the token response."); | ||
|
||
accessToken = jsonResponse.getString("access_token"); | ||
assertNotNull(accessToken, "Access token is null."); | ||
|
||
String refreshToken = jsonResponse.getString("refresh_token"); | ||
assertNotNull(refreshToken, "Refresh token is null."); | ||
|
||
int expiresIn = jsonResponse.getInt("expires_in"); | ||
assertEquals(expiresIn, applicationConfig.getExpiryTime(), "Invalid expiry time for the access token."); | ||
|
||
String tokenType = jsonResponse.getString("token_type"); | ||
assertEquals(tokenType, "Bearer", "Invalid token type for the access token."); | ||
|
||
accessTokenClaims = getJWTClaimSetFromToken(accessToken); | ||
assertNotNull(accessTokenClaims); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate JWT token identifier", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateJWTID() { | ||
|
||
assertNotNull(accessTokenClaims.getJWTID()); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate issuer", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateIssuer() { | ||
|
||
assertEquals(accessTokenClaims.getIssuer(), | ||
getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate client id", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateClientId() { | ||
|
||
assertEquals(accessTokenClaims.getClaim("client_id"), authorizedAccessTokenContext.getClientId()); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate audiences", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateAudiences() { | ||
|
||
List<String> audienceList = accessTokenClaims.getAudience(); | ||
assertEquals(audienceList.get(0), authorizedAccessTokenContext.getClientId(), | ||
"Audience value does not include the client id."); | ||
|
||
List<String> expectedAudiences = applicationConfig.getAudienceList(); | ||
for (String expectedAudience : expectedAudiences) { | ||
assertTrue(audienceList.contains(expectedAudience), | ||
"Audience " + expectedAudience + " not found in the access token."); | ||
} | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate expiry time", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateExpiryTime() { | ||
|
||
// Convert expiry time to seconds as that is how expiry is incorporated in the JWT token claims. | ||
assertEquals(accessTokenClaims.getExpirationTime().getTime() / 1000, | ||
calculateExpiryTime(accessTokenClaims.getIssueTime().getTime() / 1000, | ||
applicationConfig.getExpiryTime()), | ||
"Invalid expiry time for the access token."); | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate scopes", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateScopes() throws Exception { | ||
|
||
assertNotNull(accessTokenClaims.getStringClaim("scope")); | ||
List<String> authorizedScopes = Arrays.asList(accessTokenClaims.getStringClaim("scope").split(" ")); | ||
List<String> expectedScopes = tokenScopes.getGrantedScopes(); | ||
for (String expectedScope : expectedScopes) { | ||
assertTrue(authorizedScopes.contains(expectedScope), | ||
"Scope " + expectedScope + " not found in the access token."); | ||
} | ||
} | ||
|
||
@Test(groups = "wso2.is", description = "Validate additional user claims", dependsOnMethods = "testGetAccessTokenFromRefreshToken") | ||
public void testValidateAdditionalUserClaims() { | ||
|
||
applicationConfig.getRequestedClaimList().forEach(claim -> { | ||
if (authorizingUser.getUserClaims().get(claim) != null) { | ||
assertNotNull(accessTokenClaims.getClaim(claim.getOidcClaimUri()), | ||
"Claim " + claim.getOidcClaimUri() + " not found in the access token."); | ||
assertEquals(accessTokenClaims.getClaim(claim.getOidcClaimUri()), | ||
authorizingUser.getUserClaims().get(claim), | ||
"Value for claim " + claim.getOidcClaimUri() + " is incorrect in the access token."); | ||
} | ||
}); | ||
} | ||
|
||
private JWTClaimsSet getJWTClaimSetFromToken(String jwtToken) throws ParseException { | ||
|
||
SignedJWT signedJWT = SignedJWT.parse(jwtToken); | ||
return signedJWT.getJWTClaimsSet(); | ||
} | ||
|
||
private long calculateExpiryTime(long issuedTime, long expiryPeriodInSeconds) { | ||
|
||
return issuedTime + expiryPeriodInSeconds; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this class added to testng file?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No it's kept as this so we can invoke from different grants like password etc. As an additional improvement I'm looking at invoking this programmatically as a test class. That's why it's added with test annotations.
Will do that improvement separately