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

The following examples show how to use org.springframework.security.oauth2.client.OAuth2AuthorizedClient. These examples are extracted from open source projects. 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
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 2
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 3
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 4
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 5
Source Project: messaging-app   Source File: MessagingController.java    License: Apache License 2.0 6 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 6
@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 7
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 8
@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 9
@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 10
Source Project: training   Source File: Oauth2ClientApplication.java    License: Apache License 2.0 6 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 11
Source Project: blog-tutorials   Source File: GitHubController.java    License: 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 12
Source Project: blog-tutorials   Source File: GitHubController.java    License: 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 13
@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 14
@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 15
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 16
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 Project: jhipster-registry   Source File: AuthorizationHeaderUtil.java    License: 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 18
Source Project: spring-cloud-dataflow   Source File: ConfigCommands.java    License: 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 19
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 20
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 21
Source Project: tutorials   Source File: CFUAAOAuth2ClientController.java    License: 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 22
Source Project: tutorials   Source File: CFUAAOAuth2ClientController.java    License: 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 23
Source Project: tutorials   Source File: LoginController.java    License: 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 24
Source Project: gaia   Source File: RegistryOAuth2Provider.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the data from the authorized client
 */
default OAuth2User getOAuth2User(DefaultOAuth2User user, OAuth2AuthorizedClient client) {
    return new OAuth2User(
            client.getClientRegistration().getRegistrationId(),
            client.getAccessToken().getTokenValue(),
            user.getAttributes());
}
 
Example 25
Source Project: gaia   Source File: GitHubOAuth2ProviderTest.java    License: Mozilla Public License 2.0 5 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 = gitHubOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example 26
Source Project: gaia   Source File: GitLabOAuth2ProviderTest.java    License: Mozilla Public License 2.0 5 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 27
Source Project: spring-security-samples   Source File: TravelGatewayApplication.java    License: MIT License 5 votes vote down vote up
@GetMapping("/whoami")
@ResponseBody
public Map<String, Object> index(
		@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
		@AuthenticationPrincipal OidcUser oidcUser) {
	Map<String, Object> model = new HashMap<>();
	model.put("clientName", authorizedClient.getClientRegistration().getClientName());
	model.put("userName", oidcUser.getName());
	model.put("userAttributes", oidcUser.getAttributes());
	return model;
}
 
Example 28
@GetMapping("/")
public String index(Model model,
					@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
					@AuthenticationPrincipal OAuth2User oauth2User) {
	model.addAttribute("userName", oauth2User.getName());
	model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
	model.addAttribute("userAttributes", oauth2User.getAttributes());
	return "index";
}
 
Example 29
@Override
public void apply(RequestTemplate template) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
            oauthToken.getAuthorizedClientRegistrationId(),
            oauthToken.getName());

    OAuth2AccessToken accessToken = client.getAccessToken();
    template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, accessToken.getTokenValue()));
}
 
Example 30
Source Project: messaging-app   Source File: MessagingController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/inbox")
public String inbox(@RegisteredOAuth2AuthorizedClient("messaging") OAuth2AuthorizedClient messagingClient,
					Map<String, Object> model) {
	List<Message> messages = getMessages(messagingClient, this.messagesBaseUri + "/inbox");
	model.put(MESSAGES_ATTRIBUTE_NAME, messages);
	model.put(MESSAGE_TYPE_ATTRIBUTE_NAME, MESSAGE_TYPE_INBOX);
	return "message-list";
}