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

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

Introduction

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

Prototype

String RESPONSE_TYPE

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

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"));
    }/*from w w  w  . j av  a 2 s.co 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("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  www  .ja  v  a 2 s.  co  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.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }//from  w  ww .  j  a  v a 2s  .com
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

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

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    String redirectUri = request.getParameter(OAuth2Utils.REDIRECT_URI);
    String[] responseTypes = ofNullable(request.getParameter(OAuth2Utils.RESPONSE_TYPE))
            .map(rt -> rt.split(" ")).orElse(new String[0]);

    ClientDetails client;/*from  www  .j a  va  2  s  . com*/
    try {
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (ClientRegistrationException e) {
        logger.debug("[prompt=none] Unable to look up client for client_id=" + clientId, e);
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    Set<String> redirectUris = ofNullable(client.getRegisteredRedirectUri()).orElse(EMPTY_SET);

    //if the client doesn't have a redirect uri set, the parameter is required.
    if (redirectUris.size() == 0 && !hasText(redirectUri)) {
        logger.debug("[prompt=none] Missing redirect_uri");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    String resolvedRedirect;
    try {
        resolvedRedirect = redirectResolver.resolveRedirect(redirectUri, client);
    } catch (RedirectMismatchException rme) {
        logger.debug("[prompt=none] Invalid redirect " + redirectUri
                + " did not match one of the registered values");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    HttpHost httpHost = URIUtils.extractHost(URI.create(resolvedRedirect));
    String sessionState = openIdSessionStateCalculator.calculate("", clientId, httpHost.toURI());
    boolean implicit = stream(responseTypes).noneMatch("code"::equalsIgnoreCase);
    String redirectLocation;
    String errorCode = authException instanceof InteractionRequiredException ? "interaction_required"
            : "login_required";
    if (implicit) {
        redirectLocation = addFragmentComponent(resolvedRedirect, "error=" + errorCode);
        redirectLocation = addFragmentComponent(redirectLocation, "session_state=" + sessionState);
    } else {
        redirectLocation = addQueryParameter(resolvedRedirect, "error", errorCode);
        redirectLocation = addQueryParameter(redirectLocation, "session_state", sessionState);
    }

    response.sendRedirect(redirectLocation);
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

/**
 * Adds a request enhancer to the provider.
 * Currently only two request parameters are being enhanced
 * 1. If the {@link TokenRequest} wants an id_token the <code>id_token token</code> values are added as a response_type parameter
 * 2. If the {@link TokenRequest} is a {@link org.cloudfoundry.identity.client.token.GrantType#PASSWORD_WITH_PASSCODE}
 * the <code>passcode</code> parameter will be added to the request
 * @param tokenRequest the token request, expected to be a password grant
 * @param provider the provider to enhance
 */// w  w w. ja  v  a  2  s  .  c  o m
protected void enhanceRequestParameters(TokenRequest tokenRequest, OAuth2AccessTokenSupport provider) {
    provider.setTokenRequestEnhancer( //add id_token to the response type if requested.
            (AccessTokenRequest request, OAuth2ProtectedResourceDetails resource,
                    MultiValueMap<String, String> form, HttpHeaders headers) -> {
                if (tokenRequest.wantsIdToken()) {
                    form.put(OAuth2Utils.RESPONSE_TYPE, Arrays.asList("id_token token"));
                }
                if (tokenRequest.getGrantType() == PASSWORD_WITH_PASSCODE) {
                    form.put("passcode", Arrays.asList(tokenRequest.getPasscode()));
                }
            });
}

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())));
    }/*  ww w  .  j  a  va  2 s.  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;
    }/*w  w  w.j  a va2s  .c  o  m*/
    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 test_token_ids() throws Exception {
    String clientId = "testclient" + generator.generate();
    setUpClients(clientId, "uaa.user", "uaa.user", "password,refresh_token", true, TEST_REDIRECT_URI,
            Arrays.asList("uaa"));

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

    String response = getMockMvc()
            .perform(post("/oauth/token").contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "password")
                    .param(OAuth2Utils.CLIENT_ID, clientId).param(REQUEST_TOKEN_FORMAT, OPAQUE)
                    .param("client_secret", SECRET).param("username", username).param("password", SECRET))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    Map<String, Object> tokens = JsonUtils.readValue(response, new TypeReference<Map<String, Object>>() {
    });/*w w w  .  j av a 2s  .  co  m*/
    Object accessToken = tokens.get(ACCESS_TOKEN);
    Object refreshToken = tokens.get(REFRESH_TOKEN);
    Object jti = tokens.get(JTI);
    assertNotNull(accessToken);
    assertNotNull(refreshToken);
    assertNotNull(jti);
    assertEquals(jti, accessToken);
    assertNotEquals(accessToken + REFRESH_TOKEN_SUFFIX, refreshToken);
    String accessTokenId = (String) accessToken;
    String refreshTokenId = (String) refreshToken;

    response = getMockMvc()
            .perform(post("/oauth/token")
                    .header(AUTHORIZATION,
                            "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                    .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN)
                    .param(REFRESH_TOKEN, refreshTokenId).param(REQUEST_TOKEN_FORMAT, OPAQUE))

            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    tokens = JsonUtils.readValue(response, new TypeReference<Map<String, Object>>() {
    });
    accessToken = tokens.get(ACCESS_TOKEN);
    refreshToken = tokens.get(REFRESH_TOKEN);
    jti = tokens.get(JTI);
    assertNotNull(accessToken);
    assertNotNull(refreshToken);
    assertNotNull(jti);
    assertEquals(jti, accessToken);
    assertNotEquals(accessToken + REFRESH_TOKEN_SUFFIX, refreshToken);
    assertNotEquals(accessToken, accessTokenId);
    assertEquals(accessToken, jti);
    assertNotEquals(refreshToken, jti);
}

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

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

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user";
    setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());
    setDisableInternalAuth(getWebApplicationContext(), IdentityZone.getUaa().getId(), true);
    try {/*from   w ww . ja  v  a 2  s  .  c om*/
        getMockMvc()
                .perform(post("/oauth/token").contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                        .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "password")
                        .param(OAuth2Utils.CLIENT_ID, clientId).param("client_secret", SECRET)
                        .param("username", username).param("password", SECRET))
                .andExpect(status().isUnauthorized());
    } finally {
        setDisableInternalAuth(getWebApplicationContext(), IdentityZone.getUaa().getId(), false);
    }
}

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()/*from w w  w .  j av  a2s. c  om*/
            .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\""));
}