Java Code Examples for org.springframework.security.oauth2.provider.OAuth2Authentication#getOAuth2Request()
The following examples show how to use
org.springframework.security.oauth2.provider.OAuth2Authentication#getOAuth2Request() .
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: TokenService.java From osiam with MIT License | 7 votes |
public AccessToken validateToken(final String token) { OAuth2Authentication auth = tokenStore.readAuthentication(token); OAuth2AccessToken accessToken = tokenStore.getAccessToken(auth); OAuth2Request authReq = auth.getOAuth2Request(); AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId()); if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) { User user = (User) auth.getPrincipal(); tokenBuilder.setUserName(user.getUserName()); tokenBuilder.setUserId(user.getId()); } tokenBuilder.setExpiresAt(accessToken.getExpiration()); for (String scopeString : authReq.getScope()) { tokenBuilder.addScope(new Scope(scopeString)); } return tokenBuilder.build(); }
Example 2
Source File: CustomRedisTokenStore.java From microservices-platform with Apache License 2.0 | 6 votes |
@Override public OAuth2Authentication readAuthentication(OAuth2AccessToken token) { OAuth2Authentication auth2Authentication = readAuthentication(token.getValue()); //是否开启token续签 boolean isRenew = securityProperties.getAuth().getRenew().getEnable(); if (isRenew && auth2Authentication != null) { OAuth2Request clientAuth = auth2Authentication.getOAuth2Request(); //判断当前应用是否需要自动续签 if (checkRenewClientId(clientAuth.getClientId())) { //获取过期时长 int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId()); if (validitySeconds > 0) { double expiresRatio = token.getExpiresIn() / (double)validitySeconds; //判断是否需要续签,当前剩余时间小于过期时长的50%则续签 if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) { //更新AccessToken过期时间 DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token; oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); storeAccessToken(oAuth2AccessToken, auth2Authentication, true); } } } } return auth2Authentication; }
Example 3
Source File: OpenHelper.java From open-cloud with MIT License | 6 votes |
/** * 获取认证用户信息 * * @return */ public static OpenUserDetails getUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated() && authentication instanceof OAuth2Authentication) { OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication; OAuth2Request clientToken = oAuth2Authentication.getOAuth2Request(); if (!oAuth2Authentication.isClientOnly()) { if (authentication.getPrincipal() instanceof OpenUserDetails) { return (OpenUserDetails) authentication.getPrincipal(); } if (authentication.getPrincipal() instanceof Map) { return BeanConvertUtils.mapToObject((Map) authentication.getPrincipal(), OpenUserDetails.class); } } else { OpenUserDetails openUser = new OpenUserDetails(); openUser.setClientId(clientToken.getClientId()); openUser.setAuthorities(clientToken.getAuthorities()); return openUser; } } return null; }
Example 4
Source File: ChoerodonAuthenticationKeyGenerator.java From oauth-server with Apache License 2.0 | 6 votes |
@Override public String extractKey(OAuth2Authentication authentication) { Map<String, String> values = new LinkedHashMap<>(); OAuth2Request authorizationRequest = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) { values.put(USERNAME, authentication.getName()); } values.put(CLIENT_ID, authorizationRequest.getClientId()); if (authorizationRequest.getScope() != null) { values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<>(authorizationRequest.getScope()))); } Authentication auth = authentication.getUserAuthentication(); if (auth != null && auth.getDetails() instanceof WebAuthenticationDetails) { String sessionId = ((WebAuthenticationDetails) auth.getDetails()).getSessionId(); logger.info("sessionId : {}", sessionId); if (!StringUtils.isEmpty(sessionId)) { values.put(SESSION, sessionId); } } return generateKey(values); }
Example 5
Source File: JwtAccessTokenCustomizer.java From spring-oauth2-keycloak-connector with Apache License 2.0 | 6 votes |
/** * Spring oauth2 expects roles under authorities element in tokenMap, but keycloak provides it under resource_access. Hence extractAuthentication * method is overriden to extract roles from resource_access. * * @return OAuth2Authentication with authorities for given application */ @Override public OAuth2Authentication extractAuthentication(Map<String, ?> tokenMap) { LOG.debug("Begin extractAuthentication: tokenMap = {}", tokenMap); JsonNode token = mapper.convertValue(tokenMap, JsonNode.class); Set<String> audienceList = extractClients(token); // extracting client names List<GrantedAuthority> authorities = extractRoles(token); // extracting client roles OAuth2Authentication authentication = super.extractAuthentication(tokenMap); OAuth2Request oAuth2Request = authentication.getOAuth2Request(); OAuth2Request request = new OAuth2Request(oAuth2Request.getRequestParameters(), oAuth2Request.getClientId(), authorities, true, oAuth2Request.getScope(), audienceList, null, null, null); Authentication usernamePasswordAuthentication = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "N/A", authorities); LOG.debug("End extractAuthentication"); return new OAuth2Authentication(request, usernamePasswordAuthentication); }
Example 6
Source File: RedisTokensServiceImpl.java From microservices-platform with Apache License 2.0 | 5 votes |
@Override public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) { Integer page = MapUtils.getInteger(params, "page"); Integer limit = MapUtils.getInteger(params, "limit"); int[] startEnds = PageUtil.transToStartEnd(page, limit); //根据请求参数生成redis的key String redisKey = getRedisKey(params, clientId); long size = redisRepository.length(redisKey); List<TokenVo> result = new ArrayList<>(limit); //查询token集合 List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1); if (tokenObjs != null) { for (Object obj : tokenObjs) { DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj; //构造token对象 TokenVo tokenVo = new TokenVo(); tokenVo.setTokenValue(accessToken.getValue()); tokenVo.setExpiration(accessToken.getExpiration()); //获取用户信息 Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue()); OAuth2Authentication authentication = (OAuth2Authentication)authObj; if (authentication != null) { OAuth2Request request = authentication.getOAuth2Request(); tokenVo.setUsername(authentication.getName()); tokenVo.setClientId(request.getClientId()); tokenVo.setGrantType(request.getGrantType()); } result.add(tokenVo); } } return PageResult.<TokenVo>builder().data(result).code(0).count(size).build(); }
Example 7
Source File: YamiTokenServices.java From mall4j with GNU Affero General Public License v3.0 | 5 votes |
public String getClientId(String tokenValue) { OAuth2Authentication authentication = tokenStore.readAuthentication(tokenValue); if (authentication == null) { throw new InvalidTokenException("Invalid access token: " + tokenValue); } OAuth2Request clientAuth = authentication.getOAuth2Request(); if (clientAuth == null) { throw new InvalidTokenException("Invalid access token (no client id): " + tokenValue); } return clientAuth.getClientId(); }
Example 8
Source File: CustomAccessTokenConverter.java From microservices-oauth with Apache License 2.0 | 5 votes |
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); OAuth2Request clientToken = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); else if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) response.put(UserAuthenticationConverter.AUTHORITIES, AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); if (token.getScope() != null) response.put(SCOPE, token.getScope()); if (token.getAdditionalInformation().containsKey(JTI)) response.put(JTI, token.getAdditionalInformation().get(JTI)); if (token.getExpiration() != null) response.put(EXP, token.getExpiration().getTime() / 1000); if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); response.putAll(token.getAdditionalInformation()); response.put(CLIENT_ID, clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) response.put(AUD, clientToken.getResourceIds()); return response; }
Example 9
Source File: CustomAccessTokenConverter.java From spring-boot-2-oauth2-resource-jwt with MIT License | 5 votes |
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { Map<String, Object> response = new HashMap<String, Object>(); OAuth2Request clientToken = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) response.putAll(userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication())); else if (clientToken.getAuthorities() != null && !clientToken.getAuthorities().isEmpty()) response.put(UserAuthenticationConverter.AUTHORITIES, AuthorityUtils.authorityListToSet(clientToken.getAuthorities())); if (token.getScope() != null) response.put(SCOPE, token.getScope()); if (token.getAdditionalInformation().containsKey(JTI)) response.put(JTI, token.getAdditionalInformation().get(JTI)); if (token.getExpiration() != null) response.put(EXP, token.getExpiration().getTime() / 1000); if (includeGrantType && authentication.getOAuth2Request().getGrantType() != null) response.put(GRANT_TYPE, authentication.getOAuth2Request().getGrantType()); response.putAll(token.getAdditionalInformation()); response.put(CLIENT_ID, clientToken.getClientId()); if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) response.put(AUD, clientToken.getResourceIds()); return response; }
Example 10
Source File: SysUserServiceImpl.java From open-capacity-platform with Apache License 2.0 | 4 votes |
@Transactional @Override public SysUser updateSysUser(SysUser sysUser) { sysUser.setUpdateTime(new Date()); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof OAuth2Authentication) { OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication; authentication = oAuth2Auth.getUserAuthentication(); OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) oAuth2Auth.getDetails(); LoginAppUser user = SysUserUtil.getLoginAppUser(); if (user != null) { if ( !ObjectUtils.notEqual(user.getId(),sysUser.getId()) ) { OAuth2AccessToken token = redisTokenStore.readAccessToken(details.getTokenValue()); if (token != null) { if (!StringUtils.isBlank(sysUser.getHeadImgUrl())) { user.setHeadImgUrl(sysUser.getHeadImgUrl()); } if (!StringUtils.isBlank(sysUser.getNewPassword())) { user.setPassword(sysUser.getNewPassword()); } if (!StringUtils.isBlank(sysUser.getNewPassword())) { user.setPassword(sysUser.getNewPassword()); } if (!StringUtils.isBlank(sysUser.getNickname())) { user.setNickname(sysUser.getNickname()); } if (!StringUtils.isBlank(sysUser.getPhone())){ user.setPhone(sysUser.getPhone()); } if (sysUser.getSex() != null) { user.setSex(sysUser.getSex()); } UsernamePasswordAuthenticationToken userAuthentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Auth.getOAuth2Request(), userAuthentication); oAuth2Authentication.setAuthenticated(true); redisTokenStore.storeAccessToken(token, oAuth2Authentication); } } } } sysUserDao.updateByOps(sysUser); log.info("修改用户:{}", sysUser); return sysUser; }
Example 11
Source File: CustomAuthCodeTokenGranter.java From OAuth-2.0-Cookbook with MIT License | 4 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = tokenRequest.getRequestParameters(); String authorizationCode = parameters.get("code"); String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI); String codeVerifier = parameters.get("code_verifier"); if (authorizationCode == null) { throw new InvalidRequestException("An authorization code must be supplied."); } OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode); if (storedAuth == null) { throw new InvalidGrantException("Invalid authorization code: " + authorizationCode); } OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request(); // Validates code verifier Map<String, String> pendingOauth2RequestParams = pendingOAuth2Request.getRequestParameters(); String codeChallenge = pendingOauth2RequestParams.get("code_challenge"); String codeChallengeMethod = pendingOauth2RequestParams.get("code_challenge_method"); if (codeVerifier == null && codeChallenge != null) { // client is using PKCE but did not send the codeVerifier throw new InvalidRequestException( "Invalid authorization code for current token request."); } if (codeVerifier != null && codeChallenge != null) { String hashed = codeVerifier; if ("S256".equals(codeChallengeMethod)) { hashed = DigestUtils.sha256Hex(codeVerifier); } if (!hashed.equalsIgnoreCase(codeChallenge)) { throw new InvalidRequestException( "Invalid authorization code for current token request."); } } // https://jira.springsource.org/browse/SECOAUTH-333 // This might be null, if the authorization was done without the redirect_uri parameter String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get( OAuth2Utils.REDIRECT_URI); if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) { throw new RedirectMismatchException("Redirect URI mismatch."); } String pendingClientId = pendingOAuth2Request.getClientId(); String clientId = tokenRequest.getClientId(); if (clientId != null && !clientId.equals(pendingClientId)) { // just a sanity check. throw new InvalidClientException("Client ID mismatch"); } // Secret is not required in the authorization request, so it won't be available // in the pendingAuthorizationRequest. We do want to check that a secret is provided // in the token request, but that happens elsewhere. Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request .getRequestParameters()); // Combine the parameters adding the new ones last so they override if there are any clashes combinedParameters.putAll(parameters); // Make a new stored request with the combined parameters OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters); Authentication userAuth = storedAuth.getUserAuthentication(); return new OAuth2Authentication(finalStoredOAuth2Request, userAuth); }
Example 12
Source File: LessStrictRedirectUriAuthorizationCodeTokenGranter.java From osiam with MIT License | 4 votes |
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = tokenRequest.getRequestParameters(); String authorizationCode = parameters.get("code"); String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI); if (authorizationCode == null) { throw new InvalidRequestException("An authorization code must be supplied."); } OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode); if (storedAuth == null) { throw new InvalidGrantException("Invalid authorization code: " + authorizationCode); } OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request(); // https://jira.springsource.org/browse/SECOAUTH-333 // This might be null, if the authorization was done without the redirect_uri parameter String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); if (redirectUriApprovalParameter != null && redirectUri == null || redirectUriApprovalParameter != null && !pendingOAuth2Request.getRedirectUri().startsWith(redirectUri)) { throw new RedirectMismatchException("Redirect URI mismatch."); } String pendingClientId = pendingOAuth2Request.getClientId(); String clientId = tokenRequest.getClientId(); if (clientId != null && !clientId.equals(pendingClientId)) { // just a sanity check. throw new InvalidClientException("Client ID mismatch"); } // Secret is not required in the authorization request, so it won't be available // in the pendingAuthorizationRequest. We do want to check that a secret is provided // in the token request, but that happens elsewhere. Map<String, String> combinedParameters = new HashMap<>(pendingOAuth2Request.getRequestParameters()); // Combine the parameters adding the new ones last so they override if there are any clashes combinedParameters.putAll(parameters); // Make a new stored request with the combined parameters OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters); Authentication userAuth = storedAuth.getUserAuthentication(); return new OAuth2Authentication(finalStoredOAuth2Request, userAuth); }
Example 13
Source File: OAuth2TokenDAO.java From entando-core with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void storeAccessToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Connection conn = null; PreparedStatement stat = null; try { conn = this.getConnection(); String tokenValue = accessToken.getValue(); if (null != this.getAccessToken(tokenValue, conn)) { logger.debug("storeAccessToken: Stored Token already exists"); return; } conn.setAutoCommit(false); stat = conn.prepareStatement(INSERT_TOKEN); stat.setString(1, accessToken.getValue()); if (accessToken instanceof OAuth2AccessTokenImpl) { stat.setString(2, ((OAuth2AccessTokenImpl) accessToken).getClientId()); } else if (null != authentication.getOAuth2Request()) { stat.setString(2, authentication.getOAuth2Request().getClientId()); } else { stat.setNull(2, Types.VARCHAR); } stat.setTimestamp(3, new Timestamp(accessToken.getExpiration().getTime())); stat.setString(4, accessToken.getRefreshToken().getValue()); if (accessToken instanceof OAuth2AccessTokenImpl) { stat.setString(5, ((OAuth2AccessTokenImpl) accessToken).getGrantType()); stat.setString(6, ((OAuth2AccessTokenImpl) accessToken).getLocalUser()); } else { if (null != authentication.getOAuth2Request()) { stat.setString(5, authentication.getOAuth2Request().getGrantType()); } else { stat.setNull(5, Types.VARCHAR); } if (authentication.getPrincipal() instanceof UserDetails) { stat.setString(6, ((UserDetails) authentication.getPrincipal()).getUsername()); } else { stat.setString(6, authentication.getPrincipal().toString()); } } stat.executeUpdate(); conn.commit(); } catch (Exception t) { this.executeRollback(conn); logger.error("Error while adding an access token", t); throw new RuntimeException("Error while adding an access token", t); } finally { closeDaoResources(null, stat, conn); } }