org.springframework.security.oauth2.client.OAuth2AuthorizedClient Java Examples

The following examples show how to use org.springframework.security.oauth2.client.OAuth2AuthorizedClient. 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: GitLabOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 7 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitLabOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #2
Source File: Oauth2ClientApplication.java    From training with Apache License 2.0 7 votes vote down vote up
@Bean
RestTemplate restTemplate(OAuth2AuthorizedClientService clientService) {
		return new RestTemplateBuilder()
			.interceptors((ClientHttpRequestInterceptor) (httpRequest, bytes, execution) -> {

					OAuth2AuthenticationToken token = OAuth2AuthenticationToken.class.cast(
						SecurityContextHolder.getContext().getAuthentication());

					OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
						token.getAuthorizedClientRegistrationId(),
						token.getName());

					httpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken().getTokenValue());

					return execution.execute(httpRequest, bytes);
			})
			.build();
}
 
Example #3
Source File: MessagingController.java    From messaging-app with Apache License 2.0 7 votes vote down vote up
@PostMapping
public String save(@RegisteredOAuth2AuthorizedClient("messaging") OAuth2AuthorizedClient messagingClient,
					@Valid Message message,
					@AuthenticationPrincipal OidcUser oidcUser) {
	message.setFromId(oidcUser.getClaimAsString("user_name"));
	message = this.webClient
			.post()
			.uri(this.messagesBaseUri)
			.contentType(MediaType.APPLICATION_JSON)
			.syncBody(message)
			.attributes(oauth2AuthorizedClient(messagingClient))
			.retrieve()
			.bodyToMono(Message.class)
			.block();
	return "redirect:/messages/sent";
}
 
Example #4
Source File: GitHubController.java    From blog-tutorials with MIT License 6 votes vote down vote up
private Flux<String> fetchAllRepositories(OAuth2AuthorizedClient authorizedClient) {
    return this.webClient
            .get()
            .uri(GITHUB_API_URL, uriBuilder ->
                    uriBuilder
                            .path("/user/repos")
                            .queryParam("per_page", 100)
                            .build()
            )
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<List<JsonNode>>() {
            })
            .flatMapMany(Flux::fromIterable)
            .map(jsonNode -> jsonNode.get("full_name").asText());
}
 
Example #5
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #6
Source File: DataFlowClientAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor bearerTokenResolvingInterceptor(
		OAuth2ClientProperties properties, String username, String password, String clientRegistrationId) {
	ClientRegistrationRepository shellClientRegistrationRepository = shellClientRegistrationRepository(properties);
	OAuth2AuthorizedClientService shellAuthorizedClientService = shellAuthorizedClientService(shellClientRegistrationRepository);
	OAuth2AuthorizedClientManager authorizedClientManager = authorizedClientManager(
			shellClientRegistrationRepository, shellAuthorizedClientService);

	if (properties.getRegistration() != null && properties.getRegistration().size() == 1) {
		// if we have only one, use that
		clientRegistrationId = properties.getRegistration().entrySet().iterator().next().getKey();
	}

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
			.principal(DEFAULT_PRINCIPAL)
			.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username)
			.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password)
			.build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #7
Source File: AuthorizationHeaderFilter.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
private Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
            oauthToken.getAuthorizedClientRegistrationId(),
            oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #8
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #9
Source File: AuthorizationHeaderUtil.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
        oauthToken.getAuthorizedClientRegistrationId(),
        oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken == null) {
        return Optional.empty();
    } else {
        String tokenType = accessToken.getTokenType().getValue();
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessToken.getTokenValue());
        return Optional.of(authorizationHeaderValue);
    }
}
 
Example #10
Source File: CFUAAOAuth2ClientController.java    From tutorials with MIT License 6 votes vote down vote up
@RequestMapping("/")
public String index(OAuth2AuthenticationToken authenticationToken) {
    OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
    OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();

    String response = "Hello, " + authenticationToken.getPrincipal().getName();
    response += "</br></br>";
    response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
    response += "</br>";
    response += "</br>You can use it to call these Resource Server APIs:";
    response += "</br></br>";
    response += "<a href='/read'>Call Resource Server Read API</a>";
    response += "</br>";
    response += "<a href='/write'>Call Resource Server Write API</a>";
    return response;
}
 
