org.apache.oltu.oauth2.common.exception.OAuthSystemException Java Examples

The following examples show how to use org.apache.oltu.oauth2.common.exception.OAuthSystemException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CarbonOAuthTokenRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs CarbonOAuthTokenRequest from the given HttpServletRequest
 *
 * @param request an instance of HttpServletRequest that represents an OAuth token request
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 */
public CarbonOAuthTokenRequest(HttpServletRequest request) throws OAuthSystemException,
        OAuthProblemException {

    super(request);
    assertion = request.getParameter(OAuth.OAUTH_ASSERTION);
    windows_token = request.getParameter(OAuthConstants.WINDOWS_TOKEN);
    tenantDomain = request.getParameter(MultitenantConstants.TENANT_DOMAIN);
    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    // Store all request parameters
    if (request.getParameterNames() != null) {
        List<RequestParameter> requestParameterList = new ArrayList<RequestParameter>();
        while (request.getParameterNames().hasMoreElements()) {
            String key = request.getParameterNames().nextElement();
            String value = request.getParameter(key);
            requestParameterList.add(new RequestParameter(key, value));
        }
        requestParameters =
                requestParameterList.toArray(new RequestParameter[requestParameterList.size()]);
    }
}
 
Example #2
Source File: FragmentParametersApplier.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public OAuthMessage applyOAuthParameters(OAuthMessage message, Map<String, Object> params) throws OAuthSystemException {

        String messageUrl = message.getLocationUri();
        if (messageUrl != null) {
            StringBuilder url = new StringBuilder(messageUrl);

            if (params.containsKey(OAuth.OAUTH_REFRESH_TOKEN)) {
                params.remove(OAuth.OAUTH_REFRESH_TOKEN);
            }

            String fragmentQuery = OAuthUtils.format(params.entrySet(), "UTF-8");

            if (!OAuthUtils.isEmpty(fragmentQuery)) {
                if (params.size() > 0) {
                        url.append("#").append(fragmentQuery);
                }
            }
            message.setLocationUri(url.toString());
        }
        return message;
    }
 
Example #3
Source File: OpenIDConnectAuthenticator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private OAuthClientRequest getAccessRequest(String tokenEndPoint, String clientId, String code, String clientSecret,
                                            String callbackurl)
        throws AuthenticationFailedException {

    OAuthClientRequest accessRequest = null;
    try {
        accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint)
                .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId)
                .setClientSecret(clientSecret).setRedirectURI(callbackurl).setCode(code)
                .buildBodyMessage();

    } catch (OAuthSystemException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception while building request for request access token", e);
        }
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
    return accessRequest;
}
 
Example #4
Source File: OpenIDConnectUserEndpoint.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Build the error message response properly
 *
 * @param e
 * @return
 * @throws OAuthSystemException
 */
private Response handleError(UserInfoEndpointException e) throws OAuthSystemException {
    log.debug(e);
    OAuthResponse res = null;
    try {
        res =
                OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                        .setError(e.getErrorCode()).setErrorDescription(e.getErrorMessage())
                        .buildJSONMessage();
    } catch (OAuthSystemException e1) {
        log.error("Error while building the JSON message", e1);
        OAuthResponse response =
                OAuthASResponse.errorResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
                        .setError(OAuth2ErrorCodes.SERVER_ERROR)
                        .setErrorDescription(e1.getMessage()).buildJSONMessage();
        return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
    }
    return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
}
 
Example #5
Source File: UserInfoEndpointConfig.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public UserInfoRequestValidator getUserInfoRequestValidator() throws OAuthSystemException {
    if (requestValidator == null) {
        synchronized (UserInfoRequestValidator.class) {
            if (requestValidator == null) {
                try {
                    String requestValidatorClassName = EndpointUtil.getUserInfoRequestValidator();
                    Class requestValidatorClass =
                            this.getClass().getClassLoader()
                                    .loadClass(requestValidatorClassName);
                    requestValidator = (UserInfoRequestValidator) requestValidatorClass.newInstance();
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                    log.error("Error while loading configuration", e);
                }
            }
        }
    }
    return requestValidator;
}
 
Example #6
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @throws OAuthSystemException
 */
public void putUserRPToStore(AuthenticatedUser user, String appName, boolean trustedAlways, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDO repDO = new OpenIDUserRPDO();
    repDO.setDefaultProfileName(DEFAULT_PROFILE_NAME);
    repDO.setRpUrl(appName);
    repDO.setUserName(user.getAuthenticatedSubjectIdentifier());
    repDO.setTrustedAlways(trustedAlways);
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    dao.createOrUpdate(repDO, tenantId);
}
 
