org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails Java Examples

The following examples show how to use org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails. 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: 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 #2
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 #3
Source File: OAuth2Controller.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "获取token信息")
@PostMapping(value = "/oauth/get/token", params = "access_token")
public OAuth2AccessToken getTokenInfo(String access_token) {

	// 拿到当前用户信息
	Authentication user = SecurityContextHolder.getContext().getAuthentication();

	if (user != null) {
		if (user instanceof OAuth2Authentication) {
			Authentication athentication = (Authentication) user;
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails();
		}

	}
	OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token);

	return accessToken;

}
 
Example #4
Source File: OauthLogoutHandler.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
protected String extractToken(HttpServletRequest request) {
	// first check the header...
	String token = extractHeaderToken(request);

	// bearer type allows a request parameter as well
	if (token == null) {
		logger.debug("Token not found in headers. Trying request parameters.");
		token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
		if (token == null) {
			logger.debug("Token not found in request parameters.  Not an OAuth2 request.");
		} else {
			request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE);
		}
	}

	return token;
}
 
Example #5
Source File: OauthLogoutHandler.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
protected String extractHeaderToken(HttpServletRequest request) {
	Enumeration<String> headers = request.getHeaders("Authorization");
	while (headers.hasMoreElements()) { // typically there is only one (most
										// servers enforce that)
		String value = headers.nextElement();
		if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
			String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
			// Add this here for the auth details later. Would be better to
			// change the signature of this method.
			request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
					value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
			int commaIndex = authHeaderValue.indexOf(',');
			if (commaIndex > 0) {
				authHeaderValue = authHeaderValue.substring(0, commaIndex);
			}
			return authHeaderValue;
		}
	}

	return null;
}
 
Example #6
Source File: SpringSecurityUtils.java    From spring-microservice-boilerplate with MIT License 6 votes vote down vote up
/**
 * Get current user's IP address.
 *
 * @return IP
 */
public static String getCurrentUserIp() {
  Authentication authentication = getAuthentication();
  if (authentication == null) {
    return "";
  }
  Object details = authentication.getDetails();
  if (details instanceof OAuth2AuthenticationDetails) {
    OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) details;
    return oAuth2AuthenticationDetails.getRemoteAddress();
  }
  if (details instanceof WebAuthenticationDetails) {
    WebAuthenticationDetails webDetails = (WebAuthenticationDetails) details;
    return webDetails.getRemoteAddress();
  }
  return "";
}
 
Example #7
Source File: AuditService.java    From galeb with Apache License 2.0 6 votes vote down vote up
public void logAccess(String role, Set<String> roles, boolean result, String entityClass, String action, Object criteria, AuditType auditType) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object detailsObj = authentication.getDetails();
    String remoteAddr = null;
    Account account = (Account) authentication.getPrincipal();
    if (detailsObj instanceof WebAuthenticationDetails) {
        remoteAddr = ((WebAuthenticationDetails) detailsObj).getRemoteAddress();
    }
    if (detailsObj instanceof OAuth2AuthenticationDetails) {
        remoteAddr = ((OAuth2AuthenticationDetails) detailsObj).getRemoteAddress();
    }
    register(String.format("[%s/%s/%s]: %s%s %s %s",
            entityClass,
            action,
            criteria instanceof AbstractEntity ? ((AbstractEntity)criteria).getId() : criteria,
            account.getUsername() + (remoteAddr != null ? "/" + remoteAddr : ""),
            showRoles ? " (roles: " + String.join(",", roles) + ")" : "",
            auditType == AuditType.ROLE ? auditType.getMsg() + role + "?" : auditType.getMsg(),
            result));
}
 
Example #8
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 #9
Source File: SysUtil.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 获取当前登录的租户code
 *
 * @return String
 */
private static String getCurrentUserTenantCode() {
    String tenantCode = "";
    try {
        ResourceServerTokenServices resourceServerTokenServices = SpringContextHolder.getApplicationContext().getBean(ResourceServerTokenServices.class);
        Object details = SecurityContextHolder.getContext().getAuthentication().getDetails();
        if (details instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails) details;
            OAuth2AccessToken oAuth2AccessToken = resourceServerTokenServices.readAccessToken(oAuth2AuthenticationDetails.getTokenValue());
            Object tenantObj = oAuth2AccessToken.getAdditionalInformation().get(SecurityConstant.TENANT_CODE);
            tenantCode = tenantObj == null ? "" : tenantObj.toString();
        } else if (details instanceof WebAuthenticationDetails) {
            // 未认证
            Object requestObj = RequestContextHolder.getRequestAttributes();
            if (requestObj != null) {
                HttpServletRequest request = ((ServletRequestAttributes) requestObj).getRequest();
                tenantCode = request.getParameter(SecurityConstant.TENANT_CODE);
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return tenantCode;
}
 
Example #10
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 #11
Source File: OAuth2Util.java    From DAFramework with MIT License 6 votes vote down vote up
public static EAccessToken fetch(OAuth2Authentication oAuth2Authentication, OAuth2AccessToken accessToken){
	EAccessToken eAccessToken = new EAccessToken();
	eAccessToken.setOpenUser(fetch(oAuth2Authentication));

	Object details = oAuth2Authentication.getDetails();
	if(details instanceof OAuth2AuthenticationDetails){
		OAuth2AuthenticationDetails details1 = (OAuth2AuthenticationDetails) details;
		eAccessToken.setRemoteAddress(details1.getRemoteAddress());
		eAccessToken.setSessionId(details1.getSessionId());
	}
	eAccessToken.setTokenType(accessToken.getTokenType());
	eAccessToken.setTokenValue(accessToken.getValue());
	eAccessToken.setExpiresIn(accessToken.getExpiresIn());
	if (accessToken.getRefreshToken() != null) {
		eAccessToken.setRefreshToken(accessToken.getRefreshToken().getValue());
	}
	if (accessToken.getScope() != null) {
		String scopes = Strings.join2("|", accessToken.getScope().toArray(new String[]{}));
		eAccessToken.setScopes(scopes);
	}
	return eAccessToken;
}
 
Example #12
Source File: SpringSecurityConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate requestTemplate) {
        	log.info("Is SecurityContextHolder.getContext() null ===========>"+(SecurityContextHolder.getContext() != null));
        	if(SecurityContextHolder.getContext() != null) {
        		OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        		log.info("Token Value===========>"+details.getTokenValue());
        		requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        	}
        }
    };
}
 