Example #11
Source File: CFUAAOAuth2ClientController.java    From tutorials with MIT License 6 votes vote down vote up
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
    OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
    OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());

    HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
    ResponseEntity<String> responseEntity = null;

    String response = null;
    try {
        responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        response = responseEntity.getBody();
    } catch (HttpClientErrorException e) {
        response = e.getMessage();
    }
    return response;
}
 
Example #12
Source File: LoginController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/loginSuccess")
public String getLoginInfo(Model model, OAuth2AuthenticationToken authentication) {

    OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());

    String userInfoEndpointUri = client.getClientRegistration()
        .getProviderDetails()
        .getUserInfoEndpoint()
        .getUri();

    if (!StringUtils.isEmpty(userInfoEndpointUri)) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken()
            .getTokenValue());

        HttpEntity<String> entity = new HttpEntity<String>("", headers);

        ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class);
        Map userAttributes = response.getBody();
        model.addAttribute("name", userAttributes.get("name"));
    }

    return "loginSuccess";
}
 
Example #13
Source File: DataFlowClientAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor clientCredentialsTokenResolvingInterceptor(
		ClientRegistration clientRegistration, ClientRegistrationRepository clientRegistrationRepository,
		String clientId) {
	Authentication principal = createAuthentication(clientId);
	OAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(
			clientRegistrationRepository);
	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientService);
	OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
			.clientCredentials().build();
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
			.withClientRegistrationId(DEFAULT_REGISTRATION_ID).principal(principal).build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #14
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 #15
Source File: FlowABCClientCredentialsController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@GetMapping
public String flowABC_ClientCredentials(@RegisteredOAuth2AuthorizedClient("client-ab") OAuth2AuthorizedClient clientAB,
										OAuth2AuthenticationToken oauth2Authentication,
										HttpServletRequest request,
										Map<String, Object> model) {

	ServiceCallResponse serviceACallResponse = callService(ServicesConfig.SERVICE_A, clientAB);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.put(FLOW_TYPE_PARAMETER, Collections.singletonList(FLOW_TYPE_CLIENT_CREDENTIALS));
	ServiceCallResponse serviceBCallResponse = callService(ServicesConfig.SERVICE_B, clientAB, params);

	String modelAttr = "flowABCCall_" + FLOW_TYPE_CLIENT_CREDENTIALS;
	model.put(modelAttr, fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example #16
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private Optional<OAuth2AuthorizedClient> refreshAuthorizedClient(Authentication authentication) {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    if (clientRegistration == null) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + CLIENT_REGISTRATION_ID);
    }

    OAuth2AccessToken accessToken = retrieveNewAccessToken(clientRegistration);
    if (accessToken == null) {
        log.info("Unable to get access token for user");
        return Optional.empty();
    }
    OAuth2AuthorizedClient updatedAuthorizedClient = new OAuth2AuthorizedClient(
        clientRegistration,
        authentication.getName(),
        accessToken
    );
    clientRegistrationService.saveAuthorizedClient(updatedAuthorizedClient, authentication);
    return Optional.of(updatedAuthorizedClient);
}
 
Example #17
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
public String getAuthorizationHeader() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Optional<OAuth2AuthorizedClient> client = Optional.ofNullable(
            clientRegistrationService.loadAuthorizedClient(CLIENT_REGISTRATION_ID, authentication.getName()));

        if (!client.isPresent() || client.get().getAccessToken() == null) {
            log.info("AccessToken not found, refreshing automatically");
            client = refreshAuthorizedClient(authentication);
        } else if (isExpired(client.get().getAccessToken())) {
            log.info("AccessToken expired, refreshing automatically");
            client = refreshAuthorizedClient(authentication);
        }

        return client.map(OAuth2AuthorizedClient::getAccessToken)
            .map(this::toAuthorizationHeaderValue)
            .orElseThrow(() -> new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, "Unable to get access token for user", null)));
    }
 