Example #7
Source File: OpenIDConnectUserRPStore.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param user
 * @param appName
 * @return
 * @throws OAuthSystemException
 */
public synchronized boolean hasUserApproved(AuthenticatedUser user, String appName, String clientId) throws
        OAuthSystemException {
    OpenIDUserRPDAO dao = new OpenIDUserRPDAO();
    OpenIDUserRPDO rpDO;
    int tenantId = -1;
    if (user.getUserName() != null) {
        tenantId = IdentityTenantUtil.getTenantId(user.getTenantDomain());
    } else {
        OAuthAppDAO oAuthAppDAO = new OAuthAppDAO();
        OAuthAppDO appDO;
        try {
            appDO = oAuthAppDAO.getAppInformation(clientId);
            tenantId = IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain());
        } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
            throw new OAuthSystemException("Error while retrieving app");
        }
    }

    rpDO = dao.getOpenIDUserRP(user.getAuthenticatedSubjectIdentifier(), appName, tenantId);
    if (rpDO != null && rpDO.isTrustedAlways()) {
        return true;
    }

    return false;
}
 
Example #8
Source File: LibFilter.java    From liferay-oidc-plugin with Apache License 2.0 6 votes vote down vote up
protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response, String clientId) throws
        IOException {
    OIDCConfiguration oidcConfiguration = liferay.getOIDCConfiguration(liferay.getCompanyId(request));

    try {
        OAuthClientRequest oAuthRequest = OAuthClientRequest
                .authorizationLocation(oidcConfiguration.authorizationLocation())
                .setClientId(clientId)
                .setRedirectURI(getRedirectUri(request))
                .setResponseType("code")
                .setScope(oidcConfiguration.scope())
                .setState(generateStateParam(request))
                .buildQueryMessage();
        liferay.debug("Redirecting to URL: " + oAuthRequest.getLocationUri());
        response.sendRedirect(oAuthRequest.getLocationUri());
    } catch (OAuthSystemException e) {
        throw new IOException("While redirecting to OP for SSO login", e);
    }
}
 
Example #9
Source File: SAMLAssertionClaimsCallback.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getResponse(OAuthAuthzReqMessageContext requestMsgCtx)
        throws OAuthSystemException {

    Map<ClaimMapping, String> userAttributes =
            getUserAttributesFromCache(requestMsgCtx.getProperty(OAuthConstants.ACCESS_TOKEN).toString());
    Map<String, Object> claims = Collections.emptyMap();

    // If subject claim uri is null, we get the actual user name of the logged in user.
    if (MapUtils.isEmpty(userAttributes) && (getSubjectClaimUri(requestMsgCtx) == null)) {
        if (log.isDebugEnabled()) {
            log.debug("User attributes not found in cache. Trying to retrieve attribute for user " + requestMsgCtx
                    .getAuthorizationReqDTO().getUser());
        }
        try {
            claims = getClaimsFromUserStore(requestMsgCtx);
        } catch (UserStoreException | IdentityApplicationManagementException | IdentityException e) {
            log.error("Error occurred while getting claims for user " + requestMsgCtx.getAuthorizationReqDTO().getUser(),
                    e);
        }
    } else {
        claims = getClaimsMap(userAttributes);
    }
    return claims;
}
 
Example #10
Source File: CarbonOAuthTokenRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize a grant type validator
 *
 * @return an instance of OAuthValidator
 * @throws OAuthProblemException
 * @throws OAuthSystemException
 */
@Override
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

    String requestTypeValue = getParam(OAuth.OAUTH_GRANT_TYPE);
    if (OAuthUtils.isEmpty(requestTypeValue)) {
        throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value");
    }

    Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
            .getInstance().getSupportedGrantTypeValidators().get(requestTypeValue);

    if (clazz == null) {
        if (log.isDebugEnabled()) {
            //Do not change this log format as these logs use by external applications
            log.debug("Unsupported Grant Type : " + requestTypeValue +
                    " for client id : " + getClientId());
        }
        throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value");
    }

    return OAuthUtils.instantiateClass(clazz);
}
 
