Search in sources :

Example 1 with OAuth2ContextConfiguration

use of org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration in project spring-security-oauth by spring-projects.

the class AbstractClientCredentialsProviderTests method testInvalidCredentials.

@Test
@OAuth2ContextConfiguration(resource = InvalidClientCredentials.class, initialize = false)
public void testInvalidCredentials() throws Exception {
    context.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider() {

        @Override
        protected ResponseErrorHandler getResponseErrorHandler() {
            return new DefaultResponseErrorHandler() {

                public void handleError(ClientHttpResponse response) throws IOException {
                    responseHeaders = response.getHeaders();
                    responseStatus = response.getStatusCode();
                }
            };
        }
    });
    try {
        context.getAccessToken();
        fail("Expected ResourceAccessException");
    } catch (Exception e) {
    // System.err.println(responseHeaders);
    // ignore
    }
    String header = responseHeaders.getFirst("WWW-Authenticate");
    assertTrue("Wrong header: " + header, header.contains("Basic realm"));
    assertEquals(HttpStatus.UNAUTHORIZED, responseStatus);
}
Also used : DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) IOException(java.io.IOException) ClientCredentialsAccessTokenProvider(org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) IOException(java.io.IOException) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 2 with OAuth2ContextConfiguration

use of org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration in project spring-security-oauth by spring-projects.

the class OAuth2ContextSetup method initializeIfNecessary.

private void initializeIfNecessary(FrameworkMethod method, final Object target) {
    final TestClass testClass = new TestClass(target.getClass());
    OAuth2ContextConfiguration contextConfiguration = findOAuthContextConfiguration(method, testClass);
    if (contextConfiguration == null) {
        // Nothing to do
        return;
    }
    this.initializeAccessToken = contextConfiguration.initialize();
    this.resource = creatResource(target, contextConfiguration);
    final List<FrameworkMethod> befores = testClass.getAnnotatedMethods(BeforeOAuth2Context.class);
    if (!befores.isEmpty()) {
        logger.debug("Running @BeforeOAuth2Context methods");
        for (FrameworkMethod before : befores) {
            RestOperations savedServerClient = clientHolder.getRestTemplate();
            OAuth2ContextConfiguration beforeConfiguration = findOAuthContextConfiguration(before, testClass);
            if (beforeConfiguration != null) {
                OAuth2ProtectedResourceDetails resource = creatResource(target, beforeConfiguration);
                AccessTokenRequest beforeRequest = new DefaultAccessTokenRequest();
                beforeRequest.setAll(parameters);
                OAuth2RestTemplate client = createRestTemplate(resource, beforeRequest);
                clientHolder.setRestTemplate(client);
            }
            AccessTokenRequest request = new DefaultAccessTokenRequest();
            request.setAll(parameters);
            this.client = createRestTemplate(this.resource, request);
            List<FrameworkMethod> list = Arrays.asList(before);
            try {
                new RunBefores(new Statement() {

                    public void evaluate() {
                    }
                }, list, target).evaluate();
            } catch (AssumptionViolatedException e) {
                throw e;
            } catch (RuntimeException e) {
                throw e;
            } catch (AssertionError e) {
                throw e;
            } catch (Throwable e) {
                logger.debug("Exception in befores", e);
                Assert.assertThat(e, CoreMatchers.not(CoreMatchers.anything()));
            } finally {
                clientHolder.setRestTemplate(savedServerClient);
            }
        }
    }
}
Also used : AssumptionViolatedException(org.junit.internal.AssumptionViolatedException) Statement(org.junit.runners.model.Statement) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) TestClass(org.junit.runners.model.TestClass) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) DefaultAccessTokenRequest(org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) RestOperations(org.springframework.web.client.RestOperations) RunBefores(org.junit.internal.runners.statements.RunBefores) FrameworkMethod(org.junit.runners.model.FrameworkMethod) DefaultAccessTokenRequest(org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest)

Example 3 with OAuth2ContextConfiguration

use of org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration in project spring-security-oauth by spring-projects.