Example #18
Source File: AbstractFlowController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
protected ServiceCallResponse callService(String serviceId,
											OAuth2AuthorizedClient authorizedClient,
											MultiValueMap<String, String> params) {

	ServicesConfig.ServiceConfig serviceConfig = this.servicesConfig.getConfig(serviceId);
	UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(serviceConfig.getUri());
	if (!params.isEmpty()) {
		uriBuilder.queryParams(params);
	}
	URI uri = uriBuilder.build().toUri();

	return this.webClient
			.get()
			.uri(uri)
			.attributes(oauth2AuthorizedClient(authorizedClient))
			.retrieve()
			.bodyToMono(ServiceCallResponse.class)
			.block();
}
 
Example #19
Source File: MainController.java    From okta-spring-security-5-example with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/userinfo")
public String userinfo(Model model, OAuth2AuthenticationToken authentication) {
    OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
    Map userAttributes = Collections.emptyMap();
    String userInfoEndpointUri = authorizedClient.getClientRegistration()
            .getProviderDetails().getUserInfoEndpoint().getUri();
    if (!StringUtils.isEmpty(userInfoEndpointUri)) {    // userInfoEndpointUri is optional for OIDC Clients
        userAttributes = WebClient.builder()
                .filter(oauth2Credentials(authorizedClient)).build()
                .get().uri(userInfoEndpointUri)
                .retrieve()
                .bodyToMono(Map.class).block();
    }
    model.addAttribute("userAttributes", userAttributes);
    return "userinfo";
}
 
Example #20
Source File: MainController.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 votes vote down vote up
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
    return ExchangeFilterFunction.ofRequestProcessor(
        clientRequest -> {
            ClientRequest authorizedRequest = ClientRequest.from(clientRequest)
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue())
                .build();
            return Mono.just(authorizedRequest);
        });
}
 
