Java Code Examples for org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails#getTokenValue()

The following examples show how to use org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails#getTokenValue() . 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: KeycloakAuthenticationFilter.java    From camunda-bpm-identity-keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {

       // Get the Bearer Token and extract claims
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
       String accessToken = details.getTokenValue();
       String claims = JwtHelper.decode(accessToken).getClaims();
       
       // Extract user ID from Token claims -depending on Keycloak Identity Provider configuration
       // String userId = Spin.JSON(claims).prop("sub").stringValue();
       String userId = Spin.JSON(claims).prop("email").stringValue(); // useEmailAsCamundaUserId = true
       // String userId = Spin.JSON(claims).prop("preferred_username").stringValue(); // useUsernameAsCamundaUserId = true
       LOG.debug("Extracted userId from bearer token: {}", userId);

       try {
       	identityService.setAuthentication(userId, getUserGroups(userId));
       	chain.doFilter(request, response);
       } finally {
       	identityService.clearAuthentication();
       }
}
 
Example 2
Source File: OrderController.java    From spring-cloud-study with Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "get")
//@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication){
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
    //return "给你";
}
 
Example 3
Source File: OAuth2RestOperationsConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public DefaultOAuth2ClientContext oauth2ClientContext() {
	DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
	Authentication principal = SecurityContextHolder.getContext().getAuthentication();
	if (principal instanceof OAuth2Authentication) {
		OAuth2Authentication authentication = (OAuth2Authentication) principal;
		Object details = authentication.getDetails();
		if (details instanceof OAuth2AuthenticationDetails) {
			OAuth2AuthenticationDetails oauthsDetails = (OAuth2AuthenticationDetails) details;
			String token = oauthsDetails.getTokenValue();
			context.setAccessToken(new DefaultOAuth2AccessToken(token));
		}
	}
	return context;
}
 
Example 4
Source File: AccessTokenContextRelay.java    From spring-cloud-security with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to copy an access token from the security context into the oauth2 context.
 * @return true if the token was copied
 */
public boolean copyToken() {
	if (context.getAccessToken() == null) {
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		if (authentication != null) {
			Object details = authentication.getDetails();
			if (details instanceof OAuth2AuthenticationDetails) {
				OAuth2AuthenticationDetails holder = (OAuth2AuthenticationDetails) details;
				String token = holder.getTokenValue();
				DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(
						token);
				String tokenType = holder.getTokenType();
				if (tokenType != null) {
					accessToken.setTokenType(tokenType);
				}
				context.setAccessToken(accessToken);
				return true;
			}
		}
	}
	return false;
}
 
Example 5
Source File: FebsUtil.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前令牌内容
 *
 * @return String 令牌内容
 */
public static String getCurrentTokenValue() {
    try {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) getOauth2Authentication().getDetails();
        return details.getTokenValue();
    } catch (Exception ignore) {
        return null;
    }
}
 
Example 6
Source File: SsoLogoutSuccessHandler.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
	OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
	OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)oauth2Authentication.getDetails();
	String accessToken = details.getTokenValue();
	redirectStrategy.sendRedirect(request, response, logoutUri+accessToken);
}
 
Example 7
Source File: ClientController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "get")
//@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication){
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
    //return "给你";
}
 
Example 8
Source File: UserController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "get")
//@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication){
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String token = details.getTokenValue();
    return token;
}
 
Example 9
Source File: UserController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "jwt")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object jwtParser(Authentication authentication){
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
    String jwtToken = details.getTokenValue();
    Claims claims = Jwts.parser()
            .setSigningKey("dev".getBytes(StandardCharsets.UTF_8))
            .parseClaimsJws(jwtToken)
            .getBody();
    return claims;
}
 
Example 10
Source File: CodeClientController.java    From spring-cloud-study with Apache License 2.0 5 votes vote down vote up
@org.springframework.web.bind.annotation.ResponseBody
@GetMapping(value = "get")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication) {
    //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    authentication.getCredentials();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
    String token = details.getTokenValue();
    return token;
}
 
Example 11
Source File: SpringSecurityContext.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the token using {@link SecurityContextHolder}.
 *
 *
 * @return the token or <code>null</code> if {@link SecurityContext} is empty or
 *         does not contain a token of this type.
 */
@Nullable
public static Token getToken() {
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (Objects.nonNull(authentication) && authentication.isAuthenticated() &&
			authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
		OAuth2AuthenticationDetails authDetails = (OAuth2AuthenticationDetails) authentication.getDetails();
		String tokenValue = authDetails.getTokenValue();
		// TODO IAS Support
		return new XsuaaTokenWithGrantedAuthorities(tokenValue, authentication.getAuthorities());
	}
	return null;
}
 
Example 12
Source File: OAuth2BearerPrincipalHeadersCallback.java    From spring-cloud-netflix-zuul-websocket with Apache License 2.0 5 votes vote down vote up
@Override
protected void applyHeadersInternal(WebSocketSession userAgentSession, WebSocketHttpHeaders headers) {
    OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) userAgentSession.getPrincipal();
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Authentication.getDetails();
    String accessToken = details.getTokenValue();
    headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList("Bearer " + accessToken));
    if (logger.isDebugEnabled()) {
        logger.debug("Added Oauth2 bearer token authentication header for user " +
                oAuth2Authentication.getName() + " to web sockets http headers");
    }
}
 
Example 13
Source File: SecurityUtils.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
public static String getToken() {
    OAuth2AuthenticationDetails details = getTokenDetails();
    return details != null ? details.getTokenValue() : null;
}