Search in sources :

Example 6 with OAuthConsumerToken

use of org.springframework.security.oauth.consumer.OAuthConsumerToken in project spring-security-oauth by spring-projects.

the class CoreOAuthConsumerSupportTests method testGetTokenFromProvider.

/**
 * getTokenFromProvider
 */
@Test
public void testGetTokenFromProvider() throws Exception {
    final ByteArrayInputStream in = new ByteArrayInputStream("oauth_token=mytoken&oauth_token_secret=mytokensecret".getBytes("UTF-8"));
    CoreOAuthConsumerSupport support = new CoreOAuthConsumerSupport() {

        @Override
        protected InputStream readResource(ProtectedResourceDetails details, URL url, String httpMethod, OAuthConsumerToken token, Map<String, String> additionalParameters, Map<String, String> additionalRequestHeaders) {
            return in;
        }
    };
    URL url = new URL("https://myhost.com/somepath?with=some&query=params&too");
    when(details.getId()).thenReturn("resourceId");
    OAuthConsumerToken token = support.getTokenFromProvider(details, url, "POST", null, null);
    assertFalse(token.isAccessToken());
    assertEquals("mytoken", token.getValue());
    assertEquals("mytokensecret", token.getSecret());
    assertEquals("resourceId", token.getResourceId());
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) URL(java.net.URL) ProtectedResourceDetails(org.springframework.security.oauth.consumer.ProtectedResourceDetails) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) Test(org.junit.Test)

Example 7 with OAuthConsumerToken

use of org.springframework.security.oauth.consumer.OAuthConsumerToken in project spring-security-oauth by spring-projects.

the class OAuthConsumerContextFilterTests method testGetUserAuthorizationRedirectURL.

/**
 * tests getting the user authorization redirect URL.
 */
@Test
public void testGetUserAuthorizationRedirectURL() throws Exception {
    OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter();
    OAuthConsumerToken token = new OAuthConsumerToken();
    token.setResourceId("resourceId");
    token.setValue("mytoken");
    when(details.getUserAuthorizationURL()).thenReturn("http://user-auth/context?with=some&queryParams");
    when(details.isUse10a()).thenReturn(false);
    assertEquals("http://user-auth/context?with=some&queryParams&oauth_token=mytoken&oauth_callback=urn%3A%2F%2Fcallback%3Fwith%3Dsome%26query%3Dparams", filter.getUserAuthorizationRedirectURL(details, token, "urn://callback?with=some&query=params"));
    when(details.getUserAuthorizationURL()).thenReturn("http://user-auth/context?with=some&queryParams");
    when(details.isUse10a()).thenReturn(true);
    assertEquals("http://user-auth/context?with=some&queryParams&oauth_token=mytoken", filter.getUserAuthorizationRedirectURL(details, token, "urn://callback?with=some&query=params"));
}
Also used : OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) Test(org.junit.Test)

Example 8 with OAuthConsumerToken

use of org.springframework.security.oauth.consumer.OAuthConsumerToken in project spring-security-oauth by spring-projects.

