org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames Java Examples

The following examples show how to use org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JwtBearerGrantRequestEntityConverter.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link MultiValueMap} of the form parameters used for the Access Token Request body.
 *
 * @param jwtBearerGrantRequest the Jwt Bearer grant request
 * @return a {@link MultiValueMap} of the form parameters used for the Access Token Request body
 */
private MultiValueMap<String, String> buildFormParameters(JwtBearerGrantRequest jwtBearerGrantRequest) {
	ClientRegistration clientRegistration = jwtBearerGrantRequest.getClientRegistration();

	MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
	formParameters.add(OAuth2ParameterNames.GRANT_TYPE, jwtBearerGrantRequest.getGrantType().getValue());
	formParameters.add("assertion", jwtBearerGrantRequest.getJwt().getTokenValue());
	if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
		formParameters.add(OAuth2ParameterNames.SCOPE,
				StringUtils.collectionToDelimitedString(jwtBearerGrantRequest.getClientRegistration().getScopes(), " "));
	}
	if (ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) {
		formParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
		formParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
	}

	return formParameters;
}
 
Example #2
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity
        .post(URI.create(clientRegistration.getProviderDetails().getTokenUri()))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(formParameters);

    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
 
Example #3
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {

        MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
        formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
        formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
        formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
        RequestEntity requestEntity = RequestEntity
            .post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri()))
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(formParameters);
        try {
            RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
            ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
            return toOAuth2AccessTokenResponse(responseEntity.getBody());
        } catch (OAuth2AuthorizationException e) {
            log.error("Unable to refresh token", e);
            throw new OAuth2AuthenticationException(e.getError(), e);
        }
    }
 
Example #4
Source File: ManualOauthRequestController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/manual-request-oauth")
public Mono<String> obtainSecuredResource() {
    logger.info("Creating web client...");
    Mono<String> resource = client.post()
        .uri(tokenUri)
        .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((clientId + ":" + clientSecret).getBytes()))
        .body(BodyInserters.fromFormData(OAuth2ParameterNames.GRANT_TYPE, GrantType.CLIENT_CREDENTIALS.getValue()))
        .retrieve()
        .bodyToMono(JsonNode.class)
        .flatMap(tokenResponse -> {
            String accessTokenValue = tokenResponse.get("access_token")
                .textValue();
            logger.info("Retrieved the following access token: {}", accessTokenValue);
            return client.get()
                .uri(RESOURCE_ENDPOINT)
                .headers(h -> h.setBearerAuth(accessTokenValue))
                .retrieve()
                .bodyToMono(String.class);
        });
    logger.info("non-blocking Oauth calls registered...");
    return resource.map(res -> "Retrieved the resource using a manual approach: " + res);

}
 
Example #5
Source File: CustomAccessTokenResponseConverter.java    From messaging-app with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
	String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);

	OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

	long expiresIn = 0;
	if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
		try {
			expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
		} catch (NumberFormatException ex) { }
	}

	Set<String> scopes = Collections.emptySet();
	if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
		String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
		scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " ")).collect(Collectors.toSet());
	}

	Map<String, Object> additionalParameters = new LinkedHashMap<>();
	tokenResponseParameters.entrySet().stream()
			.filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
			.forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));

	return OAuth2AccessTokenResponse.withToken(accessToken)
			.tokenType(accessTokenType)
			.expiresIn(expiresIn)
			.scopes(scopes)
			.additionalParameters(additionalParameters)
			.build();
}
 
Example #6
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizeGitHubClientWhenLinkClickedThenStatusRedirectForAuthorization() throws Exception {
	HtmlPage page = this.webClient.getPage("/");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();

	WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

	assertThat(response.getStatusCode()).isEqualTo(HttpStatus.MOVED_PERMANENTLY.value());

	String authorizeRedirectUri = response.getResponseHeaderValue("Location");
	assertThat(authorizeRedirectUri).isNotNull();

	UriComponents uriComponents = UriComponentsBuilder.fromUri(URI.create(authorizeRedirectUri)).build();

	String requestUri = uriComponents.getScheme() + "://" + uriComponents.getHost() + uriComponents.getPath();
	assertThat(requestUri).isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());

	Map<String, String> params = uriComponents.getQueryParams().toSingleValueMap();

	assertThat(params.get(OAuth2ParameterNames.RESPONSE_TYPE)).isEqualTo(OAuth2AuthorizationResponseType.CODE.getValue());
	assertThat(params.get(OAuth2ParameterNames.CLIENT_ID)).isEqualTo(clientRegistration.getClientId());
	String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();
	assertThat(URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8")).isEqualTo(redirectUri);
	assertThat(URLDecoder.decode(params.get(OAuth2ParameterNames.SCOPE), "UTF-8"))
		.isEqualTo(clientRegistration.getScopes().stream().collect(Collectors.joining(" ")));
	assertThat(params.get(OAuth2ParameterNames.STATE)).isNotNull();
}
 
