Search in sources :

Example 16 with OAuthProblemException

use of net.oauth.OAuthProblemException in project zm-mailbox by Zimbra.

the class OAuthServiceProvider method getAccessor.

/**
     * Get the access token and token secret for the given oauth_token.
     */
public static synchronized OAuthAccessor getAccessor(OAuthMessage requestMessage) throws IOException, OAuthProblemException, ServiceException {
    // try to load from memcache if not throw exception
    String consumer_token = requestMessage.getToken();
    OAuthAccessor accessor = null;
    accessor = OAuthTokenCache.get(consumer_token, OAuthTokenCache.REQUEST_TOKEN_TYPE);
    if (accessor == null) {
        accessor = OAuthTokenCache.get(consumer_token, OAuthTokenCache.ACCESS_TOKEN_TYPE);
    }
    if (accessor == null) {
        OAuthProblemException problem = new OAuthProblemException("token_expired");
        throw problem;
    }
    return accessor;
}
Also used : OAuthAccessor(net.oauth.OAuthAccessor) OAuthProblemException(net.oauth.OAuthProblemException)

Example 17 with OAuthProblemException

use of net.oauth.OAuthProblemException in project cxf by apache.

the class CallbackURLController method handleRequest.

@RequestMapping("/callback")
protected ModelAndView handleRequest(@ModelAttribute("oAuthParams") OAuthParams oAuthParams, HttpServletRequest request) throws Exception {
    OAuthMessage message = OAuthServlet.getMessage(request, request.getRequestURL().toString());
    try {
        message.requireParameters(OAuth.OAUTH_TOKEN, OAuth.OAUTH_VERIFIER);
        oAuthParams.setOauthToken(message.getToken());
        oAuthParams.setOauthVerifier(message.getParameter(OAuth.OAUTH_VERIFIER));
        oAuthParams.setClientID(Common.findCookieValue(request, "clientID"));
        oAuthParams.setClientSecret(Common.findCookieValue(request, "clientSecret"));
    } catch (OAuthProblemException e) {
        oAuthParams.setErrorMessage("OAuth problem: " + e.getProblem() + e.getParameters().toString());
    }
    return new ModelAndView("tokenRequest");
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) OAuthMessage(net.oauth.OAuthMessage) ModelAndView(org.springframework.web.servlet.ModelAndView) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with OAuthProblemException

use of net.oauth.OAuthProblemException in project cxf by apache.

the class AbstractAuthFilter method handleOAuthRequest.

/**
 * Authenticates the third-party consumer and returns
 * {@link OAuthInfo} bean capturing the information about the request.
 * @param req http request
 * @return OAuth info
 * @see OAuthInfo
 * @throws Exception
 * @throws OAuthProblemException
 */