Example #13
Source File: SpringSecurityContextTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
private static void setToken(Token token, Set<String> scopes) {
	SecurityContext context = new SecurityContextImpl();
	OAuth2Authentication authentication = SAPOfflineTokenServicesCloud.getOAuth2Authentication(
			"clientId", scopes);

	HttpServletRequest request = mock(HttpServletRequest.class);
	when(request.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE)).thenReturn(token.getTokenValue());

	authentication.setDetails(new OAuth2AuthenticationDetails(request));
	context.setAuthentication(authentication);
	SecurityContextHolder.clearContext();
	SecurityContextHolder.setContext(context);
	assertThat(SecurityContextHolder.getContext()).isEqualTo(context);
}
 
Example #14
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 #15
Source File: SpringSecurityConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
            requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        }
    };
}
 
Example #16
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 #17
Source File: AuthConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
            requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        }
    };
}
 
Example #18
Source File: AuthConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
	return new RequestInterceptor() {
		@Override
		public void apply(RequestTemplate requestTemplate) {
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext()
					.getAuthentication().getDetails();
			requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
		}
	};
}
 
Example #19
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example #20
Source File: SecurityUtils.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public static OAuth2AuthenticationDetails getTokenDetails() {
    OAuth2Authentication auth = getTokenAuthentication();
    if (auth != null && auth.getDetails() instanceof OAuth2AuthenticationDetails) {
        return (OAuth2AuthenticationDetails) auth.getDetails();
    }
    return null;
}
 
Example #21
Source File: TokenRequestSuccessHandler.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
    Map<String, String> responseMap = new HashMap<>();
    responseMap.put("access_token", details.getTokenValue());
    responseMap.put("token_type", details.getTokenType());
    String content = gson.toJson(responseMap);
    IOUtils.write(content, response.getOutputStream(), Charset.defaultCharset());
}
 
Example #22
Source File: UserController.java    From spring-security-oauth with MIT License 5 votes vote down vote up
@PreAuthorize("#oauth2.hasScope('read')")
@RequestMapping(method = RequestMethod.GET, value = "/users/extra")
@ResponseBody
public Map<String, Object> getExtraInfo(Authentication auth) {
    OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) auth.getDetails();
    Map<String, Object> details = (Map<String, Object>) oauthDetails.getDecodedDetails();
    System.out.println("User organization is " + details.get("organization"));
    return details;
}
 
Example #23
Source File: UserController.java    From spring-security-oauth with MIT License 5 votes vote down vote up
@PreAuthorize("#oauth2.hasScope('read')")
@RequestMapping(method = RequestMethod.GET, value = "/users/extra")
@ResponseBody
public Map<String, Object> getExtraInfo(OAuth2Authentication auth) {
    final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
    final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
    System.out.println(accessToken);
    return accessToken.getAdditionalInformation();
}
 
Example #24
Source File: OAuth2Utils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static Optional<String> getAccessTokenValue(TokenExtractor tokenExtractor,  HttpServletRequest request){
	String accessToken = (String)request.getAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE);
	if(accessToken==null){
		Authentication authentication = tokenExtractor.extract(request);
		accessToken = authentication==null?null:(String)authentication.getPrincipal();
	}
	return Optional.ofNullable(accessToken);
}
 
Example #25
Source File: UserFeignClientInterceptor.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example #26
Source File: SpringSecurityConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
    return new RequestInterceptor() {
        @Override
        public void apply(RequestTemplate requestTemplate) {
        	LOGGER.info("SecurityContextHolder.getContext() ============== {}",SecurityContextHolder.getContext());
        	LOGGER.info("SecurityContextHolder.getContext() =============="+SecurityContextHolder.getContext());
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
            requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        }
    };
}
 
Example #27
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example #28
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example #29
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}
 
Example #30
Source File: UserFeignClientInterceptor.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate template) {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();

    if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {

        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        template.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
    }
}