Example #21
Source File: FlowABCTokenRelayController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@GetMapping
public String flowABC_TokenRelay(@RegisteredOAuth2AuthorizedClient("client-abc") OAuth2AuthorizedClient clientABC,
									OAuth2AuthenticationToken oauth2Authentication,
									HttpServletRequest request,
									Map<String, Object> model) {

	ServiceCallResponse serviceACallResponse = callService(ServicesConfig.SERVICE_A, clientABC);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.put(FLOW_TYPE_PARAMETER, Collections.singletonList(FLOW_TYPE_TOKEN_RELAY));
	ServiceCallResponse serviceBCallResponse = callService(ServicesConfig.SERVICE_B, clientABC, params);

	String modelAttr = "flowABCCall_" + FLOW_TYPE_TOKEN_RELAY;
	model.put(modelAttr, fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example #22
Source File: FlowABCTokenExchangeController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
@GetMapping
public String flowABC_TokenExchange(@RegisteredOAuth2AuthorizedClient("client-ab") OAuth2AuthorizedClient clientAB,
									OAuth2AuthenticationToken oauth2Authentication,
									HttpServletRequest request,
									Map<String, Object> model) {

	ServiceCallResponse serviceACallResponse = callService(ServicesConfig.SERVICE_A, clientAB);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	params.put(FLOW_TYPE_PARAMETER, Collections.singletonList(FLOW_TYPE_TOKEN_EXCHANGE));
	ServiceCallResponse serviceBCallResponse = callService(ServicesConfig.SERVICE_B, clientAB, params);

	String modelAttr = "flowABCCall_" + FLOW_TYPE_TOKEN_EXCHANGE;
	model.put(modelAttr, fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example #23
Source File: MainController.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 votes vote down vote up
@GetMapping("/userinfo")
public String userinfo(Model model, OAuth2AuthenticationToken authentication) {
    OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
    Map userAttributes = Collections.emptyMap();
    String userInfoEndpointUri = authorizedClient.getClientRegistration()
        .getProviderDetails().getUserInfoEndpoint().getUri();
    if (!StringUtils.isEmpty(userInfoEndpointUri)) {	// userInfoEndpointUri is optional for OIDC Clients
        userAttributes = WebClient.builder()
            .filter(oauth2Credentials(authorizedClient))
            .build()
            .get()
            .uri(userInfoEndpointUri)
            .retrieve()
            .bodyToMono(Map.class)
            .block();
    }
    model.addAttribute("userAttributes", userAttributes);
    return "userinfo";
}
 
Example #24
Source File: GitHubController.java    From blog-tutorials with MIT License 6 votes vote down vote up
private List<String> fetchAllRepositories(OAuth2AuthorizedClient authorizedClient) {
    List<String> repositoryNames = new ArrayList<>();

    this.webClient
            .get()
            .uri(GITHUB_API_URL, uriBuilder ->
                    uriBuilder
                            .path("/user/repos")
                            .queryParam("per_page", 100)
                            .build()
            )
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono(ArrayNode.class)
            .block()
            .forEach(jsonNode -> repositoryNames.add(jsonNode.get("full_name").asText()));

    return repositoryNames;
}
 
Example #25
Source File: ConfigCommands.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor bearerTokenResolvingInterceptor(
		OAuth2ClientProperties properties, String username, String password, String clientRegistrationId) {
	ClientRegistrationRepository shellClientRegistrationRepository = shellClientRegistrationRepository(properties);
	OAuth2AuthorizedClientService shellAuthorizedClientService = shellAuthorizedClientService(shellClientRegistrationRepository);
	OAuth2AuthorizedClientManager authorizedClientManager = authorizedClientManager(
			shellClientRegistrationRepository, shellAuthorizedClientService);

	if (properties.getRegistration() != null && properties.getRegistration().size() == 1) {
		// if we have only one, use that
		clientRegistrationId = properties.getRegistration().entrySet().iterator().next().getKey();
	}

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
			.principal(DEFAULT_PRINCIPAL)
			.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username)
			.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password)
			.build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #26
Source File: ClientRestController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/auth-code-annotated")
Mono<String> useOauthWithAuthCodeAndAnnotation(@RegisteredOAuth2AuthorizedClient("bael") OAuth2AuthorizedClient authorizedClient) {
    Mono<String> retrievedResource = webClient.get()
        .uri(RESOURCE_URI)
        .attributes(oauth2AuthorizedClient(authorizedClient))
        .retrieve()
        .bodyToMono(String.class);
    return retrievedResource.map(string -> "We retrieved the following resource using Oauth: " + string + ". Principal associated: " + authorizedClient.getPrincipalName() + ". Token will expire at: " + authorizedClient.getAccessToken()
        .getExpiresAt());
}
 
Example #27
Source File: GitHubController.java    From blog-tutorials with MIT License 5 votes vote down vote up
@GetMapping
public String index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                    @AuthenticationPrincipal OAuth2User oauth2User,
                    Model model) {

    model.addAttribute("repositories", fetchAllRepositories(authorizedClient));
    model.addAttribute("username", oauth2User.getAttributes().get("login"));

    return "index";
}
 
Example #28
Source File: MainController.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/")
public String index(Model model, OAuth2AuthenticationToken authentication) {
    OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
    model.addAttribute("userName", authentication.getName());
    model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
    return "index";
}
 
Example #29
Source File: MainController.java    From tutorials with MIT License 5 votes vote down vote up
@GetMapping("/foos/{id}")
public Mono<Foo> getFooResource(@RegisteredOAuth2AuthorizedClient("custom") OAuth2AuthorizedClient client, @PathVariable final long id){
    return webClient
        .get()
        .uri("http://localhost:8088/spring-security-oauth-resource/foos/{id}", id)
        .attributes(oauth2AuthorizedClient(client))
        .retrieve()
    .bodyToMono(Foo.class); 
}
 
Example #30
Source File: Oauth2ClientApplication.java    From training with Apache License 2.0 5 votes vote down vote up
@Bean
@RequestScope
OAuth2AuthorizedClient authorizedClient(
		OAuth2AuthorizedClientService authorizedClientService,
		OAuth2AuthenticationToken oauthToken) {
	return authorizedClientService.loadAuthorizedClient(
			oauthToken.getAuthorizedClientRegistrationId(),
			oauthToken.getName());
}