Search in sources :

Example 1 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth.provider.OAuthServiceException in project cxf by apache.

the class OAuthClientUtils method getToken.

private static Token getToken(WebClient tokenService, OAuthAccessor accessor, Map<String, String> parameters) throws OAuthServiceException {
    String header = doGetAuthorizationHeader(accessor, "POST", tokenService.getBaseURI().toString(), parameters);
    try {
        tokenService.replaceHeader("Authorization", header);
        Form form = tokenService.post(null, Form.class);
        return new Token(form.asMap().getFirst("oauth_token"), form.asMap().getFirst("oauth_token_secret"));
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Form(javax.ws.rs.core.Form) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException)

Example 2 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth.provider.OAuthServiceException in project cxf by apache.

the class AccessTokenHandler method handle.

public Response handle(MessageContext mc, OAuthDataProvider dataProvider, OAuthValidator validator) {
    try {
        OAuthMessage oAuthMessage = OAuthUtils.getOAuthMessage(mc, mc.getHttpServletRequest(), REQUIRED_PARAMETERS);
        RequestToken requestToken = dataProvider.getRequestToken(oAuthMessage.getToken());
        if (requestToken == null) {
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        String oauthVerifier = oAuthMessage.getParameter(OAuth.OAUTH_VERIFIER);
        if (StringUtils.isEmpty(oauthVerifier)) {
            if (requestToken.getSubject() != null && requestToken.isPreAuthorized()) {
                LOG.fine("Preauthorized request token");
            } else {
                throw new OAuthProblemException(OAuthConstants.VERIFIER_INVALID);
            }
        } else if (!oauthVerifier.equals(requestToken.getVerifier())) {
            throw new OAuthProblemException(OAuthConstants.VERIFIER_INVALID);
        }
        OAuthUtils.validateMessage(oAuthMessage, requestToken.getClient(), requestToken, dataProvider, validator);
        AccessTokenRegistration reg = new AccessTokenRegistration();
        reg.setRequestToken(requestToken);
        AccessToken accessToken = dataProvider.createAccessToken(reg);
        // create response
        Map<String, Object> responseParams = new HashMap<>();
        responseParams.put(OAuth.OAUTH_TOKEN, accessToken.getTokenKey());
        responseParams.put(OAuth.OAUTH_TOKEN_SECRET, accessToken.getTokenSecret());
        String responseString = OAuth.formEncode(responseParams.entrySet());
        return Response.ok(responseString).build();
    } catch (OAuthProblemException e) {
        LOG.log(Level.WARNING, "An OAuth-related problem: {0}", new Object[] { e.fillInStackTrace() });
        int code = e.getHttpStatusCode();
        if (code == HttpServletResponse.SC_OK) {
            code = e.getProblem() == OAuth.Problems.CONSUMER_KEY_UNKNOWN ? 401 : 400;
        }
        return OAuthUtils.handleException(mc, e, code);
    } catch (OAuthServiceException e) {
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected internal server exception: {0}", new Object[] { e.fillInStackTrace() });
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) OAuthMessage(net.oauth.OAuthMessage) HashMap(java.util.HashMap) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) RequestToken(org.apache.cxf.rs.security.oauth.data.RequestToken) AccessToken(org.apache.cxf.rs.security.oauth.data.AccessToken) AccessTokenRegistration(org.apache.cxf.rs.security.oauth.data.AccessTokenRegistration) OAuthProblemException(net.oauth.OAuthProblemException) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException)

Example 3 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth.provider.OAuthServiceException in project cxf by apache.

the class AuthorizationRequestHandler method handle.

public Response handle(MessageContext mc, OAuthDataProvider dataProvider) {
    HttpServletRequest request = mc.getHttpServletRequest();
    try {
        OAuthMessage oAuthMessage = OAuthUtils.getOAuthMessage(mc, request, REQUIRED_PARAMETERS);
        new DefaultOAuthValidator().checkSingleParameter(oAuthMessage);
        RequestToken token = dataProvider.getRequestToken(oAuthMessage.getToken());
        if (token == null) {
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        String decision = oAuthMessage.getParameter(OAuthConstants.AUTHORIZATION_DECISION_KEY);
        OAuthAuthorizationData secData = new OAuthAuthorizationData();
        if (!compareRequestSessionTokens(request, oAuthMessage)) {
            if (decision != null) {
                // this is a user decision request, the session has expired or been possibly hijacked
                LOG.warning("Session authenticity token is missing or invalid");
                throw ExceptionUtils.toBadRequestException(null, null);
            }
            // assume it is an initial authorization request
            addAuthenticityTokenToSession(secData, request);
            return Response.ok(addAdditionalParams(secData, dataProvider, token)).build();
        }
        boolean allow = OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(decision);
        Map<String, String> queryParams = new HashMap<>();
        if (allow) {
            SecurityContext sc = (SecurityContext) mc.get(SecurityContext.class.getName());
            List<String> roleNames = Collections.emptyList();
            if (sc instanceof LoginSecurityContext) {
                roleNames = new ArrayList<>();
                Set<Principal> roles = ((LoginSecurityContext) sc).getUserRoles();
                for (Principal p : roles) {
                    roleNames.add(p.getName());
                }
            }
            token.setSubject(new UserSubject(sc.getUserPrincipal() == null ? null : sc.getUserPrincipal().getName(), roleNames));
            AuthorizationInput input = new AuthorizationInput();
            input.setToken(token);
            Set<OAuthPermission> approvedScopesSet = new HashSet<>();
            List<OAuthPermission> originalScopes = token.getScopes();
            for (OAuthPermission perm : originalScopes) {
                String param = oAuthMessage.getParameter(perm.getPermission() + "_status");
                if (param != null && OAuthConstants.AUTHORIZATION_DECISION_ALLOW.equals(param)) {
                    approvedScopesSet.add(perm);
                }
            }
            List<OAuthPermission> approvedScopes = new LinkedList<OAuthPermission>(approvedScopesSet);
            if (approvedScopes.isEmpty()) {
                approvedScopes = originalScopes;
            } else if (approvedScopes.size() < originalScopes.size()) {
                for (OAuthPermission perm : originalScopes) {
                    if (perm.isDefault() && !approvedScopes.contains(perm)) {
                        approvedScopes.add(perm);
                    }
                }
            }
            input.setApprovedScopes(approvedScopes);
            String verifier = dataProvider.finalizeAuthorization(input);
            queryParams.put(OAuth.OAUTH_VERIFIER, verifier);
        } else {
            dataProvider.removeToken(token);
        }
        queryParams.put(OAuth.OAUTH_TOKEN, token.getTokenKey());
        if (token.getState() != null) {
            queryParams.put(OAuthConstants.X_OAUTH_STATE, token.getState());
        }
        String callbackValue = getCallbackValue(token);
        if (OAuthConstants.OAUTH_CALLBACK_OOB.equals(callbackValue)) {
            OOBAuthorizationResponse bean = convertQueryParamsToOOB(queryParams);
            return Response.ok().entity(bean).build();
        }
        URI callbackURI = buildCallbackURI(callbackValue, queryParams);
        return Response.seeOther(callbackURI).build();
    } catch (OAuthProblemException e) {
        LOG.log(Level.WARNING, "An OAuth related problem: {0}", new Object[] { e.fillInStackTrace() });
        int code = e.getHttpStatusCode();
        if (code == HttpServletResponse.SC_OK) {
            code = e.getProblem() == OAuth.Problems.CONSUMER_KEY_UNKNOWN ? 401 : 400;
        }
        return OAuthUtils.handleException(mc, e, code);
    } catch (OAuthServiceException e) {
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected internal server exception: {0}", new Object[] { e.fillInStackTrace() });
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : OAuthPermission(org.apache.cxf.rs.security.oauth.data.OAuthPermission) HashMap(java.util.HashMap) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) AuthorizationInput(org.apache.cxf.rs.security.oauth.data.AuthorizationInput) URI(java.net.URI) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSubject(org.apache.cxf.rs.security.oauth.data.UserSubject) RequestToken(org.apache.cxf.rs.security.oauth.data.RequestToken) HashSet(java.util.HashSet) OAuthMessage(net.oauth.OAuthMessage) LinkedList(java.util.LinkedList) OAuthProblemException(net.oauth.OAuthProblemException) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) IOException(java.io.IOException) OAuthProblemException(net.oauth.OAuthProblemException) SecurityContext(org.apache.cxf.security.SecurityContext) LoginSecurityContext(org.apache.cxf.security.LoginSecurityContext) DefaultOAuthValidator(org.apache.cxf.rs.security.oauth.provider.DefaultOAuthValidator) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth.data.OAuthAuthorizationData) Principal(java.security.Principal)

Example 4 with OAuthServiceException

use of org.apache.cxf.rs.security.oauth.provider.OAuthServiceException in project cxf by apache.

the class RequestTokenHandler method handle.

public Response handle(MessageContext mc, OAuthDataProvider dataProvider, OAuthValidator validator) {
    try {
        OAuthMessage oAuthMessage = OAuthUtils.getOAuthMessage(mc, mc.getHttpServletRequest(), REQUIRED_PARAMETERS);
        Client client = dataProvider.getClient(oAuthMessage.getParameter(OAuth.OAUTH_CONSUMER_KEY));
        // client credentials not found
        if (client == null) {
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        OAuthUtils.validateMessage(oAuthMessage, client, null, dataProvider, validator);
        String callback = oAuthMessage.getParameter(OAuth.OAUTH_CALLBACK);
        validateCallbackURL(client, callback);
        List<String> scopes = OAuthUtils.parseParamValue(oAuthMessage.getParameter(OAuthConstants.X_OAUTH_SCOPE), defaultScope);
        RequestTokenRegistration reg = new RequestTokenRegistration();
        reg.setClient(client);
        reg.setCallback(callback);
        reg.setState(oAuthMessage.getParameter(OAuthConstants.X_OAUTH_STATE));
        reg.setScopes(scopes);
        reg.setLifetime(tokenLifetime);
        reg.setIssuedAt(System.currentTimeMillis() / 1000);
        RequestToken requestToken = dataProvider.createRequestToken(reg);
        if (LOG.isLoggable(Level.FINE)) {
            LOG.log(Level.FINE, "Preparing Temporary Credentials Endpoint correct response");
        }
        // create response
        Map<String, Object> responseParams = new HashMap<>();
        responseParams.put(OAuth.OAUTH_TOKEN, requestToken.getTokenKey());
        responseParams.put(OAuth.OAUTH_TOKEN_SECRET, requestToken.getTokenSecret());
        responseParams.put(OAuth.OAUTH_CALLBACK_CONFIRMED, Boolean.TRUE);
        String responseBody = OAuth.formEncode(responseParams.entrySet());
        return Response.ok(responseBody).build();
    } catch (OAuthProblemException e) {
        LOG.log(Level.WARNING, "An OAuth-related problem: {0}", new Object[] { e.fillInStackTrace() });
        int code = e.getHttpStatusCode();
        if (code == HttpServletResponse.SC_OK) {
            code = e.getProblem() == OAuth.Problems.CONSUMER_KEY_UNKNOWN ? 401 : 400;
        }
        return OAuthUtils.handleException(mc, e, code);
    } catch (OAuthServiceException e) {
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected internal server exception: {0}", new Object[] { e.fillInStackTrace() });
        return OAuthUtils.handleException(mc, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) OAuthMessage(net.oauth.OAuthMessage) HashMap(java.util.HashMap) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) RequestToken(org.apache.cxf.rs.security.oauth.data.RequestToken) Client(org.apache.cxf.rs.security.oauth.data.Client) OAuthProblemException(net.oauth.OAuthProblemException) OAuthServiceException(org.apache.cxf.rs.security.oauth.provider.OAuthServiceException) RequestTokenRegistration(org.apache.cxf.rs.security.oauth.data.RequestTokenRegistration)

Aggregations

OAuthServiceException (org.apache.cxf.rs.security.oauth.provider.OAuthServiceException)4 HashMap (java.util.HashMap)3 OAuthMessage (net.oauth.OAuthMessage)3 OAuthProblemException (net.oauth.OAuthProblemException)3 RequestToken (org.apache.cxf.rs.security.oauth.data.RequestToken)3 IOException (java.io.IOException)1 URI (java.net.URI)1 Principal (java.security.Principal)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 Form (javax.ws.rs.core.Form)1 AccessToken (org.apache.cxf.rs.security.oauth.data.AccessToken)1 AccessTokenRegistration (org.apache.cxf.rs.security.oauth.data.AccessTokenRegistration)1 AuthorizationInput (org.apache.cxf.rs.security.oauth.data.AuthorizationInput)1 Client (org.apache.cxf.rs.security.oauth.data.Client)1 OAuthAuthorizationData (org.apache.cxf.rs.security.oauth.data.OAuthAuthorizationData)1 OAuthPermission (org.apache.cxf.rs.security.oauth.data.OAuthPermission)1 RequestTokenRegistration (org.apache.cxf.rs.security.oauth.data.RequestTokenRegistration)1