Example #11
Source File: CarbonOAuthAuthzRequest.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
protected OAuthValidator<HttpServletRequest> initValidator() throws OAuthProblemException, OAuthSystemException {

        String responseTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE);
        if (OAuthUtils.isEmpty(responseTypeValue)) {
            throw OAuthUtils.handleOAuthProblemException("Missing response_type parameter value");
        }

        Class<? extends OAuthValidator<HttpServletRequest>> clazz = OAuthServerConfiguration
                .getInstance().getSupportedResponseTypeValidators().get(responseTypeValue);

        if (clazz == null) {
            if (log.isDebugEnabled()) {
                //Do not change this log format as these logs use by external applications
                log.debug("Unsupported Response Type : " + responseTypeValue +
                        " for client id : " + getClientId());
            }
            throw OAuthUtils.handleOAuthProblemException("Invalid response_type parameter value");
        }

        return OAuthUtils.instantiateClass(clazz);
    }
 
Example #12
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Builds an request url that the browser needs to be redirected to for OAuth.
 * @param req
 * @return
 * @throws OAuthSystemException
 */
public String buildOauthRequestString(HttpServletRequest req) throws OAuthSystemException {
    OAuthClientRequest.AuthenticationRequestBuilder requestBuilder = OAuthClientRequest
            .authorizationLocation(this.oidcConfiguration.getOidcAuthLocation())
            .setClientId(this.oidcConfiguration.getOidcClientId())
            .setParameter("response_mode", "form_post")
            .setParameter("response_type", "code");
    if (identityProviderExtractor.hasIdentityProvider(req)) {
        requestBuilder = requestBuilder.setParameter("kc_idp_hint", identityProviderExtractor.getIdentityProviderName(req))
                .setRedirectURI(identityProviderExtractor.getRedirectUri(req));
    } else if (StringUtils.isNotEmpty(this.oidcConfiguration.getDefaultIdentityProvider())) {
        requestBuilder = requestBuilder.setParameter("kc_idp_hint", this.oidcConfiguration.getDefaultIdentityProvider())
                .setRedirectURI(identityProviderExtractor.getRedirectUri(req));
    } else {
        requestBuilder = requestBuilder.setRedirectURI(buildRedirectURI(req));
    }
    OAuthClientRequest oauthRequest = requestBuilder
            .buildQueryMessage();
    return oauthRequest.getLocationUri();
}
 
Example #13
Source File: RetryingOAuth.java    From eve-esi with Apache License 2.0 6 votes vote down vote up
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
    if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
        try {
            OAuthJSONAccessTokenResponse accessTokenResponse = oAuthClient.accessToken(tokenRequestBuilder
                    .buildBodyMessage());
            if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
                setAccessToken(accessTokenResponse.getAccessToken());
                return !getAccessToken().equals(requestAccessToken);
            }
        } catch (OAuthSystemException | OAuthProblemException e) {
            throw new IOException(e);
        }
    }

    return false;
}
 
Example #14
Source File: RetryingOAuth.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
    if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
        try {
            OAuthJSONAccessTokenResponse accessTokenResponse =
                    oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
            if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
                setAccessToken(accessTokenResponse.getAccessToken());
                return !getAccessToken().equals(requestAccessToken);
            }
        } catch (OAuthSystemException | OAuthProblemException e) {
            throw new IOException(e);
        }
    }

    return false;
}
 
Example #15
Source File: OAuthAuthorizationServlet.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
private URI makeUrl(String redirectURI, OAuthAuthorizationCode oauthCode, OAuthAuthorizationResponseBuilder builder) throws OAuthSystemException, URISyntaxException {
	String siteAddress = getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress();
	OAuthAuthorizationResponseBuilder build = builder.location(redirectURI).setParam("address", siteAddress + "/json");
	build.setParam("serviceaddress", siteAddress + "/services");
	build.setParam("websocketUrl", siteAddress.replace("http://", "ws://").replace("https://", "wss://") + "/stream");
	if (oauthCode.getAuthorization() instanceof SingleProjectAuthorization) {
		SingleProjectAuthorization singleProjectAuthorization = (SingleProjectAuthorization) oauthCode.getAuthorization();
		build.setParam("poid", "" + singleProjectAuthorization.getProject().getOid());
	} else if (oauthCode.getAuthorization() instanceof RunServiceAuthorization) {
		RunServiceAuthorization auth = (RunServiceAuthorization) oauthCode.getAuthorization();
		build.setParam("soid", "" + auth.getService().getOid());
	}
	final OAuthResponse response = build.buildQueryMessage();
	String locationUri = response.getLocationUri();
	URI url = new URI(locationUri);
	return url;
}
 
Example #16
Source File: RetryingOAuth.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
    if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
        try {
            OAuthJSONAccessTokenResponse accessTokenResponse =
                    oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
            if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
                setAccessToken(accessTokenResponse.getAccessToken());
                return !getAccessToken().equals(requestAccessToken);
            }
        } catch (OAuthSystemException | OAuthProblemException e) {
            throw new IOException(e);
        }
    }

    return false;
}
 
