org.springframework.security.oauth2.provider.OAuth2Authentication Java Examples
The following examples show how to use
org.springframework.security.oauth2.provider.OAuth2Authentication.
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: FacebookTokenServices.java From geowave with Apache License 2.0 | 6 votes |
@Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(tokenName, accessToken); final HttpHeaders headers = new HttpHeaders(); String req = ""; try { req = checkTokenEndpointUrl + "?access_token=" + URLEncoder.encode(accessToken, "UTF-8"); } catch (final UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); } final Map<String, Object> map = getForMap(req, formData, headers); if (map.containsKey("error")) { logger.debug("check_token returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); } return tokenConverter.extractAuthentication(map); }
Example #2
Source File: GleeController.java From spring-glee-o-meter with GNU General Public License v3.0 | 6 votes |
@GetMapping("/search") Page<Glee> search( @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "fromDate", required = false) LocalDate fromDate, @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam(value = "toDate", required = false) LocalDate toDate, @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) @RequestParam(value = "fromTime", required = false) LocalTime fromTime, @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) @RequestParam(value = "toTime", required = false) LocalTime toTime, @RequestParam(value = "text", required = false) String text, @RequestParam(value = "value", required = false) Double cal, @RequestParam(value = "userId", required = false) Long userId, Pageable pageable, OAuth2Authentication authentication) { String auth = (String) authentication.getUserAuthentication().getPrincipal(); String role = authentication.getAuthorities().iterator().next().getAuthority(); if (role.equals(User.Role.USER.name())) { User user = userRepository.findByEmail(auth).orElseThrow(() -> new EntityNotFoundException(User.class, "email", auth)); userId = user.getId(); return repository.filter(fromDate, toDate, fromTime, toTime, text, cal, userId, pageable); } return repository.filter(fromDate, toDate, fromTime, toTime, text, cal, userId, pageable); }
Example #3
Source File: MyInfoAPI.java From springboot-seed with MIT License | 6 votes |
@ApiOperation(value = "绑定微信个人信息" ) @PutMapping("/bind_wx" ) public ResponseEntity<?> bindUserInfo(@RequestBody Map<String, Object> params) { OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); SecurityUser principal = (SecurityUser) auth.getPrincipal(); User user = userService.selectByID(principal.getId()).get(); user.setNickname(params.get("nickName" ).toString()); user.setGender(Short.parseShort(params.get("gender" ).toString())); user.setLanguage(params.get("language" ).toString()); user.setCity(params.get("city" ).toString()); user.setProvince(params.get("province" ).toString()); user.setCountry(params.get("country" ).toString()); user.setAvatarUrl(params.get("avatarUrl" ).toString()); userService.modifyById(user); return ResponseEntity.status(HttpStatus.OK).body(user); }
Example #4
Source File: MongoTokenStore.java From spring-security-mongo with MIT License | 6 votes |
@Override public OAuth2AccessToken getAccessToken(final OAuth2Authentication authentication) { OAuth2AccessToken accessToken = null; String key = authenticationKeyGenerator.extractKey(authentication); final MongoOAuth2AccessToken oAuth2AccessToken = mongoOAuth2AccessTokenRepository.findByAuthenticationId(key); if (oAuth2AccessToken != null) { accessToken = deserializeAccessToken(oAuth2AccessToken.getToken()); } if (accessToken != null && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) { removeAccessToken(accessToken.getValue()); // Keep the store consistent (maybe the same user is represented by this authentication but the details have // changed) storeAccessToken(accessToken, authentication); } return accessToken; }
Example #5
Source File: RedisAuthorizationCodeServices.java From springcloud-oauth2 with MIT License | 6 votes |
/** * 取出授权码并删除授权码(权限码只能用一次,调试时可不删除,code就可多次使用) * * @param code * @return org.springframework.security.oauth2.provider.OAuth2Authentication */ @Override protected OAuth2Authentication remove(String code) { byte[] serializedKey = serializeKey(AUTHORIZATION_CODE + code); RedisConnection conn = getConnection(); byte[] bytes; try { bytes = conn.get(serializedKey); if (bytes != null) { conn.del(serializedKey); } } finally { conn.close(); } return deserializeAuthentication(bytes); }
Example #6
Source File: CustomRedisTokenStore.java From microservices-platform with Apache License 2.0 | 6 votes |
@Override public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue()); byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue()); byte[] serializedRefreshToken = serialize(refreshToken); RedisConnection conn = getConnection(); try { conn.openPipeline(); if (springDataRedis_2_0) { try { this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken); this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication)); } catch (Exception ex) { throw new RuntimeException(ex); } } else { conn.set(refreshKey, serializedRefreshToken); conn.set(refreshAuthKey, serialize(authentication)); } expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey); conn.closePipeline(); } finally { conn.close(); } }
Example #7
Source File: AuthorizationServerConfiguration.java From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License | 6 votes |
@PostMapping("/introspect") @ResponseBody public Map<String, Object> introspect(@RequestParam("token") String token) { OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token); Map<String, Object> attributes = new HashMap<>(); if (accessToken == null || accessToken.isExpired()) { attributes.put("active", false); return attributes; } OAuth2Authentication authentication = this.tokenStore.readAuthentication(token); attributes.put("active", true); attributes.put("exp", accessToken.getExpiration().getTime()); attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" "))); attributes.put("sub", authentication.getName()); return attributes; }
Example #8
Source File: AuthorizationServerConfig.java From cloud-service with MIT License | 6 votes |
/** * 将当前用户信息追加到登陆后返回的json数据里<br> * 通过参数access_token.add-userinfo控制<br> * 2019.07.13 * * @param accessToken * @param authentication */ private void addLoginUserInfo(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { if (!addUserInfo) { return; } if (accessToken instanceof DefaultOAuth2AccessToken) { DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken; Authentication userAuthentication = authentication.getUserAuthentication(); Object principal = userAuthentication.getPrincipal(); if (principal instanceof LoginAppUser) { LoginAppUser loginUser = (LoginAppUser) principal; Map<String, Object> map = new HashMap<>(defaultOAuth2AccessToken.getAdditionalInformation()); // 旧的附加参数 map.put("loginUser", loginUser); // 追加当前登陆用户 defaultOAuth2AccessToken.setAdditionalInformation(map); } } }
Example #9
Source File: OpenHelper.java From open-cloud with MIT License | 6 votes |
/*** * 更新客户端权限 * @param tokenStore * @param clientId * @param authorities */ public static void updateOpenClientAuthorities(TokenStore tokenStore, String clientId, Collection<? extends GrantedAuthority> authorities) { if (authorities == null) { return; } // 动态更新客户端生成的token Collection<OAuth2AccessToken> accessTokens = tokenStore.findTokensByClientId(clientId); if (accessTokens != null && !accessTokens.isEmpty()) { Iterator<OAuth2AccessToken> iterator = accessTokens.iterator(); while (iterator.hasNext()) { OAuth2AccessToken token = iterator.next(); OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token); if (oAuth2Authentication != null && oAuth2Authentication.isClientOnly()) { // 只更新客户端权限 // 由于没有set方法,使用反射机制强制赋值 ReflectionUtils.setFieldValue(oAuth2Authentication, "authorities", authorities); // 重新保存 tokenStore.storeAccessToken(token, oAuth2Authentication); } } } }
Example #10
Source File: OsiamTokenEnhancer.java From osiam with MIT License | 6 votes |
@Override public OAuth2AccessToken enhance(final OAuth2AccessToken accessToken, final OAuth2Authentication authentication) { DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken; Map<String, Object> additionalInformation = new HashMap<>(); additionalInformation.put("expires_at", token.getExpiration()); if (token.getRefreshToken() != null) { DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken) token.getRefreshToken(); additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration()); } additionalInformation.put("client_id", authentication.getOAuth2Request().getClientId()); if (authentication.getUserAuthentication() != null && authentication.getPrincipal() instanceof User) { User user = (User) authentication.getPrincipal(); additionalInformation.put("user_name", user.getUserName()); additionalInformation.put("user_id", user.getId()); } token.setAdditionalInformation(additionalInformation); return accessToken; }
Example #11
Source File: AccountResource.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 6 votes |
/** * GET /account : get the current user. * * @param principal the current user; resolves to null if not authenticated * @return the current user * @throws InternalServerErrorException 500 (Internal Server Error) if the user couldn't be returned */ @GetMapping("/account") @Timed @SuppressWarnings("unchecked") public UserDTO getAccount(Principal principal) { if (principal != null) { if (principal instanceof OAuth2Authentication) { return userService.getUserFromAuthentication((OAuth2Authentication) principal); } else { // Allow Spring Security Test to be used to mock users in the database return userService.getUserWithAuthorities() .map(UserDTO::new) .orElseThrow(() -> new InternalServerErrorException("User could not be found")); } } else { throw new InternalServerErrorException("User could not be found"); } }
Example #12
Source File: FwJwtTokenEnhancer.java From fw-spring-cloud with Apache License 2.0 | 5 votes |
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { //为返回的access token 添加返回信息 Map<String, Object> info = new HashMap<>(); info.put("name", "yisu"); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info); return accessToken; }
Example #13
Source File: UserServiceIntTest.java From okta-jhipster-microservices-oauth-example with Apache License 2.0 | 5 votes |
private OAuth2Authentication createMockOAuth2AuthenticationWithDetails(Map<String, Object> userDetails) { Set<String> scopes = new HashSet<String>(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Constants.ANONYMOUS_USER, Constants.ANONYMOUS_USER, authorities); usernamePasswordAuthenticationToken.setDetails(userDetails); OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null, null); return new OAuth2Authentication(authRequest, usernamePasswordAuthenticationToken); }
Example #14
Source File: SAPOfflineTokenServicesCloud.java From cloud-security-xsuaa-integration with Apache License 2.0 | 5 votes |
@Override public OAuth2Authentication loadAuthentication(@Nonnull String accessToken) throws AuthenticationException, InvalidTokenException { Token token = checkAndCreateToken(accessToken); ValidationResult validationResult = tokenValidator.validate(token); if (validationResult.isErroneous()) { throw new InvalidTokenException(validationResult.getErrorDescription()); } SecurityContext.setToken(token); return getOAuth2Authentication(serviceConfiguration.getClientId(), getScopes(token)); }
Example #15
Source File: DiscordTokenServices.java From JuniperBot with GNU General Public License v3.0 | 5 votes |
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { try { return authorities.get(accessToken); } catch (ExecutionException | UncheckedExecutionException e) { if (e.getCause() instanceof OAuth2Exception) { throw (OAuth2Exception) e.getCause(); } throw new RuntimeException(e); } }
Example #16
Source File: MyParkAPI.java From springboot-seed with MIT License | 5 votes |
@ApiOperation(value = "最近一次停车记录") @GetMapping(value = "/last_car_fee", produces = "application/json; charset=utf-8") public ResponseEntity<?> car_fee_list() throws Exception { OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); Long currentUserId = ((SecurityUser) auth.getPrincipal()).getId(); List<Car> carList = carService.selectAll( new QueryParameter[]{new QueryParameter("userId", QueryParameterMethod.EQUAL, currentUserId.toString(), QueryParameterType.LONG)}); String cars = EMPTY_STRING; for (int i = 0; i < carList.size(); i++) { cars += carList.get(i).getCarNumber(); if (i != carList.size() - 1) cars += ","; } QueryParameter[] parameters = new QueryParameter[]{ new QueryParameter("carNumber", QueryParameterMethod.IN, cars, QueryParameterType.ARRAY), new QueryParameter("userId", QueryParameterMethod.IS_NULL, EMPTY_STRING, QueryParameterType.STRING)}; List<CarFee> carFeeList = carFeeService.selectTop(1, parameters); if (carFeeList.size() != 1) { parameters = new QueryParameter[]{ new QueryParameter("userId", QueryParameterMethod.EQUAL, currentUserId.toString(), QueryParameterType.LONG) }; carFeeList = carFeeService.selectTop(1, parameters); } if (carFeeList.size() == 1) { Park park = parkService.selectByID(carFeeList.get(0).getParkId()).get(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); SimpleModule module = new SimpleModule(); module.addSerializer(String.class, new StringUnicodeSerializer()); mapper.registerModule(module); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return ResponseEntity.status(HttpStatus.OK).header("park", mapper.writeValueAsString(park)).body(carFeeList.get(0)); } else { return ResponseEntity.ok().build(); } }
Example #17
Source File: UserController.java From spring-cloud-skipper with Apache License 2.0 | 5 votes |
@RequestMapping("/revoke_token") public boolean revokeToken() { final OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder .getContext().getAuthentication(); final String token = this.tokenStore.getAccessToken(auth).getValue(); return tokenServices.revokeToken(token); }
Example #18
Source File: OauthMongoSessionManager.java From secure-data-service with Apache License 2.0 | 5 votes |
private OAuth2Authentication createAnonymousAuth() { String time = Long.toString(System.currentTimeMillis()); SLIPrincipal anon = new SLIPrincipal(time); anon.setEntity(new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>())); return new OAuth2Authentication(new ClientToken("UNKNOWN", "UNKNOWN", new HashSet<String>()), new AnonymousAuthenticationToken(time, anon, Arrays.<GrantedAuthority> asList(Right.ANONYMOUS_ACCESS))); }
Example #19
Source File: CustomTokenServices.java From multiapps-controller with Apache License 2.0 | 5 votes |
@Override public OAuth2Authentication loadAuthentication(String tokenString) { // Get an access token for the specified token string OAuth2AccessToken token = readAccessToken(tokenString); // Check if a valid access token has been obtained if (token == null) { logToAuditLogAndThrow("Invalid access token"); } // Check if the token has expired and there is no refresh token if (token.isExpired() && token.getRefreshToken() == null) { tokenStore.removeAccessToken(token); logToAuditLogAndThrow(MessageFormat.format("The access token has expired on {0}", token.getExpiration())); } // Check if an authentication for this token already exists in the token store OAuth2Authentication auth = tokenStore.readAuthentication(token); if (auth == null) { // Create an authentication for the token and store it in the token store TokenProperties tokenProperties = TokenProperties.fromToken(token); auth = SecurityUtil.createAuthentication(tokenProperties.getClientId(), token.getScope(), SecurityUtil.getTokenUserInfo(token)); try { LOGGER.info(MessageFormat.format(Messages.STORING_TOKEN_FOR_USER_0_WITH_EXPIRATION_TIME_1, tokenProperties.getUserName(), token.getExpiresIn())); tokenStore.storeAccessToken(token, auth); } catch (DataIntegrityViolationException e) { LOGGER.debug(Messages.ERROR_STORING_TOKEN_DUE_TO_INTEGRITY_VIOLATION, e); // Ignoring the exception as the token and authentication are already persisted by another client. } } return auth; }
Example #20
Source File: JwtCustomHeadersAccessTokenConverter.java From spring-security-oauth with MIT License | 5 votes |
@Override protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { String content; try { content = this.objectMapper.formatMap(getAccessTokenConverter().convertAccessToken(accessToken, authentication)); } catch (Exception ex) { throw new IllegalStateException("Cannot convert access token to JSON", ex); } String token = JwtHelper.encode(content, this.signer, this.customHeaders) .getEncoded(); return token; }
Example #21
Source File: JweTokenEnhancer.java From OAuth-2.0-Cookbook with MIT License | 5 votes |
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken); Map<String, Object> info = new LinkedHashMap<>(accessToken.getAdditionalInformation()); String tokenId = result.getValue(); if (!info.containsKey(TOKEN_ID)) { info.put(TOKEN_ID, tokenId); } result.setAdditionalInformation(info); result.setValue(encode(result, authentication)); return result; }
Example #22
Source File: ApiService.java From pacbot with Apache License 2.0 | 5 votes |
public void logout(Principal principal) { JdbcTokenStore jdbcTokenStore = tokenStore(); OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal; OAuth2AccessToken accessToken = jdbcTokenStore.getAccessToken(oAuth2Authentication); jdbcTokenStore.removeAccessToken(accessToken.getValue()); jdbcTokenStore.removeRefreshToken(accessToken.getRefreshToken()); }
Example #23
Source File: SessionCache.java From secure-data-service with Apache License 2.0 | 5 votes |
private void replicate(String token, OAuth2Authentication auth) { try { ObjectMessage msg = createMessage(token, auth, PUT); tp.send(msg); } catch (JMSException e) { LOG.error("Failed to replicate session cache entry", e); } }
Example #24
Source File: DiscordTokenServices.java From JuniperBot with GNU General Public License v3.0 | 5 votes |
public OAuth2Authentication load(String accessToken) { Map map = executeRequest(Map.class, apiProperties.getDiscord().getUserInfoUri(), accessToken); Object principal = map.get("username"); principal = (principal == null ? "unknown" : principal); List<GrantedAuthority> authorities = authoritiesExtractor.extractAuthorities(map); OAuth2Request request = new OAuth2Request(null, apiProperties.getDiscord().getClientId(), null, true, null, null, null, null, null); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(DiscordUserDetails.create(map)); return new OAuth2Authentication(request, token); }
Example #25
Source File: UserController.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@RequestMapping("/revoke_token") public boolean revokeToken() { final OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder .getContext().getAuthentication(); final String token = this.tokenStore.getAccessToken(auth).getValue(); return tokenServices.revokeToken(token); }
Example #26
Source File: GleeController.java From spring-glee-o-meter with GNU General Public License v3.0 | 5 votes |
@GetMapping Page<Glee> all(Pageable pageable, OAuth2Authentication authentication) { String auth = (String) authentication.getUserAuthentication().getPrincipal(); String role = authentication.getAuthorities().iterator().next().getAuthority(); if (role.equals(User.Role.USER.name())) { User user = userRepository.findByEmail(auth).orElseThrow(() -> new EntityNotFoundException(User.class, "email", auth)); return repository.findAllByUser(user, pageable); } return repository.findAll(pageable); }
Example #27
Source File: CustomAccessTokenConverter.java From spring-boot-2-oauth2-resource-jwt with MIT License | 5 votes |
@Override public OAuth2Authentication extractAuthentication(Map<String, ?> map) { Set<String> scope = extractScope(map); Map<String, String> parameters = new HashMap<String, String>(); Authentication user = userTokenConverter.extractAuthentication(map); String clientId = (String) map.get(CLIENT_ID); parameters.put(CLIENT_ID, clientId); if (includeGrantType && map.containsKey(GRANT_TYPE)) parameters.put(GRANT_TYPE, (String) map.get(GRANT_TYPE)); Set<String> resourceIds = new LinkedHashSet<String>( map.containsKey(AUD) ? getAudience(map) : Collections.<String>emptySet()); Collection<? extends GrantedAuthority> authorities = null; if (user == null && map.containsKey(AUTHORITIES)) { @SuppressWarnings("unchecked") String[] roles = ((Collection<String>) map.get(AUTHORITIES)).toArray(new String[0]); authorities = AuthorityUtils.createAuthorityList(roles); } OAuth2Request request = new OAuth2Request(parameters, clientId, authorities, true, scope, resourceIds, null, null, null); return new OAuth2Authentication(request, user); }
Example #28
Source File: CustomRedisTokenStore.java From microservices-platform with Apache License 2.0 | 5 votes |
@Override public OAuth2Authentication readAuthentication(String token) { byte[] bytes; RedisConnection conn = getConnection(); try { bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token)); } finally { conn.close(); } return deserializeAuthentication(bytes); }
Example #29
Source File: SpringSocialTokenServices.java From spring-security-oauth2-boot with Apache License 2.0 | 5 votes |
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException { AccessGrant accessGrant = new AccessGrant(accessToken); Connection<?> connection = this.connectionFactory.createConnection(accessGrant); UserProfile user = connection.fetchUserProfile(); return extractAuthentication(user); }
Example #30
Source File: OauthTokenAspect.java From microservices-platform with Apache License 2.0 | 5 votes |
private String getClientId(Principal principal) { Authentication client = (Authentication) principal; if (!client.isAuthenticated()) { throw new InsufficientAuthenticationException("The client is not authenticated."); } String clientId = client.getName(); if (client instanceof OAuth2Authentication) { clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId(); } return clientId; }