Search in sources :

Example 1 with GrantType

use of org.apache.oltu.oauth2.common.message.types.GrantType in project Kustvakt by KorAP.

the class OAuth2Controller method requestAccessToken.

/**
 * Grants a client an access token, namely a string used in
 * authenticated requests representing user authorization for
 * the client to access user resources. An additional refresh
 * token strictly associated to the access token is also granted
 * for confidential clients. Both public and confidential clients
 * may issue multiple access tokens.
 *
 * <br /><br />
 *
 * Confidential clients may request refresh access token using
 * this endpoint. This request will grant a new access token.
 *
 * Usually the given refresh token is not changed and can be used
 * until it expires. However, currently there is a limitation of
 * one access token per one refresh token. Thus, the given refresh
 * token will be revoked, and a new access token and a new refresh
 * token will be returned.
 *
 * <br /><br />
 *
 * Client credentials for authentication can be provided either as
 * an authorization header with Basic authentication scheme or as
 * form parameters in the request body.
 *
 * <br /><br />
 *
 * OAuth2 specification describes various ways of requesting an
 * access token. Kustvakt supports:
 * <ul>
 * <li> Authorization code grant: obtains authorization from a
 * third party application. Required parameters: grant_type,
 * code, client_id, redirect_uri (if specified in the
 * authorization request), client_secret (if the client is
 * confidential or issued a secret).
 * </li>
 * <li> Resource owner password grant: strictly for clients that
 * are parts of KorAP. Clients use user credentials, e.g. Kalamar
 * (front-end) with login form. Required parameters: grant_type,
 * username, password, client_id, client_secret (if the client is
 * confidential or issued a secret). Optional parameters: scope.
 * </li>
 * <li> Client credentials grant: strictly for clients that are
 * parts of KorAP. Clients access their own resources, not on
 * behalf of a user. Required parameters: grant_type, client_id,
 * client_secret. Optional parameters: scope.
 * </li>
 * </ul>
 *
 * RFC 6749: The value of the scope parameter is expressed as a
 * list of space-delimited, case-sensitive strings defined by the
 * authorization server.
 *
 * @param request
 *            the request
 * @param form
 *            form parameters in a map
 * @return a JSON object containing an access token, a refresh
 *         token, a token type and the token expiration in seconds
 *         if successful, an error code and an error description
 *         otherwise.
 */
@POST
@Path("token")
@ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public Response requestAccessToken(@Context HttpServletRequest request, @FormParam("grant_type") String grantType, MultivaluedMap<String, String> form) {
    try {
        boolean grantTypeExist = grantType != null && !grantType.isEmpty();
        AbstractOAuthTokenRequest oAuthRequest = null;
        if (grantTypeExist && grantType.equals(GrantType.CLIENT_CREDENTIALS.toString())) {
            oAuthRequest = new OAuthTokenRequest(new FormRequestWrapper(request, form));
        } else {
            oAuthRequest = new OAuthUnauthenticatedTokenRequest(new FormRequestWrapper(request, form));
        }
        OAuthResponse oAuthResponse = tokenService.requestAccessToken(oAuthRequest);
        return responseHandler.createResponse(oAuthResponse);
    } catch (KustvaktException e) {
        throw responseHandler.throwit(e);
    } catch (OAuthProblemException e) {
        throw responseHandler.throwit(e);
    } catch (OAuthSystemException e) {
        throw responseHandler.throwit(e);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) FormRequestWrapper(de.ids_mannheim.korap.web.utils.FormRequestWrapper) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) AbstractOAuthTokenRequest(org.apache.oltu.oauth2.as.request.AbstractOAuthTokenRequest) OAuthUnauthenticatedTokenRequest(org.apache.oltu.oauth2.as.request.OAuthUnauthenticatedTokenRequest) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthTokenRequest(org.apache.oltu.oauth2.as.request.OAuthTokenRequest) AbstractOAuthTokenRequest(org.apache.oltu.oauth2.as.request.AbstractOAuthTokenRequest) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Path(javax.ws.rs.Path) ResourceFilters(com.sun.jersey.spi.container.ResourceFilters) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 2 with GrantType

use of org.apache.oltu.oauth2.common.message.types.GrantType in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testIssueAccessToken.