Example #7
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenValidAuthorizationResponseThenDisplayIndexPage() throws Exception {
	HtmlPage page = this.webClient.getPage("/");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();

	WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

	UriComponents authorizeRequestUriComponents = UriComponentsBuilder.fromUri(
		URI.create(response.getResponseHeaderValue("Location"))).build();

	Map<String, String> params = authorizeRequestUriComponents.getQueryParams().toSingleValueMap();
	String code = "auth-code";
	String state = URLDecoder.decode(params.get(OAuth2ParameterNames.STATE), "UTF-8");
	String redirectUri = URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8");

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	this.assertIndexPage(page);
}
 
Example #8
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenNoMatchingAuthorizationRequestThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	String code = "auth-code";
	String state = "state";
	String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	// Clear session cookie will ensure the 'session-saved'
	// Authorization Request (from previous request) is not found
	this.webClient.getCookieManager().clearCookies();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("authorization_request_not_found");
}
 
Example #9
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenInvalidStateParamThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();
	this.followLinkDisableRedirects(clientAnchorElement);

	String code = "auth-code";
	String state = "invalid-state";
	String redirectUri = AUTHORIZE_BASE_URL + "/" + clientRegistration.getRegistrationId();

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("invalid_state_parameter");
}
 
Example #10
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void requestAuthorizationCodeGrantWhenInvalidRedirectUriThenDisplayLoginPageWithError() throws Exception {
	HtmlPage page = this.webClient.getPage("/");
	URL loginPageUrl = page.getBaseURL();
	URL loginErrorPageUrl = new URL(loginPageUrl.toString() + "?error");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();

	WebResponse response = this.followLinkDisableRedirects(clientAnchorElement);

	UriComponents authorizeRequestUriComponents = UriComponentsBuilder.fromUri(
		URI.create(response.getResponseHeaderValue("Location"))).build();

	Map<String, String> params = authorizeRequestUriComponents.getQueryParams().toSingleValueMap();
	String code = "auth-code";
	String state = URLDecoder.decode(params.get(OAuth2ParameterNames.STATE), "UTF-8");
	String redirectUri = URLDecoder.decode(params.get(OAuth2ParameterNames.REDIRECT_URI), "UTF-8");
	redirectUri += "-invalid";

	String authorizationResponseUri =
		UriComponentsBuilder.fromHttpUrl(redirectUri)
			.queryParam(OAuth2ParameterNames.CODE, code)
			.queryParam(OAuth2ParameterNames.STATE, state)
			.build().encode().toUriString();

	page = this.webClient.getPage(new URL(authorizationResponseUri));
	assertThat(page.getBaseURL()).isEqualTo(loginErrorPageUrl);

	HtmlElement errorElement = page.getBody().getFirstByXPath("p");
	assertThat(errorElement).isNotNull();
	assertThat(errorElement.asText()).contains("invalid_redirect_uri_parameter");
}
 
Example #11
Source File: LinkedinTokenResponseConverter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);
    long expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
    
    OAuth2AccessToken.TokenType accessTokenType = OAuth2AccessToken.TokenType.BEARER;

    return OAuth2AccessTokenResponse.withToken(accessToken)
        .tokenType(accessTokenType)
        .expiresIn(expiresIn)
        .build();
}
 
Example #12
Source File: CustomTokenResponseConverter.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public OAuth2AccessTokenResponse convert(Map<String, String> tokenResponseParameters) {
    String accessToken = tokenResponseParameters.get(OAuth2ParameterNames.ACCESS_TOKEN);

    OAuth2AccessToken.TokenType accessTokenType = null;
    if (OAuth2AccessToken.TokenType.BEARER.getValue()
        .equalsIgnoreCase(tokenResponseParameters.get(OAuth2ParameterNames.TOKEN_TYPE))) {
        accessTokenType = OAuth2AccessToken.TokenType.BEARER;
    }

    long expiresIn = 0;
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.EXPIRES_IN)) {
        try {
            expiresIn = Long.valueOf(tokenResponseParameters.get(OAuth2ParameterNames.EXPIRES_IN));
        } catch (NumberFormatException ex) {
        }
    }

    Set<String> scopes = Collections.emptySet();
    if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
        String scope = tokenResponseParameters.get(OAuth2ParameterNames.SCOPE);
        scopes = Arrays.stream(StringUtils.delimitedListToStringArray(scope, " "))
            .collect(Collectors.toSet());
    }

    String refreshToken = tokenResponseParameters.get(OAuth2ParameterNames.REFRESH_TOKEN);

    Map<String, Object> additionalParameters = new LinkedHashMap<>();
    tokenResponseParameters.entrySet()
        .stream()
        .filter(e -> !TOKEN_RESPONSE_PARAMETER_NAMES.contains(e.getKey()))
        .forEach(e -> additionalParameters.put(e.getKey(), e.getValue()));

    return OAuth2AccessTokenResponse.withToken(accessToken)
        .tokenType(accessTokenType)
        .expiresIn(expiresIn)
        .scopes(scopes)
        .refreshToken(refreshToken)
        .additionalParameters(additionalParameters)
        .build();
}