Example usage for org.springframework.security.oauth2.common.util OAuth2Utils STATE

List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils STATE

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.util OAuth2Utils STATE.

Prototype

String STATE

To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils STATE.

Click Source Link

Document

Constant to use while parsing and formatting parameter maps for OAuth2 requests

Usage

From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey("prompt")) {
        request.getExtensions().put("prompt", inputParams.get("prompt"));
    }// w  ww.  j a  va 2  s  .  c om
    if (inputParams.containsKey("nonce")) {
        request.getExtensions().put("nonce", inputParams.get("nonce"));
    }

    if (inputParams.containsKey("claims")) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims"));
        if (claimsRequest != null) {
            request.getExtensions().put("claims", claimsRequest.toString());
        }
    }

    if (inputParams.containsKey("request")) {
        request.getExtensions().put("request", inputParams.get("request"));
        processRequestObject(inputParams.get("request"), request);
    }

    if ((request.getScope() == null || request.getScope().isEmpty())) {
        if (request.getClientId() != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(request.getClientId());
            Set<String> clientScopes = client.getScope();
            request.setScope(clientScopes);
        }
    }

    return request;
}

From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey(PROMPT)) {
        request.getExtensions().put(PROMPT, inputParams.get(PROMPT));
    }/*from w w w  .j  a  v a  2 s  . c  o m*/
    if (inputParams.containsKey(NONCE)) {
        request.getExtensions().put(NONCE, inputParams.get(NONCE));
    }

    if (inputParams.containsKey(CLAIMS)) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get(CLAIMS));
        if (claimsRequest != null) {
            request.getExtensions().put(CLAIMS, claimsRequest.toString());
        }
    }

    if (inputParams.containsKey(MAX_AGE)) {
        request.getExtensions().put(MAX_AGE, inputParams.get(MAX_AGE));
    }

    if (inputParams.containsKey(LOGIN_HINT)) {
        request.getExtensions().put(LOGIN_HINT, inputParams.get(LOGIN_HINT));
    }

    if (inputParams.containsKey(AUD)) {
        request.getExtensions().put(AUD, inputParams.get(AUD));
    }

    if (inputParams.containsKey(REQUEST)) {
        request.getExtensions().put(REQUEST, inputParams.get(REQUEST));
        processRequestObject(inputParams.get(REQUEST), request);
    }

    if (request.getClientId() != null) {
        try {
            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if ((request.getScope() == null || request.getScope().isEmpty())) {
                Set<String> clientScopes = client.getScope();
                request.setScope(clientScopes);
            }

            if (request.getExtensions().get(MAX_AGE) == null && client.getDefaultMaxAge() != null) {
                request.getExtensions().put(MAX_AGE, client.getDefaultMaxAge().toString());
            }
        } catch (OAuth2Exception e) {
            logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
        }
    }

    return request;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) {
    Map<String, Object> authorizationRequestMap = new HashMap<>();

    authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId());
    authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState());
    authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri());

    if (authorizationRequest.getResponseTypes() != null) {
        authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResponseTypes())));
    }/*from   w  ww .  jav a 2s  .  c  o m*/
    if (authorizationRequest.getScope() != null) {
        authorizationRequestMap.put(OAuth2Utils.SCOPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getScope())));
    }

    authorizationRequestMap.put("approved", authorizationRequest.isApproved());

    if (authorizationRequest.getResourceIds() != null) {
        authorizationRequestMap.put("resourceIds",
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResourceIds())));
    }
    if (authorizationRequest.getAuthorities() != null) {
        authorizationRequestMap.put("authorities", Collections
                .unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities())));
    }

    return authorizationRequestMap;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private boolean isAuthorizationRequestModified(AuthorizationRequest authorizationRequest,
        Map<String, Object> originalAuthorizationRequest) {
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getClientId(),
            originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) {
        return true;
    }//from   w  ww  . j a v  a2s . c  om
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getState(),
            originalAuthorizationRequest.get(OAuth2Utils.STATE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getRedirectUri(),
            originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResponseTypes(),
            originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.isApproved(),
            originalAuthorizationRequest.get("approved"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResourceIds(),
            originalAuthorizationRequest.get("resourceIds"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getAuthorities(),
            originalAuthorizationRequest.get("authorities"))) {
        return true;
    }

    return !ObjectUtils.nullSafeEquals(authorizationRequest.getScope(),
            originalAuthorizationRequest.get(OAuth2Utils.SCOPE));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void token_endpoint_should_return_Basic_WWW_Authenticate_Header() throws Exception {
    String clientId = "testclient" + generator.generate();
    setUpClients(clientId, "uaa.user", "uaa.user", "authorization_code", true, TEST_REDIRECT_URI,
            Arrays.asList("uaa"));
    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());
    MockHttpSession session = getAuthenticatedSession(developer);
    String state = generator.generate();
    MvcResult result = getMockMvc()//  ww  w . j  a  v a2s.co  m
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isFound()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    String code = ((List<String>) query.get("code")).get(0);

    assertThat(code.length(), greaterThan(9));

    state = ((List<String>) query.get("state")).get(0);

    getMockMvc()
            .perform(post("/oauth/token").contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .accept(MediaType.APPLICATION_JSON_VALUE).param(OAuth2Utils.RESPONSE_TYPE, "token")
                    .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.CLIENT_ID, clientId)
                    .param("code", code).param("state", state))
            .andExpect(status().isUnauthorized()).andExpect(header().stringValues("WWW-Authenticate",
                    "Basic realm=\"UAA/client\", error=\"unauthorized\", error_description=\"Bad credentials\""));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void getOauthToken_usingAuthCode_withClientIdAndSecretInRequestBody_shouldBeOk() throws Exception {
    String clientId = "testclient" + generator.generate();
    setUpClients(clientId, "uaa.user", "uaa.user", "authorization_code", true, TEST_REDIRECT_URI,
            Arrays.asList("uaa"));

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()/*from www. java2s .  c o m*/
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isFound()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    String code = ((List<String>) query.get("code")).get(0);

    assertThat(code.length(), greaterThan(9));

    state = ((List<String>) query.get("state")).get(0);

    getMockMvc()
            .perform(post("/oauth/token").contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .accept(MediaType.APPLICATION_JSON_VALUE).param(OAuth2Utils.RESPONSE_TYPE, "token")
                    .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.CLIENT_ID, clientId)
                    .param("client_secret", "secret").param("code", code).param("state", state))
            .andExpect(status().isOk());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void refreshAccessToken_withClient_withAutoApproveField() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user,other.scope";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()/*from   ww  w .  j a  v  a 2 s. c o m*/
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isFound()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    String code = ((List<String>) query.get("code")).get(0);
    state = ((List<String>) query.get("state")).get(0);

    MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).accept(MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.CLIENT_ID, clientId).param("client_secret", "secret").param("code", code)
            .param("state", state);

    MvcResult mvcResult = getMockMvc().perform(oauthTokenPost).andReturn();
    OAuth2RefreshToken refreshToken = JsonUtils
            .readValue(mvcResult.getResponse().getContentAsString(), CompositeAccessToken.class)
            .getRefreshToken();

    MockHttpServletRequestBuilder postForRefreshToken = post("/oauth/token")
            .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
            .param(GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken.getValue());
    getMockMvc().perform(postForRefreshToken).andExpect(status().isOk());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void authorizeEndpointWithPromptNone_WhenNotAuthenticated() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    MockHttpSession session = new MockHttpSession();

    String state = generator.generate();

    MvcResult result = getMockMvc()//from   ww  w .  j  av a2s  . com
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
                    .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)
                    .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE))
            .andExpect(status().isFound()).andExpect(cookie().maxAge("Current-User", 0)).andReturn();

    String url = result.getResponse().getHeader("Location");
    assertEquals(UaaUrlUtils.addQueryParameter(TEST_REDIRECT_URI, "error", "login_required"), url);

}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void testAuthorizeEndpointWithPromptNone_Authenticated() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user,other.scope";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()//from  ww w .j a v a 2 s . c o  m
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
                    .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)
                    .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE))
            .andExpect(status().isFound()).andReturn();

    String url = result.getResponse().getHeader("Location");
    assertThat(url, containsString(TEST_REDIRECT_URI));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void testClientIdentityProviderClientWithoutAllowedProvidersForAuthCodeAlreadyLoggedInWorksInAnotherZone()
        throws Exception {
    //a client without allowed providers in non default zone should always be rejected
    String subdomain = "testzone" + generator.generate();
    IdentityZone testZone = setupIdentityZone(subdomain);
    IdentityZoneHolder.set(testZone);//from   w  w  w.  j a  va2 s. c o m
    IdentityProvider provider = setupIdentityProvider(OriginKeys.UAA);

    String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid";

    String clientId = "testclient" + generator.generate();
    setUpClients(clientId, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI, null);

    String clientId2 = "testclient" + generator.generate();
    setUpClients(clientId2, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI,
            Arrays.asList(provider.getOriginKey()));

    String clientId3 = "testclient" + generator.generate();
    setUpClients(clientId3, scopes, scopes, "authorization_code,password", true, TEST_REDIRECT_URI,
            Arrays.asList(OriginKeys.LOGIN_SERVER));

    String username = "testuser" + generator.generate();
    String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, testZone.getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();
    IdentityZoneHolder.clear();

    //no providers is ok
    getMockMvc()
            .perform(get("/oauth/authorize").session(session)
                    .with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"))
                    .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.STATE, state)
                    .param(OAuth2Utils.CLIENT_ID, clientId).param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI))
            .andExpect(status().isFound());

    //correct provider is ok
    MvcResult result = getMockMvc()
            .perform(get("/oauth/authorize").session(session)
                    .with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"))
                    .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.STATE, state)
                    .param(OAuth2Utils.CLIENT_ID, clientId2).param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI))
            .andExpect(status().isFound()).andReturn();

    //other provider, not ok
    getMockMvc()
            .perform(get("/oauth/authorize").session(session)
                    .with(new SetServerNameRequestPostProcessor(subdomain + ".localhost"))
                    .param(OAuth2Utils.RESPONSE_TYPE, "code").param(OAuth2Utils.STATE, state)
                    .param(OAuth2Utils.CLIENT_ID, clientId3).param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI))
            .andExpect(status().isUnauthorized()).andExpect(model().attributeExists("error"))
            .andExpect(model().attribute("error_message_code", "login.invalid_idp"));

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    assertNotNull(query.get("code"));
    String code = ((List<String>) query.get("code")).get(0);
    assertNotNull(code);

}