@Test(dataProvider = "testIssueAccessTokenDataProvider", groups = "testWithConnection")
public void testIssueAccessToken(String clientId, String authzHeader, Object paramMapObj, String grantType, String idToken, Object headerObj, Object customResponseParamObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
    MultivaluedMap<String, String> paramMap = (MultivaluedMap<String, String>) paramMapObj;
    ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
    Map<String, String> customResponseParameters = (Map<String, String>) customResponseParamObj;
    Map<String, String[]> requestParams = new HashMap<>();
    if (clientId != null) {
        requestParams.put(OAuth.OAUTH_CLIENT_ID, clientId.split(","));
    }
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
    requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
    requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {

        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));
    spy(EndpointUtil.class);
    doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn(oAuth2AccessTokenRespDTO);
    when(oAuth2AccessTokenRespDTO.getAccessToken()).thenReturn(ACCESS_TOKEN);
    when(oAuth2AccessTokenRespDTO.getRefreshToken()).thenReturn(REFRESH_TOKEN);
    when(oAuth2AccessTokenRespDTO.getExpiresIn()).thenReturn(3600L);
    when(oAuth2AccessTokenRespDTO.getAuthorizedScopes()).thenReturn("scope1");
    when(oAuth2AccessTokenRespDTO.getIDToken()).thenReturn(idToken);
    when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
    when(oAuth2AccessTokenRespDTO.getParameters()).thenReturn(customResponseParameters);
    mockOAuthServerConfiguration();
    mockStatic(IdentityDatabaseUtil.class);
    when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    Response response;
    try {
        response = oAuth2TokenEndpoint.issueAccessToken(request, paramMap);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Token response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    assertNotNull(response.getEntity(), "Response entity is null");
    final String responseBody = response.getEntity().toString();
    if (customResponseParameters != null) {
        customResponseParameters.forEach((key, value) -> assertTrue(responseBody.contains(key) && responseBody.contains(value), "Expected custom response parameter: " + key + " not found in token response."));
    }
    if (expectedErrorCode != null) {
        assertTrue(responseBody.contains(expectedErrorCode), "Expected error code not found");
    } else if (HttpServletResponse.SC_OK == expectedStatus) {
        assertTrue(responseBody.contains(ACCESS_TOKEN), "Successful response should contain access token");
    }
}
Also used : ResponseHeader(org.wso2.carbon.identity.oauth2.ResponseHeader) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with GrantType

use of org.apache.oltu.oauth2.common.message.types.GrantType in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2TokenEndpointTest method testGetAccessToken.

@Test(dataProvider = "testGetAccessTokenDataProvider")
public void testGetAccessToken(String grantType, String additionalParameters) throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(OAuth.OAUTH_CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
    requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
    // Required params for authorization_code grant type
    requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
    requestParams.put(OAuth.OAUTH_CODE, new String[] { "auth_code" });
    // Required params for password grant type
    requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
    requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
    // Required params for refresh token grant type
    requestParams.put(OAuth.OAUTH_REFRESH_TOKEN, new String[] { REFRESH_TOKEN });
    // Required params for saml2 bearer grant type
    requestParams.put(OAuth.OAUTH_ASSERTION, new String[] { "dummyAssertion" });
    // Required params for IWA_NLTM grant type
    requestParams.put(OAuthConstants.WINDOWS_TOKEN, new String[] { "dummyWindowsToken" });
    HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
    when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER);
    when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {

        {
            add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
        }
    }));
    Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
    grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
    grantTypeValidators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
    grantTypeValidators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class);
    grantTypeValidators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
    grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString(), NTLMAuthenticationValidator.class);
    grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString(), SAML2GrantValidator.class);
    mockOAuthServerConfiguration();
    when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
    spy(EndpointUtil.class);
    doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
    final Map<String, String> parametersSetToRequest = new HashMap<>();
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            OAuth2AccessTokenReqDTO request = (OAuth2AccessTokenReqDTO) invocation.getArguments()[0];
            parametersSetToRequest.put(OAuth.OAUTH_CODE, request.getAuthorizationCode());
            parametersSetToRequest.put(OAuth.OAUTH_USERNAME, request.getResourceOwnerUsername());
            parametersSetToRequest.put(OAuth.OAUTH_PASSWORD, request.getResourceOwnerPassword());
            parametersSetToRequest.put(OAuth.OAUTH_REFRESH_TOKEN, request.getRefreshToken());
            parametersSetToRequest.put(OAuth.OAUTH_ASSERTION, request.getAssertion());
            parametersSetToRequest.put(OAuthConstants.WINDOWS_TOKEN, request.getWindowsToken());
            parametersSetToRequest.put(OAuth.OAUTH_GRANT_TYPE, request.getGrantType());
            OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO();
            return tokenRespDTO;
        }
    }).when(oAuth2Service).issueAccessToken(any(OAuth2AccessTokenReqDTO.class));
    CarbonOAuthTokenRequest oauthRequest = new CarbonOAuthTokenRequest(request);
    HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(request);
    Class<?> clazz = OAuth2TokenEndpoint.class;
    Object tokenEndpointObj = clazz.newInstance();
    Method getAccessToken = tokenEndpointObj.getClass().getDeclaredMethod("issueAccessToken", CarbonOAuthTokenRequest.class, HttpServletRequestWrapper.class);
    getAccessToken.setAccessible(true);
    OAuth2AccessTokenRespDTO tokenRespDTO = (OAuth2AccessTokenRespDTO) getAccessToken.invoke(tokenEndpointObj, oauthRequest, httpServletRequestWrapper);
    assertNotNull(tokenRespDTO, "ResponseDTO is null");
    String[] paramsToCheck = additionalParameters.split(",");
    for (String param : paramsToCheck) {
        assertNotNull(parametersSetToRequest.get(param), "Required parameter " + param + " is not set for " + grantType + "grant type");
    }
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) Method(java.lang.reflect.Method) HttpMethod(javax.ws.rs.HttpMethod) CarbonOAuthTokenRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthTokenRequest) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthValidator(org.apache.oltu.oauth2.common.validators.OAuthValidator) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with GrantType

