Example usage for org.springframework.security.oauth2.provider AuthorizationRequest setRequestParameters

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setRequestParameters

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider AuthorizationRequest setRequestParameters.

Prototype

public void setRequestParameters(Map<String, String> requestParameters) 

Source Link

Document

Set the Request Parameters on this authorization request, which represent the original request parameters and should never be changed during processing.

Usage

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

private ModelAndView getImplicitGrantOrHybridResponse(AuthorizationRequest authorizationRequest,
        Authentication authentication, String grantType) {
    OAuth2AccessToken accessToken;//from   ww w.  j  av a2 s. co  m
    try {
        TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest,
                GRANT_TYPE_IMPLICIT);
        Map<String, String> requestParameters = new HashMap<>(authorizationRequest.getRequestParameters());
        requestParameters.put(GRANT_TYPE, grantType);
        authorizationRequest.setRequestParameters(requestParameters);
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        accessToken = getAccessTokenForImplicitGrantOrHybrid(tokenRequest, storedOAuth2Request, grantType);
        if (accessToken == null) {
            throw new UnsupportedResponseTypeException("Unsupported response type: token or id_token");
        }
        return new ModelAndView(new RedirectView(
                buildRedirectURI(authorizationRequest, accessToken, authentication), false, true, false));
    } catch (OAuth2Exception e) {
        return new ModelAndView(
                new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false));
    }
}

From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException {
    Map<String, Object> claims;
    try {/* ww  w.j  a  v a2  s  .  c  om*/
        claims = getTokenClaims(accessToken);
    } catch (IllegalArgumentException e) {
        LOG.error("Malformed Access Token: " + accessToken);
        LOG.error(e);
        throw new InvalidTokenException("Malformed Access Token", e);
    }
    String iss = getIssuerFromClaims(claims);

    verifyIssuer(iss);

    // check if the singerProvider for that issuer has already in the cache
    SignatureVerifier verifier = this.tokenKeys.get(iss);
    if (null == verifier) {
        String tokenKey = getTokenKey(iss);
        verifier = getVerifier(tokenKey);
        this.tokenKeys.put(iss, verifier);
    }

    JwtHelper.decodeAndVerify(accessToken, verifier);
    verifyTimeWindow(claims);

    Assert.state(claims.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) claims.get("client_id");

    Set<String> scope = new HashSet<>();
    if (claims.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) claims.get("scope");
        scope.addAll(values);
    }

    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (claims.containsKey("resource_ids") || claims.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<>();
        if (claims.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("resource_ids");
            resourceIds.addAll(values);
        }

        Set<GrantedAuthority> clientAuthorities = new HashSet<>();
        if (claims.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }

        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }

    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : claims.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (claims.containsKey(Claims.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(Claims.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(claims.get(Claims.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(claims, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

From source file:org.cloudfoundry.identity.uaa.authentication.AbstractClientParametersAuthenticationFilter.java

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {//from w ww .jav a 2  s . c  o m
    if (clientId != null) {
        Result policyResult = loginPolicy.isAllowed(clientId);
        if (!policyResult.isAllowed()) {
            throw new ClientLockoutException("Client " + clientId + " has " + policyResult.getFailureCount()
                    + " failed authentications within the last checking period.");
        }
    }

    String clientSecret = loginInfo.get(CLIENT_SECRET);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);
    authentication.setDetails(new UaaAuthenticationDetails(req, clientId));
    try {
        Authentication auth = clientAuthenticationManager.authenticate(authentication);
        if (auth == null || !auth.isAuthenticated()) {
            throw new BadCredentialsException("Client Authentication failed.");
        }
        loginInfo.remove(CLIENT_SECRET);
        AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req));
        authorizationRequest.setRequestParameters(getSingleValueMap(req));
        authorizationRequest.setApproved(true);
        //must set this to true in order for
        //Authentication.isAuthenticated to return true
        OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
                null);
        result.setAuthenticated(true);
        return result;
    } catch (AuthenticationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (Exception e) {
        logger.debug("Unable to authenticate client: " + clientId, e);
        throw new BadCredentialsException(e.getMessage(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java

private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo,
        String clientId) {//from  w  w w. j a  v a 2 s.  c  o  m

    String clientSecret = loginInfo.get(CLIENT_SECRET);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);
    authentication.setDetails(new UaaAuthenticationDetails(req, clientId));
    try {
        Authentication auth = clientAuthenticationManager.authenticate(authentication);
        if (auth == null || !auth.isAuthenticated()) {
            throw new BadCredentialsException("Client Authentication failed.");
        }
        loginInfo.remove(CLIENT_SECRET);
        AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req));
        authorizationRequest.setRequestParameters(getSingleValueMap(req));
        authorizationRequest.setApproved(true);
        //must set this to true in order for
        //Authentication.isAuthenticated to return true
        OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
                null);
        result.setAuthenticated(true);
        return result;
    } catch (AuthenticationException e) {
        throw new BadCredentialsException(e.getMessage(), e);
    } catch (Exception e) {
        logger.debug("Unable to authenticate client: " + clientId, e);
        throw new BadCredentialsException(e.getMessage(), e);
    }
}

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

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }//w ww  . ja  v a  2 s. c  o m

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(map, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

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

@Test
public void is_opaque_token_required() {
    defaultClient.setAutoApproveScopes(singleton("true"));
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token")));
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, TokenConstants.GRANT_TYPE_USER_TOKEN);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*from w w w. jav a2  s  .  c  om*/
    assertTrue(tokenServices.opaqueTokenRequired(authentication));
}

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

@Test
public void testCreateAccessTokenForAClient() {

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);//w  w  w .j  a v  a 2  s .  c  om

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    assertCommonClientAccessTokenProperties(accessToken);
    assertThat(accessToken, validFor(is(accessTokenValidity)));
    assertThat(accessToken, issuerUri(is(ISSUER_URI)));
    assertThat(accessToken, zoneId(is(IdentityZoneHolder.get().getId())));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
    validateExternalAttributes(accessToken);

    assertCommonEventProperties(accessToken, CLIENT_ID, expectedJson);
}

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