protected OAuthInfo handleOAuthRequest(HttpServletRequest req) throws Exception, OAuthProblemException {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.log(Level.FINE, "OAuth security filter for url: {0}", req.getRequestURL());
    }
    AccessToken accessToken = null;
    Client client = null;
    OAuthMessage oAuthMessage = OAuthServlet.getMessage(new CustomHttpServletWrapper(req), OAuthServlet.getRequestURL(req));
    if (oAuthMessage.getParameter(OAuth.OAUTH_TOKEN) != null) {
        oAuthMessage.requireParameters(REQUIRED_PARAMETERS);
        accessToken = dataProvider.getAccessToken(oAuthMessage.getToken());
        // check if access token is not null
        if (accessToken == null) {
            LOG.warning("Access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
        client = accessToken.getClient();
        OAuthUtils.validateMessage(oAuthMessage, client, accessToken, dataProvider, validator);
    } else {
        String consumerKey = null;
        String consumerSecret = null;
        String authHeader = oAuthMessage.getHeader("Authorization");
        if (authHeader != null) {
            if (authHeader.startsWith("OAuth")) {
                consumerKey = oAuthMessage.getParameter(OAuth.OAUTH_CONSUMER_KEY);
                consumerSecret = oAuthMessage.getParameter(OAuthConstants.OAUTH_CONSUMER_SECRET);
            } else if (authHeader.startsWith("Basic")) {
                AuthorizationPolicy policy = getAuthorizationPolicy(authHeader);
                if (policy != null) {
                    consumerKey = policy.getUserName();
                    consumerSecret = policy.getPassword();
                }
            }
        }
        if (consumerKey != null) {
            client = dataProvider.getClient(consumerKey);
        }
        if (client == null) {
            LOG.warning("Client is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        if (consumerSecret != null && !consumerSecret.equals(client.getSecretKey())) {
            LOG.warning("Client secret is invalid");
            throw new OAuthProblemException(OAuth.Problems.CONSUMER_KEY_UNKNOWN);
        }
        OAuthUtils.validateMessage(oAuthMessage, client, null, dataProvider, validator);
        accessToken = client.getPreAuthorizedToken();
        if (accessToken == null || !accessToken.isPreAuthorized()) {
            LOG.warning("Preauthorized access token is unavailable");
            throw new OAuthProblemException(OAuth.Problems.TOKEN_REJECTED);
        }
    }
    List<OAuthPermission> permissions = accessToken.getScopes();
    List<OAuthPermission> matchingPermissions = new ArrayList<>();
    for (OAuthPermission perm : permissions) {
        boolean uriOK = checkRequestURI(req, perm.getUris());
        boolean verbOK = checkHttpVerb(req, perm.getHttpVerbs());
        if (uriOK && verbOK) {
            matchingPermissions.add(perm);
        }
    }
    if (!permissions.isEmpty() && matchingPermissions.isEmpty()) {
        String message = "Client has no valid permissions";
        LOG.warning(message);
        throw new OAuthProblemException(message);
    }
    return new OAuthInfo(accessToken, matchingPermissions);
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) OAuthPermission(org.apache.cxf.rs.security.oauth.data.OAuthPermission) OAuthMessage(net.oauth.OAuthMessage) AccessToken(org.apache.cxf.rs.security.oauth.data.AccessToken) ArrayList(java.util.ArrayList) Client(org.apache.cxf.rs.security.oauth.data.Client)

Example 19 with OAuthProblemException

use of net.oauth.OAuthProblemException in project cxf by apache.

the class OAuthRequestFilter method filter.

@Override
public void filter(ContainerRequestContext context) {
    try {
        Message m = JAXRSUtils.getCurrentMessage();
        MessageContext mc = new MessageContextImpl(m);
        OAuthInfo info = handleOAuthRequest(mc.getHttpServletRequest());
        setSecurityContext(mc, m, info);
    } catch (OAuthProblemException e) {
        context.abortWith(Response.status(401).header("WWW-Authenticate", "OAuth").build());
    } catch (Exception e) {
        context.abortWith(Response.status(401).header("WWW-Authenticate", "OAuth").build());
    }
}
Also used : OAuthProblemException(net.oauth.OAuthProblemException) Message(org.apache.cxf.message.Message) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) OAuthProblemException(net.oauth.OAuthProblemException) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 20 with OAuthProblemException

use of net.oauth.OAuthProblemException 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)

Aggregations

OAuthProblemException (net.oauth.OAuthProblemException)23 OAuthMessage (net.oauth.OAuthMessage)8 IOException (java.io.IOException)6 HashMap (java.util.HashMap)4 ServletException (javax.servlet.ServletException)3 OAuthAccessor (net.oauth.OAuthAccessor)3 RequestToken (org.apache.cxf.rs.security.oauth.data.RequestToken)3 OAuthServiceException (org.apache.cxf.rs.security.oauth.provider.OAuthServiceException)3 ServiceException (com.zimbra.common.service.ServiceException)2 Account (com.zimbra.cs.account.Account)2 ArrayList (java.util.ArrayList)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 AccessToken (org.apache.cxf.rs.security.oauth.data.AccessToken)2 Client (org.apache.cxf.rs.security.oauth.data.Client)2 OAuthPermission (org.apache.cxf.rs.security.oauth.data.OAuthPermission)2 AuthToken (com.zimbra.cs.account.AuthToken)1 AuthTokenException (com.zimbra.cs.account.AuthTokenException)1 ZimbraAuthToken (com.zimbra.cs.account.ZimbraAuthToken)1 OAuthAccessorSerializer (com.zimbra.cs.account.oauth.OAuthAccessorSerializer)1 InputStream (java.io.InputStream)1