Example #17
Source File: OAuthOkHttpClient.java    From android with MIT License 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                response.headers().toMultimap(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #18
Source File: OAuthOkHttpClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass)
                throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if(headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(
                response.body().string(), 
                response.body().contentType().toString(),
                response.code(),
                responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #19
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
public String accessToken(OAuthTokenReqMessageContext oAuthTokenReqMessageContext) throws OAuthSystemException {
    if (log.isDebugEnabled()) {
        log.debug("Access token request with token request message context. Authorized user " +
                oAuthTokenReqMessageContext.getAuthorizedUser().toString());
    }
    try {
        return this.buildIDToken(oAuthTokenReqMessageContext);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while issuing jwt access token. Hence returning default token", e);
        }
        // Return default access token if it fails to build jwt
        return super.accessToken(oAuthTokenReqMessageContext);
    }
}
 
Example #20
Source File: OAuthOkHttpClient.java    From eve-esi with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
        String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {

    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());

    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);

    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body()
                .contentType().toString(), response.code(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
 
Example #21
Source File: JWTAccessTokenBuilder.java    From msf4j with Apache License 2.0 5 votes vote down vote up
public String accessToken(OAuthAuthzReqMessageContext oAuthAuthzReqMessageContext) throws OAuthSystemException {
    if (log.isDebugEnabled()) {
        log.debug("Access token request with authorization request message context message context. Authorized " +
                "user " + oAuthAuthzReqMessageContext.getAuthorizationReqDTO().getUser().toString());
    }
    try {
        return this.buildIDToken(oAuthAuthzReqMessageContext);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while issuing jwt access token. Hence returning default token", e);
        }
        // Return default access token if it fails to build jwt
        return super.accessToken(oAuthAuthzReqMessageContext);
    }
}
 
Example #22
Source File: FacebookAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private OAuthClientRequest buidTokenRequest(
        String tokenEndPoint, String clientId, String clientSecret, String callbackurl, String code)
        throws ApplicationAuthenticatorException {
    OAuthClientRequest tokenRequest = null;
    try {
        tokenRequest =
                OAuthClientRequest.tokenLocation(tokenEndPoint).setClientId(clientId)
                        .setClientSecret(clientSecret)
                        .setRedirectURI(callbackurl).setCode(code)
                        .buildQueryMessage();
    } catch (OAuthSystemException e) {
        throw new ApplicationAuthenticatorException("Exception while building access token request.", e);
    }
    return tokenRequest;
}
 
Example #23
Source File: OAuth2TokenEndpoint.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Response handleBasicAuthFailure() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
            .setError(OAuth2ErrorCodes.INVALID_CLIENT)
            .setErrorDescription("Client Authentication failed.").buildJSONMessage();
    return Response.status(response.getResponseStatus())
            .header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, EndpointUtil.getRealmInfo())
            .entity(response.getBody()).build();
}
 
Example #24
Source File: OAuth2TokenEndpoint.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Response handleServerError() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).
            setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription("Internal Server Error.").buildJSONMessage();

    return Response.status(response.getResponseStatus()).header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE,
                    EndpointUtil.getRealmInfo()).entity(response.getBody()).build();

}
 
Example #25
Source File: OAuth2TokenEndpoint.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Response handleSQLError() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_GATEWAY).
            setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription("Service Unavailable Error.").buildJSONMessage();

    return Response.status(response.getResponseStatus()).header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE,
            EndpointUtil.getRealmInfo()).entity(response.getBody()).build();
}
 
Example #26
Source File: UserInfoJWTResponse.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public String getResponseString(OAuth2TokenValidationResponseDTO tokenResponse)
        throws UserInfoEndpointException, OAuthSystemException {

    Map<ClaimMapping, String> userAttributes = getUserAttributesFromCache(tokenResponse);

    Map<String, Object> claims = null;

    if (userAttributes.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("User attributes not found in cache. Trying to retrieve from user store.");
        }
        claims = ClaimUtil.getClaimsFromUserStore(tokenResponse);
    } else {
        UserInfoClaimRetriever retriever = UserInfoEndpointConfig.getInstance().getUserInfoClaimRetriever();
        claims = retriever.getClaimsMap(userAttributes);
    }
    if(claims == null){
        claims = new HashMap<String,Object>();
    }
    if(!claims.containsKey("sub") || StringUtils.isBlank((String) claims.get("sub"))) {
        claims.put("sub", tokenResponse.getAuthorizedUser());
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setAllClaims(claims);
    return new PlainJWT(jwtClaimsSet).serialize();
}
 