use of org.apache.oltu.oauth2.common.message.types.GrantType in project components by Talend.

the class Oauth2ImplicitClient method getToken.

public <T extends OAuthAccessTokenResponse> T getToken(Class<T> tokenResponseClass) {
    try {
        TokenRequestBuilder builder = // 
        OAuthClientRequest.tokenLocation(// 
        tokenLocation.toString()).setGrantType(// 
        grantType).setClientId(// 
        clientID).setClientSecret(clientSecret);
        if (GrantType.AUTHORIZATION_CODE == grantType) {
            builder = // 
            builder.setRedirectURI(callbackURL.toString()).setCode(getAuthorizationCode());
        } else if (GrantType.REFRESH_TOKEN == grantType) {
            builder = builder.setRefreshToken(refreshToken);
        }
        OAuthClientRequest request = builder.buildQueryMessage();
        OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
        return oauthClient.accessToken(request, tokenResponseClass);
    } catch (OAuthSystemException e) {
        throw new RuntimeException(e);
    } catch (OAuthProblemException e) {
        throw new RuntimeException(e);
    }
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 5 with GrantType

use of org.apache.oltu.oauth2.common.message.types.GrantType in project identity-inbound-auth-oauth by wso2-extensions.

the class TokenResponseTypeHandler method issue.

@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        Map<String, Object> paramMap = new HashMap<>();
        oAuthEventInterceptorProxy.onPreTokenIssue(oauthAuthzMsgCtx, paramMap);
    }
    OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId = null;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    String oAuthCacheKeyString;
    String responseType = oauthAuthzMsgCtx.getAuthorizationReqDTO().getResponseType();
    String grantType;
    // Loading the stored application data.
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(consumerKey);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving app information for clientId: " + consumerKey, e);
    }
    if (StringUtils.contains(responseType, OAuthConstants.GrantTypes.TOKEN)) {
        grantType = OAuthConstants.GrantTypes.IMPLICIT;
    } else {
        grantType = responseType;
    }
    oAuthCacheKeyString = consumerKey + ":" + authorizedUserId + ":" + scope;
    OAuthCacheKey cacheKey = new OAuthCacheKey(oAuthCacheKeyString);
    String userStoreDomain = null;
    // Select the user store domain when multiple user stores are configured.
    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        userStoreDomain = OAuth2Util.getUserStoreForFederatedUser(authorizationReqDTO.getUser());
    }
    if (log.isDebugEnabled()) {
        log.debug("Service Provider specific expiry time enabled for application : " + consumerKey + ". Application access token expiry time : " + oAuthAppDO.getApplicationAccessTokenExpiryTime() + ", User access token expiry time : " + oAuthAppDO.getUserAccessTokenExpiryTime() + ", Refresh token expiry time : " + oAuthAppDO.getRefreshTokenExpiryTime());
    }
    String refreshToken = null;
    Timestamp refreshTokenIssuedTime = null;
    long refreshTokenValidityPeriodInMillis = 0;
    AccessTokenDO tokenDO = null;
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingAccessTokenDO = null;
        // check if valid access token exists in cache
        if (isHashDisabled && cacheEnabled) {
            existingAccessTokenDO = (AccessTokenDO) OAuthCache.getInstance().getValueFromCache(cacheKey);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved active Access Token for Client Id : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from cache");
                }
                long expireTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                if ((expireTime > 0 || expireTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        if (log.isDebugEnabled()) {
                            if (expireTime > 0) {
                                log.debug("Access Token is valid for another " + expireTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expireTime > 0) {
                            respDTO.setValidityPeriod(expireTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // We only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                    if (refreshTokenExpiryTime < 0 || refreshTokenExpiryTime > 0) {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token.");
                        }
                        refreshToken = existingAccessTokenDO.getRefreshToken();
                        refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                        refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                    }
                    // Token is expired. Clear it from cache
                    OAuthCache.getInstance().clearCacheEntry(cacheKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Access Token is expired. Therefore cleared it from cache and marked it as" + " expired in database");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No active access token found in cache for Client ID : " + consumerKey + ", User " + "ID" + " : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        // in the database
        if (isHashDisabled && existingAccessTokenDO == null) {
            existingAccessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(consumerKey, authorizationReqDTO.getUser(), userStoreDomain, scope, false);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved latest Access Token for Client ID : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from database");
                }
                long expiryTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(existingAccessTokenDO.getTokenState()) && (expiryTime > 0 || expiryTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        // token is active and valid
                        if (log.isDebugEnabled()) {
                            if (expiryTime > 0) {
                                log.debug("Access token is valid for another " + expiryTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        if (cacheEnabled) {
                            OAuthCache.getInstance().addToCache(cacheKey, existingAccessTokenDO);
                            if (log.isDebugEnabled()) {
                                log.debug("Access Token was added to cache for cache key : " + cacheKey.getCacheKeyString());
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expiryTime > 0) {
                            respDTO.setValidityPeriod(expiryTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // we only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                        log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                    }
                    String tokenState = existingAccessTokenDO.getTokenState();
                    if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) {
                        // Token is expired. If refresh token is still valid, use it.
                        if (refreshTokenExpiryTime > 0 || refreshTokenExpiryTime < 0) {
                            if (log.isDebugEnabled()) {
                                log.debug("Access token has expired, But refresh token is still valid. User " + "existing refresh token.");
                            }
                            refreshToken = existingAccessTokenDO.getRefreshToken();
                            refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                            refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("Marked Access Token as expired");
                        }
                    } else {
                        // Token is revoked or inactive
                        if (log.isDebugEnabled()) {
                            log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                        }
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No access token found in database for Client ID : " + consumerKey + ", User ID : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Issuing a new access token for client id: " + consumerKey + ", user : " + authorizationReqDTO.getUser().getLoggableUserId() + "and scope : " + scope);
        }
        Timestamp timestamp = new Timestamp(new Date().getTime());
        // if reusing existing refresh token, use its original issued time
        if (refreshTokenIssuedTime == null) {
            refreshTokenIssuedTime = timestamp;
        }
        // Default token validity Period
        long validityPeriodInMillis = OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() * 1000;
        if (oAuthAppDO.getUserAccessTokenExpiryTime() != 0) {
            validityPeriodInMillis = oAuthAppDO.getUserAccessTokenExpiryTime() * 1000;
        }
        // if a VALID validity period is set through the callback, then use it
        long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
        if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
            validityPeriodInMillis = callbackValidityPeriod * 1000;
        }
        // otherwise use existing refresh token's validity period
        if (refreshTokenValidityPeriodInMillis == 0) {
            if (oAuthAppDO.getRefreshTokenExpiryTime() != 0) {
                refreshTokenValidityPeriodInMillis = oAuthAppDO.getRefreshTokenExpiryTime() * 1000;
            } else {
                refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance().getRefreshTokenValidityPeriodInSeconds() * 1000;
            }
        }
        // issue a new access token
        String accessToken;
        // set the validity period. this is needed by downstream handlers.
        // if this is set before - then this will override it by the calculated new value.
        oauthAuthzMsgCtx.setValidityPeriod(validityPeriodInMillis);
        // set the refresh token validity period. this is needed by downstream handlers.
        // if this is set before - then this will override it by the calculated new value.
        oauthAuthzMsgCtx.setRefreshTokenvalidityPeriod(refreshTokenValidityPeriodInMillis);
        // set access token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setAccessTokenIssuedTime(timestamp.getTime());
        // set refresh token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setRefreshTokenIssuedTime(refreshTokenIssuedTime.getTime());
        try {
            OauthTokenIssuer oauthIssuerImpl = OAuth2Util.getOAuthTokenIssuerForOAuthApp(oAuthAppDO);
            accessToken = oauthIssuerImpl.accessToken(oauthAuthzMsgCtx);
            // regenerate only if refresh token is null
            if (refreshToken == null) {
                refreshToken = oauthIssuerImpl.refreshToken(oauthAuthzMsgCtx);
            }
        } catch (OAuthSystemException e) {
            throw new IdentityOAuth2Exception("Error occurred while generating access token and refresh token", e);
        }
        if (OAuth2Util.checkUserNameAssertionEnabled()) {
            accessToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), accessToken);
            refreshToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), refreshToken);
        }
        AccessTokenDO newAccessTokenDO = new AccessTokenDO(consumerKey, authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, OAuthConstants.UserType.APPLICATION_USER);
        newAccessTokenDO.setAccessToken(accessToken);
        newAccessTokenDO.setRefreshToken(refreshToken);
        newAccessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        newAccessTokenDO.setGrantType(grantType);
        String tokenId = UUID.randomUUID().toString();
        newAccessTokenDO.setTokenId(tokenId);
        oauthAuthzMsgCtx.addProperty(OAuth2Util.ACCESS_TOKEN_DO, newAccessTokenDO);
        // Persist the access token in database
        try {
            OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().insertAccessToken(accessToken, authorizationReqDTO.getConsumerKey(), newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
            deactivateCurrentAuthorizationCode(newAccessTokenDO.getAuthorizationCode(), newAccessTokenDO.getTokenId());
            if (!accessToken.equals(newAccessTokenDO.getAccessToken())) {
                // Using latest active token.
                accessToken = newAccessTokenDO.getAccessToken();
                refreshToken = newAccessTokenDO.getRefreshToken();
            }
        } catch (IdentityException e) {
            throw new IdentityOAuth2Exception("Error occurred while storing new access token : " + accessToken, e);
        }
        tokenDO = newAccessTokenDO;
        if (log.isDebugEnabled()) {
            log.debug("Persisted Access Token for " + "Client ID : " + authorizationReqDTO.getConsumerKey() + ", Authorized User : " + authorizationReqDTO.getUser().getLoggableUserId() + ", Timestamp : " + timestamp + ", Validity period (s) : " + newAccessTokenDO.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", Callback URL : " + authorizationReqDTO.getCallbackUrl() + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + OAuthConstants.UserType.APPLICATION_USER);
        }
        // Add the access token to the cache, if cacheEnabled and the hashing oauth key feature turn on.
        if (isHashDisabled && cacheEnabled) {
            OAuthCache.getInstance().addToCache(cacheKey, newAccessTokenDO);
            // Adding AccessTokenDO to improve validation performance
            OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(accessToken);
            OAuthCache.getInstance().addToCache(accessTokenCacheKey, newAccessTokenDO);
            if (log.isDebugEnabled()) {
                log.debug("Access Token was added to OAuthCache for cache key : " + cacheKey.getCacheKeyString());
                log.debug("Access Token was added to OAuthCache for cache key : " + accessTokenCacheKey.getCacheKeyString());
            }
        }
        if (StringUtils.contains(responseType, ResponseType.TOKEN.toString())) {
            respDTO.setAccessToken(accessToken);
            if (validityPeriodInMillis > 0) {
                respDTO.setValidityPeriod(newAccessTokenDO.getValidityPeriod());
            } else {
                respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
            }
            respDTO.setScope(newAccessTokenDO.getScope());
            respDTO.setTokenType(newAccessTokenDO.getTokenType());
        }
    }
    // we only need to deal with id_token and user attributes if the request is OIDC
    if (isOIDCRequest(oauthAuthzMsgCtx)) {
        buildIdToken(oauthAuthzMsgCtx, respDTO);
    }
    triggerPostListeners(oauthAuthzMsgCtx, tokenDO, respDTO);
    return respDTO;
}
Also used : HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) IdentityException(org.wso2.carbon.identity.base.IdentityException) Timestamp(java.sql.Timestamp) Date(java.util.Date) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Aggregations

HashMap (java.util.HashMap)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 ArrayList (java.util.ArrayList)2 Hashtable (java.util.Hashtable)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)2 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)2 OAuthValidator (org.apache.oltu.oauth2.common.validators.OAuthValidator)2 Matchers.anyString (org.mockito.Matchers.anyString)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AfterTest (org.testng.annotations.AfterTest)2 BeforeTest (org.testng.annotations.BeforeTest)2 Test (org.testng.annotations.Test)2 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)2 ResourceFilters (com.sun.jersey.spi.container.ResourceFilters)1 KustvaktException (de.ids_mannheim.korap.exceptions.KustvaktException)1 FormRequestWrapper (de.ids_mannheim.korap.web.utils.FormRequestWrapper)1 Method (java.lang.reflect.Method)1 Timestamp (java.sql.Timestamp)1 Date (java.util.Date)1