the class AdminEndpointsTests method testRevokeTokenByUser.

@Test
@OAuth2ContextConfiguration(ResourceOwnerWriteOnly.class)
public void testRevokeTokenByUser() throws Exception {
    OAuth2AccessToken token = context.getAccessToken();
    String tokenValueBeforeDeletion = token.getValue();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<?> request = new HttpEntity<Void>(headers);
    assertEquals(HttpStatus.NO_CONTENT, serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/sparklr2/oauth/users/{user}/tokens/{token}"), HttpMethod.DELETE, request, Void.class, "marissa", token.getValue()).getStatusCode());
    try {
        // The request above will delete the oauth token so that the next request will initially fail. However,
        // the failure will be detected and a new access token will be obtained.  The new access token
        // only has "write" scope and the requested resource needs "read" scope.  So, an insufficient_scope
        // exception should be thrown.
        ResponseEntity<String> result = serverRunning.getForString("/sparklr2/oauth/clients/my-client-with-registered-redirect/users/marissa/tokens", headers);
        fail("Should have thrown an exception");
        assertNotNull(result);
    } catch (InsufficientScopeException ex) {
        assertEquals(HttpStatus.FORBIDDEN.value(), ex.getHttpErrorCode());
        assertEquals("insufficient_scope", ex.getOAuth2ErrorCode());
        String secondTokenWithWriteOnlyScope = context.getOAuth2ClientContext().getAccessToken().getValue();
        assertNotNull(secondTokenWithWriteOnlyScope);
        assertFalse(secondTokenWithWriteOnlyScope.equals(tokenValueBeforeDeletion));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) HttpEntity(org.springframework.http.HttpEntity) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 4 with OAuth2ContextConfiguration

use of org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method testUnauthenticatedAuthorizationRequestRedirectsToLogin.

@Test
@OAuth2ContextConfiguration(resource = MyLessTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRequestRedirectsToLogin() throws Exception {
    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setCurrentUri("http://anywhere");
    request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    String location = null;
    try {
        String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
        assertNotNull(code);
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        location = e.getRedirectUri();
    }
    assertNotNull(location);
    assertEquals(serverRunning.getUrl("/sparklr2/login.jsp"), location);
}
Also used : AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 5 with OAuth2ContextConfiguration

use of org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method testSuccessfulAuthorizationCodeFlow.

@Test
@OAuth2ContextConfiguration(resource = MyLessTrustedClient.class, initialize = false)
public void testSuccessfulAuthorizationCodeFlow() throws Exception {
    // Once the request is ready and approved, we can continue with the access token
    approveAccessTokenGrant("http://anywhere", true);
    // Finally everything is in place for the grant to happen...
    assertNotNull(context.getAccessToken());
    AccessTokenRequest request = context.getAccessTokenRequest();
    assertNotNull(request.getAuthorizationCode());
    assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr2/photos?format=json"));
}
Also used : AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)28 OAuth2ContextConfiguration (org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration)28 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7 HttpHeaders (org.springframework.http.HttpHeaders)4 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)4 IOException (java.io.IOException)3 ClientCredentialsAccessTokenProvider (org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider)3 InsufficientScopeException (org.springframework.security.oauth2.common.exceptions.InsufficientScopeException)3 DefaultResponseErrorHandler (org.springframework.web.client.DefaultResponseErrorHandler)3 ResponseErrorHandler (org.springframework.web.client.ResponseErrorHandler)3 TestRestTemplate (org.springframework.boot.test.web.client.TestRestTemplate)2 MediaType (org.springframework.http.MediaType)2 OAuth2RestTemplate (org.springframework.security.oauth2.client.OAuth2RestTemplate)2 UserRedirectRequiredException (org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)2 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)2 RedirectMismatchException (org.springframework.security.oauth2.common.exceptions.RedirectMismatchException)2 HashSet (java.util.HashSet)1 Map (java.util.Map)1 ExecutorService (java.util.concurrent.ExecutorService)1