use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testHandleUserConsent.
@Test(dataProvider = "provideUserConsentData", groups = "testWithConnection")
public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean skipConsent, String errorCode, String authCode, String accessToken, String idToken, String responseType, String responseMode, String authenticatedIdps, String state, int expectedStatus, String expectedLocation) throws Exception {
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new HashMap<>();
requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { SESSION_DATA_KEY_CONSENT_VALUE });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
requestParams.put(OAuthConstants.Prompt.CONSENT, new String[] { consent });
requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, responseMode, APP_REDIRECT_URL);
oAuth2Params.setResponseType(responseType);
oAuth2Params.setState(state);
oAuth2Params.setClientId(CLIENT_ID_VALUE);
when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
when(consentCacheEntry.getAuthenticatedIdPs()).thenReturn(authenticatedIdps);
OAuth2AuthorizeRespDTO authzRespDTO = null;
if (!isRespDTONull) {
authzRespDTO = new OAuth2AuthorizeRespDTO();
authzRespDTO.setAuthorizationCode(authCode);
authzRespDTO.setCallbackURI(APP_REDIRECT_URL);
authzRespDTO.setAccessToken(accessToken);
authzRespDTO.setIdToken(idToken);
authzRespDTO.setErrorCode(errorCode);
if (OAuthConstants.ID_TOKEN.equals(responseType) && idToken == null) {
authzRespDTO.setCallbackURI(APP_REDIRECT_URL + "?");
}
}
mockEndpointUtil(false);
when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
mockStatic(OpenIDConnectUserRPStore.class);
when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(skipConsent);
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
when(oAuthServerConfiguration.getAuthorizationCodeValidityPeriodInSeconds()).thenReturn(300L);
mockStatic(OAuth2Util.class);
when(OAuth2Util.getServiceProvider(CLIENT_ID_VALUE)).thenReturn(new ServiceProvider());
mockApplicationManagementService();
spy(FrameworkUtils.class);
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
Response response;
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
assertNotNull(response, "Authorization response is null");
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
if (expectedLocation != null) {
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata, "Response metadata is null");
assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
if (errorCode != null) {
assertTrue(location.contains(errorCode), "Expected error code not found in URL");
}
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleSuccessAuthorization.
private OAuthResponse handleSuccessAuthorization(OAuthMessage oAuthMessage, OIDCSessionState sessionState, OAuth2Parameters oauth2Params, String responseType, OAuth2AuthorizeRespDTO authzRespDTO) throws OAuthSystemException {
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(oAuthMessage.getRequest(), HttpServletResponse.SC_FOUND);
// all went okay
if (isAuthorizationCodeExists(authzRespDTO)) {
// Get token binder if it is enabled for the client.
Optional<TokenBinder> tokenBinderOptional = getTokenBinder(oauth2Params.getClientId());
String tokenBindingValue = null;
if (tokenBinderOptional.isPresent()) {
TokenBinder tokenBinder = tokenBinderOptional.get();
tokenBindingValue = tokenBinder.getOrGenerateTokenBindingValue(oAuthMessage.getRequest());
tokenBinder.setTokenBindingValueForResponse(oAuthMessage.getResponse(), tokenBindingValue);
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oauth2Params.getClientId());
params.put("tokenBindingValue", tokenBindingValue);
Map<String, Object> configs = new HashMap<>();
configs.put("tokenBinderType", tokenBinder.getBindingType());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Successfully generated token binding value.", "generate-token-binding-value", configs);
}
}
setAuthorizationCode(oAuthMessage, authzRespDTO, builder, tokenBindingValue);
}
if (isResponseTypeNotIdTokenOrNone(responseType, authzRespDTO)) {
setAccessToken(authzRespDTO, builder);
setScopes(authzRespDTO, builder);
}
if (isIdTokenExists(authzRespDTO)) {
setIdToken(authzRespDTO, builder);
oAuthMessage.setProperty(OIDC_SESSION_ID, authzRespDTO.getOidcSessionId());
}
if (StringUtils.isNotBlank(oauth2Params.getState())) {
builder.setParam(OAuth.OAUTH_STATE, oauth2Params.getState());
}
String redirectURL = authzRespDTO.getCallbackURI();
OAuthResponse oauthResponse;
if (RESPONSE_MODE_FORM_POST.equals(oauth2Params.getResponseMode())) {
oauthResponse = handleFormPostMode(oAuthMessage, builder, redirectURL);
} else {
oauthResponse = builder.location(redirectURL).buildQueryMessage();
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oauth2Params.getClientId());
params.put("responseMode", oauth2Params.getResponseMode());
params.put("redirectUrl", redirectURL);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Successfully generated oauth response.", "generate-response", null);
}
sessionState.setAuthenticated(true);
return oauthResponse;
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class DefaultIDTokenBuilder method buildIDToken.
@Override
public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception {
String accessToken = tokenRespDTO.getAccessToken();
String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey();
String spTenantDomain = getSpTenantDomain(authzReqMessageContext);
String issuer = OAuth2Util.getIdTokenIssuer(spTenantDomain);
// Get subject from Authenticated Subject Identifier
AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser();
String subject = getSubjectClaim(authzReqMessageContext, tokenRespDTO, clientId, spTenantDomain, authorizedUser);
String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce();
String acrValue = authzReqMessageContext.getAuthorizationReqDTO().getSelectedAcr();
// TODO:
List<String> amrValues = Collections.emptyList();
String idpSessionKey = getIdpSessionKey(authzReqMessageContext);
// Initialize OAuthAppDO using the client ID.
OAuthAppDO oAuthAppDO;
try {
oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
} catch (InvalidOAuthClientException e) {
String error = "Error occurred while getting app information for client_id: " + clientId;
throw new IdentityOAuth2Exception(error, e);
}
String[] amrValueArray = (String[]) (authzReqMessageContext.getAuthorizationReqDTO().getProperty(OAuthConstants.AMR));
if (ArrayUtils.isNotEmpty(amrValueArray)) {
amrValues = Arrays.asList(amrValueArray);
}
long idTokenLifeTimeInMillis = getIDTokenExpiryInMillis(oAuthAppDO);
long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
if (log.isDebugEnabled()) {
log.debug(buildDebugMessage(issuer, subject, nonceValue, idTokenLifeTimeInMillis, currentTimeInMillis));
}
JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
jwtClaimsSetBuilder.issuer(issuer);
// Set the audience
List<String> audience = OAuth2Util.getOIDCAudience(clientId, oAuthAppDO);
jwtClaimsSetBuilder.audience(audience);
jwtClaimsSetBuilder.claim(AZP, clientId);
jwtClaimsSetBuilder.expirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis));
jwtClaimsSetBuilder.issueTime(new Date(currentTimeInMillis));
long authTime = getAuthTime(authzReqMessageContext);
if (authTime != 0) {
jwtClaimsSetBuilder.claim(AUTH_TIME, authTime / 1000);
}
if (nonceValue != null) {
jwtClaimsSetBuilder.claim(OAuthConstants.OIDCClaims.NONCE, nonceValue);
}
if (StringUtils.isNotEmpty(acrValue)) {
jwtClaimsSetBuilder.claim("acr", acrValue);
}
if (amrValues != null) {
jwtClaimsSetBuilder.claim("amr", translateAmrToResponse(amrValues));
}
if (idpSessionKey != null) {
jwtClaimsSetBuilder.claim(IDP_SESSION_KEY, idpSessionKey);
}
setUserRealm(authorizedUser, jwtClaimsSetBuilder);
setAdditionalClaims(authzReqMessageContext, tokenRespDTO, jwtClaimsSetBuilder);
authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken);
authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext));
jwtClaimsSetBuilder.subject(subject);
JWTClaimsSet jwtClaimsSet = handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSetBuilder);
if (isUnsignedIDToken()) {
return new PlainJWT(jwtClaimsSet).serialize();
}
return getIDToken(clientId, spTenantDomain, jwtClaimsSet, oAuthAppDO, getSigningTenantDomain(authzReqMessageContext));
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class CibaResponseTypeHandler method issue.
@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception {
OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
try {
// Assigning authenticated user for the request that to be persisted.
AuthenticatedUser cibaAuthenticatedUser = authorizationReqDTO.getUser();
// Assigning the authentication status that to be persisted.
Enum authenticationStatus = AuthReqStatus.AUTHENTICATED;
String authCodeKey = CibaDAOFactory.getInstance().getCibaAuthMgtDAO().getCibaAuthCodeKey(authorizationReqDTO.getNonce());
// Update successful authentication.
CibaDAOFactory.getInstance().getCibaAuthMgtDAO().persistAuthenticationSuccess(authCodeKey, cibaAuthenticatedUser);
// Building custom CallBack URL.
String callbackURL = authorizationReqDTO.getCallbackUrl() + "?authenticationStatus=" + authenticationStatus;
respDTO.setCallbackURI(callbackURL);
return respDTO;
} catch (CibaCoreException e) {
throw new IdentityOAuth2Exception("Error occurred in persisting authenticated user and authentication " + "status for the request made by client: " + authorizationReqDTO.getConsumerKey(), e);
}
}
Aggregations