org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken Java Examples

The following examples show how to use org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken. 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: 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 #2
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 7 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #3
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 #4
Source File: SpringLdapController.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
/**
 * This method will return current user name
 * @return
 */
@ModelAttribute("currentUserName")
public String getCurrentUserName() {
	String name = "";SecurityContextHolder.getContext().getAuthentication().getName();
	if(SecurityContextHolder.getContext().getAuthentication() !=null) {
		if(SecurityContextHolder.getContext().getAuthentication() 
				instanceof OAuth2AuthenticationToken) {
			OAuth2AuthenticationToken oauth2Authentication = 
					(OAuth2AuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
			name = (String)oauth2Authentication.getPrincipal().getAttributes().get("name");
		}else {
			String userName =  SecurityContextHolder.getContext().getAuthentication().getName();
			LdapAuthUser ldapUser =  ldapAuthService.getUser(userName);
			if(ldapUser !=null) {
				name = ldapUser.getFirstName()+" "+ldapUser.getSurName();
			}
		}
	}
	return name;
}
 
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: SpringOAuthController.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
/**
 * This method will return current user name
 * @return
 */
@ModelAttribute("currentUserName")
public String getCurrentUserName() {
	String name = "";SecurityContextHolder.getContext().getAuthentication().getName();
	if(SecurityContextHolder.getContext().getAuthentication() !=null) {
		if(SecurityContextHolder.getContext().getAuthentication() 
				instanceof OAuth2AuthenticationToken) {
			OAuth2AuthenticationToken oauth2Authentication = 
					(OAuth2AuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
			name = (String)oauth2Authentication.getPrincipal().getAttributes().get("name");
		}else {
			//in case if its not OAuth authentication, then write logic to fetch username
		}
	}
	return name;
}
 
Example #7
Source File: Oauth2ClientApplication.java    From training with Apache License 2.0 6 votes vote down vote up
@GetMapping("/profile")
Map<String, String> profile(OAuth2AuthenticationToken token) {
	String userInfoUri =
			this.authorizedClient
					.getClientRegistration()
					.getProviderDetails()
					.getUserInfoEndpoint()
					.getUri();

	return restTemplate
			.exchange(userInfoUri, HttpMethod.GET,
					null, new ParameterizedTypeReference<Map<String, String>>() {
					})
			.getBody();


}
 
Example #8
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 #9
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 #10
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #11
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 #12
Source File: AccountResourceIT.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void testGetExistingAccount() throws Exception {
    // create security-aware mockMvc
    restUserMockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

    Map<String, Object> userDetails = new HashMap<>();
    userDetails.put("sub", "test");
    userDetails.put("email", "[email protected]");
    Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, authorities, "oidc");
    TestSecurityContextHolder.getContext().setAuthentication(authentication);

    restUserMockMvc.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("test"))
        .andExpect(jsonPath("$.email").value("[email protected]"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #13
Source File: FacebookTokenStore.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public AccessToken loadSecurityToken(OAuth2AuthenticationToken authentication) {
    DefaultOAuth2User user = (DefaultOAuth2User) authentication.getPrincipal();
    String id = (String) user.getAttributes().get("id");

    Optional<FacebookAuth> facebookAuth = repository.findById(id);

    if (facebookAuth.isPresent()) {
        FacebookAuth auth = facebookAuth.get();
        return new AccessToken(AccessToken.TokenType.BEARER, id,
            Instant.ofEpochSecond(auth.getIssuedAt()),
            Instant.ofEpochSecond(auth.getExpirationTime()));
    }

    return null;
}
 
Example #14
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 #15
Source File: SecurityUtilsUnitTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCurrentUserLoginForOAuth2() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Map<String, Object> claims = new HashMap<>();
    claims.put("groups", "ROLE_USER");
    claims.put("sub", 123);
    claims.put("preferred_username", "admin");
    OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
        Instant.now().plusSeconds(60), claims);
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
    OidcUser user = new DefaultOidcUser(authorities, idToken);
    OAuth2AuthenticationToken bla = new OAuth2AuthenticationToken(user, authorities, "oidc");
    securityContext.setAuthentication(bla);
    SecurityContextHolder.setContext(securityContext);

    Optional<String> login = SecurityUtils.getCurrentUserLogin();

    assertThat(login).contains("admin");
}
 
Example #16
Source File: AbstractFlowController.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
protected ServiceCallResponse fromUiApp(OAuth2AuthenticationToken oauth2Authentication,
										HttpServletRequest request,
										ServiceCallResponse... serviceCallResponses) {

	OidcUser oidcUser = (OidcUser) oauth2Authentication.getPrincipal();

	ServiceCallResponse serviceCallResponse = new ServiceCallResponse();
	serviceCallResponse.setServiceName(ServicesConfig.UI_APP);
	serviceCallResponse.setServiceUri(request.getRequestURL().toString());
	serviceCallResponse.setJti("(opaque to client)");
	serviceCallResponse.setSub(oidcUser.getSubject());
	serviceCallResponse.setAud(oidcUser.getAudience());
	serviceCallResponse.setAuthorities(oauth2Authentication.getAuthorities().stream()
			.map(GrantedAuthority::getAuthority).sorted().collect(Collectors.toList()));
	if (serviceCallResponses != null) {
		serviceCallResponse.setServiceCallResponses(Arrays.asList(serviceCallResponses));
	}

	return serviceCallResponse;
}
 
Example #17
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 #18
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 #19
Source File: UserDetailsFormatter.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
public static UserDetails getCurrentUser() {
    final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession()
            .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = context.getAuthentication();
    if (authentication instanceof OAuth2AuthenticationToken) {
        OidcUser oidcUser = (OidcUser) authentication.getPrincipal();
        Object details = authentication.getDetails();
        String tenant = "DEFAULT";
        if (details instanceof TenantAwareAuthenticationDetails) {
            tenant = ((TenantAwareAuthenticationDetails) details).getTenant();
        }
        return new UserPrincipal(oidcUser.getPreferredUsername(), "***", oidcUser.getGivenName(),
                oidcUser.getFamilyName(), oidcUser.getPreferredUsername(), oidcUser.getEmail(), tenant,
                oidcUser.getAuthorities());
    } else {
        return (UserDetails) authentication.getPrincipal();
    }
}
 
Example #20
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 #21
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 #22
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 #23
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 #24
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
public Optional<String> getAuthorizationHeader() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
    String name = oauthToken.getName();
    String registrationId = oauthToken.getAuthorizedClientRegistrationId();
    OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(registrationId, name);

    if (null == client) {
        throw new OAuth2AuthorizationException(new OAuth2Error("access_denied", "The token is expired", null));
    }
    OAuth2AccessToken accessToken = client.getAccessToken();

    if (accessToken != null) {
        String tokenType = accessToken.getTokenType().getValue();
        String accessTokenValue = accessToken.getTokenValue();
        if (isExpired(accessToken)) {
            log.info("AccessToken expired, refreshing automatically");
            accessTokenValue = refreshToken(client, oauthToken);
            if (null == accessTokenValue) {
                SecurityContextHolder.getContext().setAuthentication(null);
                throw new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.ACCESS_DENIED, "The token is expired", null));
            }
        }
        String authorizationHeaderValue = String.format("%s %s", tokenType, accessTokenValue);
        return Optional.of(authorizationHeaderValue);
    }
    return Optional.empty();
}
 