Example #27
Source File: SAMLAssertionClaimsCallback.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get response map
 *
 * @param requestMsgCtx Token request message context
 * @return Mapped claimed
 * @throws OAuthSystemException
 */
private Map<String, Object> getResponse(OAuthTokenReqMessageContext requestMsgCtx)
        throws OAuthSystemException {

    Map<ClaimMapping, String> userAttributes =
            getUserAttributesFromCache(requestMsgCtx.getProperty(OAuthConstants.ACCESS_TOKEN).toString());
    Map<String, Object> claims = Collections.emptyMap();

    if (userAttributes.isEmpty() && requestMsgCtx.getProperty(OAuthConstants.AUTHZ_CODE) != null) {
        userAttributes =
                getUserAttributesFromCache(requestMsgCtx.getProperty(OAuthConstants.AUTHZ_CODE).toString());
    }

    // If subject claim uri is null, we get the actual user name of the logged in user.
    if (MapUtils.isEmpty(userAttributes) && (getSubjectClaimUri(requestMsgCtx) == null)) {
        if (log.isDebugEnabled()) {
            log.debug("User attributes not found in cache. Trying to retrieve attribute for user " + requestMsgCtx
                    .getAuthorizedUser());
        }
        try {
            claims = getClaimsFromUserStore(requestMsgCtx);
        } catch (UserStoreException | IdentityApplicationManagementException | IdentityException e) {
            log.error("Error occurred while getting claims for user " + requestMsgCtx.getAuthorizedUser(), e);
        }
    } else {
        claims = getClaimsMap(userAttributes);
    }
    return claims;
}
 
Example #28
Source File: OidcAuthenticator.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void fetchAndProcessToken(HttpServletRequest req, String code) throws
        OAuthSystemException, OAuthProblemException, ApsSystemException {
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
    OAuthClientRequest oAuthClientRequest = this.oidcHelper.buildOauthRequest(req, code);
    OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.resource(oAuthClientRequest, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);

    _logger.info("----------------------TOKEN------------------- ");
    String accessToken = oAuthResponse.getAccessToken();
    _logger.info("accessToken -> " + accessToken);
    UserDetails cdpUser = this.oidcHelper.getOidcUser(oAuthResponse.getAccessToken());
    HttpSession session = req.getSession();
    session.setAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER, cdpUser);
}
 
Example #29
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public OAuthClientRequest buildOauthRequest(HttpServletRequest request, String code) throws OAuthSystemException {
    return OAuthClientRequest
            .tokenLocation(this.oidcConfiguration.getOidcTokenLocation())
            //.tokenProvider(OAuthProviderType.MICROSOFT)
            .setGrantType(GrantType.AUTHORIZATION_CODE)
            .setClientId(this.oidcConfiguration.getOidcClientId())
            //.setClientSecret("your-facebook-application-client-secret")
            .setRedirectURI(buildRedirectURI(request))
            .setCode(code)
            .setParameter("response_mode", "form_post")
            .buildBodyMessage();

}
 
Example #30
Source File: OAuth.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
public static String getLoginURL(Req req, OAuthProvider provider, String oauthDomain) {

		if (OAUTH.isEmpty()) {
			Log.warn("OAuth is not configured!");
		}

		String name = provider.getName().toLowerCase();

		Config providerConfig = OAUTH.sub(name);
		Value<String> clientId = providerConfig.entry("clientId").str();
		Value<String> clientSecret = providerConfig.entry("clientSecret").str();

		String callbackPath = Msc.specialUri(name + "OauthCallback");

		boolean popup = req.param("popup", null) != null;

		String redirectUrl = U.notEmpty(oauthDomain) ? oauthDomain + callbackPath : HttpUtils.constructUrl(req,
			callbackPath);

		String statePrefix = popup ? "P" : "N";
		String state = statePrefix + STATE_CHECK.generateState(clientSecret, req.sessionId());

		try {
			OAuthClientRequest request = OAuthClientRequest.authorizationLocation(provider.getAuthEndpoint())
				.setClientId(clientId.str().get()).setRedirectURI(redirectUrl).setScope(provider.getEmailScope())
				.setState(state).setResponseType("code").buildQueryMessage();
			return request.getLocationUri();
		} catch (OAuthSystemException e) {
			throw U.rte(e);
		}
	}