the class OAuthConsumerContextFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    OAuthSecurityContextImpl context = new OAuthSecurityContextImpl();
    context.setDetails(request);
    Map<String, OAuthConsumerToken> rememberedTokens = getRememberMeServices().loadRememberedTokens(request, response);
    Map<String, OAuthConsumerToken> accessTokens = new TreeMap<String, OAuthConsumerToken>();
    Map<String, OAuthConsumerToken> requestTokens = new TreeMap<String, OAuthConsumerToken>();
    if (rememberedTokens != null) {
        for (Map.Entry<String, OAuthConsumerToken> tokenEntry : rememberedTokens.entrySet()) {
            OAuthConsumerToken token = tokenEntry.getValue();
            if (token != null) {
                if (token.isAccessToken()) {
                    accessTokens.put(tokenEntry.getKey(), token);
                } else {
                    requestTokens.put(tokenEntry.getKey(), token);
                }
            }
        }
    }
    context.setAccessTokens(accessTokens);
    OAuthSecurityContextHolder.setContext(context);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute() + "'.");
    }
    try {
        try {
            request.setAttribute(getAccessTokensRequestAttribute(), new ArrayList<OAuthConsumerToken>(accessTokens.values()));
            chain.doFilter(request, response);
        } catch (Exception e) {
            try {
                ProtectedResourceDetails resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e);
                String neededResourceId = resourceThatNeedsAuthorization.getId();
                while (!accessTokens.containsKey(neededResourceId)) {
                    OAuthConsumerToken token = requestTokens.remove(neededResourceId);
                    if (token == null) {
                        token = getTokenServices().getToken(neededResourceId);
                    }
                    String verifier = request.getParameter(OAuthProviderParameter.oauth_verifier.toString());
                    // if there is NO access token and (we're not using 1.0a or the verifier is not null)
                    if (token == null || (!token.isAccessToken() && (!resourceThatNeedsAuthorization.isUse10a() || verifier == null))) {
                        // if there's a request token, but no verifier, we'll assume that a previous oauth request failed and we need to get a new request token.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining request token for resource: " + neededResourceId);
                        }
                        // obtain authorization.
                        String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
                        token = getConsumerSupport().getUnauthorizedRequestToken(neededResourceId, callbackURL);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Request token obtained for resource " + neededResourceId + ": " + token);
                        }
                        // okay, we've got a request token, now we need to authorize it.
                        requestTokens.put(neededResourceId, token);
                        getTokenServices().storeToken(neededResourceId, token);
                        String redirect = getUserAuthorizationRedirectURL(resourceThatNeedsAuthorization, token, callbackURL);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Redirecting request to " + redirect + " for user authorization of the request token for resource " + neededResourceId + ".");
                        }
                        request.setAttribute("org.springframework.security.oauth.consumer.AccessTokenRequiredException", e);
                        this.redirectStrategy.sendRedirect(request, response, redirect);
                        return;
                    } else if (!token.isAccessToken()) {
                        // we have a presumably authorized request token, let's try to get an access token with it.
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining access token for resource: " + neededResourceId);
                        }
                        // authorize the request token and store it.
                        try {
                            token = getConsumerSupport().getAccessToken(token, verifier);
                        } finally {
                            getTokenServices().removeToken(neededResourceId);
                        }
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Access token " + token + " obtained for resource " + neededResourceId + ". Now storing and using.");
                        }
                        getTokenServices().storeToken(neededResourceId, token);
                    }
                    accessTokens.put(neededResourceId, token);
                    try {
                        // try again
                        if (!response.isCommitted()) {
                            request.setAttribute(getAccessTokensRequestAttribute(), new ArrayList<OAuthConsumerToken>(accessTokens.values()));
                            chain.doFilter(request, response);
                        } else {
                            // dang. what do we do now?
                            throw new IllegalStateException("Unable to reprocess filter chain with needed OAuth2 resources because the response is already committed.");
                        }
                    } catch (Exception e1) {
                        resourceThatNeedsAuthorization = checkForResourceThatNeedsAuthorization(e1);
                        neededResourceId = resourceThatNeedsAuthorization.getId();
                    }
                }
            } catch (OAuthRequestFailedException eo) {
                fail(request, response, eo);
            } catch (Exception ex) {
                Throwable[] causeChain = getThrowableAnalyzer().determineCauseChain(ex);
                OAuthRequestFailedException rfe = (OAuthRequestFailedException) getThrowableAnalyzer().getFirstThrowableOfType(OAuthRequestFailedException.class, causeChain);
                if (rfe != null) {
                    fail(request, response, rfe);
                } else {
                    // Rethrow ServletExceptions and RuntimeExceptions as-is
                    if (ex instanceof ServletException) {
                        throw (ServletException) ex;
                    } else if (ex instanceof RuntimeException) {
                        throw (RuntimeException) ex;
                    }
                    // Wrap other Exceptions. These are not expected to happen
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        OAuthSecurityContextHolder.setContext(null);
        HashMap<String, OAuthConsumerToken> tokensToRemember = new HashMap<String, OAuthConsumerToken>();
        tokensToRemember.putAll(requestTokens);
        tokensToRemember.putAll(accessTokens);
        getRememberMeServices().rememberTokens(tokensToRemember, request, response);
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) TreeMap(java.util.TreeMap) OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException) ServletException(javax.servlet.ServletException) AccessTokenRequiredException(org.springframework.security.oauth.consumer.AccessTokenRequiredException) OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) OAuthSecurityContextImpl(org.springframework.security.oauth.consumer.OAuthSecurityContextImpl) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ProtectedResourceDetails(org.springframework.security.oauth.consumer.ProtectedResourceDetails)