protected OAuth2AccessToken performPasswordGrant(String tokenFormat) {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, PASSWORD);
    azParameters.put(REQUEST_TOKEN_FORMAT, tokenFormat);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);//  ww w.j a v  a2 s . c om
    return tokenServices.createAccessToken(authentication);
}

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

@Test
public void testCreateOpaqueAccessTokenForAClient() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE);
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);/*from   w ww  . ja v a2 s .co  m*/

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    assertTrue("Token is not a composite token", accessToken instanceof CompositeAccessToken);
    assertThat("Token value should be equal to or lesser than 36 characters", accessToken.getValue().length(),
            lessThanOrEqualTo(36));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
}

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

@Test
public void testCreateAccessTokenForAClientInAnotherIdentityZone() {
    String subdomain = "test-zone-subdomain";
    IdentityZone identityZone = getIdentityZone(subdomain);
    identityZone.setConfig(JsonUtils.readValue(
            "{\"tokenPolicy\":{\"accessTokenValidity\":3600,\"refreshTokenValidity\":7200}}",
            IdentityZoneConfiguration.class));
    IdentityZoneHolder.set(identityZone);
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);//w w  w .j a va  2 s.co m

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    this.assertCommonClientAccessTokenProperties(accessToken);
    assertThat(accessToken, validFor(is(3600)));
    assertThat(accessToken, issuerUri(is("http://" + subdomain + ".localhost:8080/uaa/oauth/token")));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
    validateExternalAttributes(accessToken);

    Assert.assertEquals(1, publisher.getEventCount());

    this.assertCommonEventProperties(accessToken, CLIENT_ID, expectedJson);
}