Search in sources :

Example 56 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.

the class OAuth2Controller method revokeAccessToken.

/**
 * Revokes either an access token or a refresh token. Revoking a
 * refresh token also revokes all access token associated with the
 * refresh token.
 *
 * RFC 7009
 * Client authentication for confidential client
 *
 * @param request
 * @param form
 *            containing
 *            client_id,
 *            client_secret (required for confidential clients),
 *            token,
 *            token_type (optional)
 * @return 200 if token invalidation is successful or the given
 *         token is invalid
 */
@POST
@Path("revoke")
@ResourceFilters({ APIVersionFilter.class })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revokeAccessToken(@Context HttpServletRequest request, MultivaluedMap<String, String> form) {
    try {
        OAuth2RevokeTokenRequest revokeTokenRequest = new OAuth2RevokeTokenRequest(new FormRequestWrapper(request, form));
        tokenService.revokeToken(revokeTokenRequest);
        return Response.ok("SUCCESS").build();
    } catch (OAuthProblemException e) {
        throw responseHandler.throwit(e);
    } catch (OAuthSystemException e) {
        throw responseHandler.throwit(e);
    } catch (KustvaktException 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) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2RevokeTokenRequest(de.ids_mannheim.korap.oauth2.oltu.OAuth2RevokeTokenRequest) Path(javax.ws.rs.Path) ResourceFilters(com.sun.jersey.spi.container.ResourceFilters) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 57 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project Kustvakt by KorAP.

the class OAuth2Controller method revokeTokenViaSuperClient.

@POST
@Path("revoke/super")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response revokeTokenViaSuperClient(@Context SecurityContext context, @Context HttpServletRequest request, MultivaluedMap<String, String> form) {
    TokenContext tokenContext = (TokenContext) context.getUserPrincipal();
    String username = tokenContext.getUsername();
    try {
        OAuth2RevokeTokenSuperRequest revokeTokenRequest = new OAuth2RevokeTokenSuperRequest(new FormRequestWrapper(request, form));
        tokenService.revokeTokensViaSuperClient(username, revokeTokenRequest);
        return Response.ok("SUCCESS").build();
    } catch (OAuthSystemException e) {
        throw responseHandler.throwit(e);
    } catch (OAuthProblemException e) {
        throw responseHandler.throwit(e);
    } catch (KustvaktException e) {
        throw responseHandler.throwit(e);
    }
}
Also used : TokenContext(de.ids_mannheim.korap.security.context.TokenContext) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) FormRequestWrapper(de.ids_mannheim.korap.web.utils.FormRequestWrapper) KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2RevokeTokenSuperRequest(de.ids_mannheim.korap.oauth2.oltu.OAuth2RevokeTokenSuperRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 58 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException 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 59 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project geoprism-registry by terraframe.

the class RegistrySessionService method ologin.

/**
 * Serves as a "redirect url" for logging into DHIS2 via oauth.
 *
 * @param serverId
 * @param code
 * @param locales
 * @param redirectBase
 * @return
 */
@Authenticate
public static java.lang.String ologin(java.lang.String serverId, java.lang.String code, java.lang.String locales, java.lang.String redirectBase) {
    try {
        // We used to try to build this from the controller but it would include stuff (like the port :443) which then wouldn't match
        // with the redirect url the client specified in DHIS2. Therefore this has to be something that the user can set (or, at least,
        // in a properties file)
        redirectBase = GeoregistryProperties.getRemoteServerUrl();
        String redirect = redirectBase + "cgrsession/ologin";
        OauthServer server = OauthServer.get(serverId);
        /*
       * Get the access token
       */
        TokenRequestBuilder tokenBuilder = OAuthClientRequest.tokenLocation(server.getTokenLocation());
        tokenBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
        tokenBuilder.setRedirectURI(redirect);
        tokenBuilder.setCode(code);
        String auth = server.getClientId() + ":" + server.getSecretKey();
        OAuthClientRequest tokenRequest = tokenBuilder.buildBodyMessage();
        tokenRequest.setHeader("Accept", "application/json");
        tokenRequest.setHeader("Authorization", "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())));
        URLConnectionClient connClient = new URLConnectionClient();
        OAuthClient oAuthClient = new OAuthClient(connClient);
        OAuthJSONAccessTokenResponse accessToken = oAuthClient.accessToken(tokenRequest, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);
        /*
       * Request the user information
       */
        OAuthBearerClientRequest requestBuilder = new OAuthBearerClientRequest(server.getProfileLocation());
        requestBuilder.setAccessToken(accessToken.getAccessToken());
        OAuthClientRequest bearerRequest = requestBuilder.buildQueryMessage();
        OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
        String body = resourceResponse.getBody();
        JSONObject object = new JSONObject(body);
        final String username = object.getJSONObject("userCredentials").getString("username");
        SingleActorDAOIF profile = RegistrySessionService.getActor(server, username);
        String sessionId = SessionFacade.logIn(profile, LocaleSerializer.deserialize(locales));
        JsonObject json = new JsonObject();
        json.addProperty("sessionId", sessionId);
        json.addProperty("username", username);
        return json.toString();
    } catch (JSONException | OAuthSystemException | OAuthProblemException e) {
        throw new InvalidLoginException(e);
    }
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) JsonObject(com.google.gson.JsonObject) JSONException(org.json.JSONException) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) JSONObject(org.json.JSONObject) InvalidLoginException(com.runwaysdk.session.InvalidLoginException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) SingleActorDAOIF(com.runwaysdk.business.rbac.SingleActorDAOIF) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OauthServer(net.geoprism.account.OauthServer) Authenticate(com.runwaysdk.business.rbac.Authenticate)

Example 60 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project entando-core by entando.

the class AuthEndpointServlet method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    OAuthAuthzRequest oauthRequest = null;
    OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
    IApiOAuthorizationCodeManager codeManager = (IApiOAuthorizationCodeManager) ApsWebApplicationUtils.getBean(SystemConstants.OAUTH2_AUTHORIZATION_CODE_MANAGER, request);
    try {
        oauthRequest = new OAuthAuthzRequest(request);
        if (validateClient(oauthRequest, request, response)) {
            // build response according to response_type
            String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE) == null ? OAuth.OAUTH_RESPONSE_TYPE : oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
            OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
            final String authorizationCode = oauthIssuerImpl.authorizationCode();
            final int expires = 3;
            AuthorizationCode authCode = new AuthorizationCode();
            authCode.setAuthorizationCode(authorizationCode);
            // gets a calendar using the default time zone and locale.
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND, expires);
            authCode.setExpires(calendar.getTimeInMillis());
            authCode.setClientId(oauthRequest.getClientId());
            authCode.setSource(request.getRemoteAddr());
            codeManager.addAuthorizationCode(authCode);
            if (responseType.equals(ResponseType.CODE.toString())) {
                builder.setCode(authorizationCode);
            }
            if (responseType.equals(ResponseType.TOKEN.toString())) {
                builder.setAccessToken(authorizationCode);
                builder.setExpiresIn((long) expires);
            }
            String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
            final OAuthResponse resp = builder.location(redirectURI).buildQueryMessage();
            final int status = resp.getResponseStatus();
            response.setStatus(status);
            response.sendRedirect(resp.getLocationUri());
        } else {
            logger.warn("OAuth2 authentication failed");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (OAuthSystemException ex) {
        logger.error("System exception {} ", ex.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (OAuthProblemException ex) {
        logger.error("OAuth2 error {} ", ex.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (IOException e) {
        logger.error("IOException {} ", e);
    }
}
Also used : AuthorizationCode(org.entando.entando.aps.system.services.oauth2.model.AuthorizationCode) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Calendar(java.util.Calendar) IOException(java.io.IOException) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) OAuthIssuerImpl(org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) IApiOAuthorizationCodeManager(org.entando.entando.aps.system.services.oauth2.IApiOAuthorizationCodeManager) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)47 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)36 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)20 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)14 MediaType (okhttp3.MediaType)13 RequestBody (okhttp3.RequestBody)13 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)11 Path (javax.ws.rs.Path)10 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)9 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 HashMap (java.util.HashMap)8