Example 9 with OAuthConsumerToken

use of org.springframework.security.oauth.consumer.OAuthConsumerToken in project spring-security-oauth by spring-projects.

the class HttpSessionBasedTokenServices method getToken.

public OAuthConsumerToken getToken(String resourceId) throws AuthenticationException {
    HttpSession session = getSession();
    OAuthConsumerToken consumerToken = (OAuthConsumerToken) session.getAttribute(KEY_PREFIX + "#" + resourceId);
    if (consumerToken != null) {
        Long expiration = (Long) session.getAttribute(KEY_PREFIX + "#" + resourceId + "#EXPIRATION");
        if (expiration != null && (System.currentTimeMillis() > expiration)) {
            // token expired; remove it
            removeToken(resourceId);
            consumerToken = null;
        }
    }
    return consumerToken;
}
Also used : HttpSession(javax.servlet.http.HttpSession) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken)

Example 10 with OAuthConsumerToken

use of org.springframework.security.oauth.consumer.OAuthConsumerToken in project spring-security-oauth by spring-projects.

the class OAuthConsumerProcessingFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain);
    if (!accessTokenDeps.isEmpty()) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (isRequireAuthenticated() && !authentication.isAuthenticated()) {
            throw new InsufficientAuthenticationException("An authenticated principal must be present.");
        }
        OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
        if (context == null) {
            throw new IllegalStateException("No OAuth security context has been established. Unable to access resources.");
        }
        Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens();
        for (String dependency : accessTokenDeps) {
            if (!accessTokens.containsKey(dependency)) {
                throw new AccessTokenRequiredException(getProtectedResourceDetailsService().loadProtectedResourceDetailsById(dependency));
            }
        }
        chain.doFilter(request, response);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No access token dependencies for request.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) AccessTokenRequiredException(org.springframework.security.oauth.consumer.AccessTokenRequiredException) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthSecurityContext(org.springframework.security.oauth.consumer.OAuthSecurityContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken)

Aggregations

OAuthConsumerToken (org.springframework.security.oauth.consumer.OAuthConsumerToken)18 HashMap (java.util.HashMap)12 Test (org.junit.Test)12 Map (java.util.Map)9 TreeMap (java.util.TreeMap)7 ProtectedResourceDetails (org.springframework.security.oauth.consumer.ProtectedResourceDetails)7 URL (java.net.URL)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 MockHttpSession (org.springframework.mock.web.MockHttpSession)4 LinkedHashSet (java.util.LinkedHashSet)3 Set (java.util.Set)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 AccessTokenRequiredException (org.springframework.security.oauth.consumer.AccessTokenRequiredException)3 OAuthRequestFailedException (org.springframework.security.oauth.consumer.OAuthRequestFailedException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 HttpSession (javax.servlet.http.HttpSession)2 OAuthSecurityContext (org.springframework.security.oauth.consumer.OAuthSecurityContext)2