Example #25
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 #26
Source File: OAuth2AuthenticationSuccessHandler.java    From jvue-admin with MIT License 5 votes vote down vote up
@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		super.onAuthenticationSuccess(request, response, authentication);
		// TODO 处理jvue用户绑定
//		logger.info("URI {}", request.getRequestURI());
//		request.getParameterMap().forEach((key, value) -> {
//			logger.info("param {} = {} ", key, value);
//		});
		
		String registrationId = null;
		String username = null;
		
		if (authentication instanceof OAuth2AuthenticationToken) {
			OAuth2AuthenticationToken oAuth2Authentication = (OAuth2AuthenticationToken)authentication;
			registrationId = oAuth2Authentication.getAuthorizedClientRegistrationId();
		} else {
			// registration取不到
			logger.warn("取不到 ClientRegistrationId");
			return;
		}
			
		
		if (authentication.getPrincipal() != null) {
			if (authentication.getPrincipal() instanceof OAuth2User) {
				OAuth2User oauth2User = (OAuth2User) authentication.getPrincipal();
				username = oauth2User.getName();
				
				// 这里可以根据不同的[registrationId]从[oauth2User.getAttributes()]里获取不同的用户数据
				// oauth2User.getAttributes()
			}
		}
		
		// save and update the principal
		logger.info("session {}", request.getSession());
		JwtUserDetails userDetails = userService.updateUser(registrationId, username);
		request.getSession(true).setAttribute("USER_INFO", userDetails);
	}
 
Example #27
Source File: FlowAController.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@GetMapping
public String flowA(@RegisteredOAuth2AuthorizedClient("client-a") OAuth2AuthorizedClient clientA,
					OAuth2AuthenticationToken oauth2Authentication,
					HttpServletRequest request,
					Map<String, Object> model) {

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

	model.put("flowACall", fromUiApp(oauth2Authentication, request, serviceACallResponse));
	model.put("flowActive", true);

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

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

	model.put("flowABCall", fromUiApp(oauth2Authentication, request, serviceACallResponse, serviceBCallResponse));
	model.put("flowActive", true);

	return "index";
}
 
Example #29
Source File: DefaultControllerAdvice.java    From oauth2-protocol-patterns with Apache License 2.0 5 votes vote down vote up
@ModelAttribute("idTokenClaims")
Map<String, Object> idTokenClaims(OAuth2AuthenticationToken oauth2Authentication) {
	if (oauth2Authentication == null) {
		return Collections.emptyMap();
	}
	OidcUser oidcUser = (OidcUser) oauth2Authentication.getPrincipal();
	final List<String> claimNames = Arrays.asList("iss", "sub", "aud", "azp", "given_name", "family_name", "email");
	return oidcUser.getClaims().entrySet().stream()
			.filter(e -> claimNames.contains(e.getKey()))
			.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
 
Example #30
Source File: TokenRelayGatewayFilterFactoryTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test
public void whenPrincipalExistsAuthorizationHeaderAdded() {
	OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
	when(accessToken.getTokenValue()).thenReturn("mytoken");

	ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("myregistrationid")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.clientId("myclientid").tokenUri("mytokenuri").build();
	OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
			clientRegistration, "joe", accessToken);

	when(repository.loadAuthorizedClient(anyString(),
			any(OAuth2AuthenticationToken.class), any(ServerWebExchange.class)))
					.thenReturn(Mono.just(authorizedClient));

	OAuth2AuthenticationToken authenticationToken = new OAuth2AuthenticationToken(
			mock(OAuth2User.class), Collections.emptyList(), "myId");
	SecurityContextImpl securityContext = new SecurityContextImpl(
			authenticationToken);
	SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange(
			mockExchange, Mono.just(securityContext));

	filter.filter(exchange, filterChain).block(TIMEOUT);

	assertThat(request.getHeaders()).containsEntry(HttpHeaders.AUTHORIZATION,
			Collections.singletonList("Bearer mytoken"));
}