Java Code Examples for org.springframework.security.oauth2.provider.OAuth2Authentication

The following examples show how to use org.springframework.security.oauth2.provider.OAuth2Authentication. These examples are extracted from open source projects. 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
/**
 * 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 2
Source Project: osiam   Source File: OsiamTokenEnhancer.java    License: MIT License 6 votes vote down vote up
@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 3
@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 4
Source Project: springboot-seed   Source File: MyInfoAPI.java    License: MIT License 6 votes vote down vote up
@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 5
Source Project: geowave   Source File: FacebookTokenServices.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: cloud-service   Source File: AuthorizationServerConfig.java    License: MIT License 6 votes vote down vote up
/**
 * 将当前用户信息追加到登陆后返回的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 7
@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 8
Source Project: spring-security-mongo   Source File: MongoTokenStore.java    License: MIT License 6 votes vote down vote up
@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 9
/**
 * 取出授权码并删除授权码(权限码只能用一次,调试时可不删除,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 10
@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 11
Source Project: open-cloud   Source File: OpenHelper.java    License: MIT License 6 votes vote down vote up
/***
 * 更新客户端权限
 * @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 12
@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 13
Source Project: smaker   Source File: SysLogUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取客户端
 *
 * @return clientId
 */
private static String getClientId() {
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	if (authentication instanceof OAuth2Authentication) {
		OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
		return auth2Authentication.getOAuth2Request().getClientId();
	}
	return null;
}
 
Example 14
Source Project: konker-platform   Source File: MongoTokenStore.java    License: Apache License 2.0 5 votes vote down vote up
protected OAuth2Authentication readAuthenticationForRefreshToken(String tokenValue) {
    OAuth2Authentication authentication = null;

    try {
        final String tokenId = extractTokenKey(tokenValue);
        RefreshToken refreshToken = refreshTokenRepository.findOne(tokenId);

        authentication = refreshToken == null ? null : refreshToken.authentication();
    } catch (IllegalArgumentException e) {
        LOG.warn("Failed to deserialize access token for {}", tokenValue);
        removeRefreshToken(tokenValue);
    }

    return authentication;
}
 
Example 15
@PersistenceConstructor
public OAuth2AuthenticationAccessToken(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication, String authenticationId) {
    this.id = UUID.randomUUID().toString();
    this.tokenId = oAuth2AccessToken.getValue();
    this.oAuth2AccessToken = oAuth2AccessToken;
    this.authenticationId = authenticationId;
    this.userName = authentication.getName();
    this.clientId = authentication.getOAuth2Request().getClientId();
    this.authentication = authentication;
    if(oAuth2AccessToken.getRefreshToken() != null) {
        this.refreshToken = oAuth2AccessToken.getRefreshToken().getValue();
    }
}
 
Example 16
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
		throws AuthenticationException, InvalidTokenException {
	Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken);
	if (map.containsKey("error")) {
		this.logger.info("userinfo returned error: " + map.get("error"));
		throw new InvalidTokenException(accessToken);
	}
	return extractAuthentication(map);
}
 
Example 17
@Test
public void testPersistTokenInCache() {
    OAuth2AccessToken token = buildValidToken();
    prepareTokenParserChain(token);

    OAuth2Authentication auth = customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING);

    assertNotNull(auth.getAuthorities());
    assertNotNull(auth.getCredentials());
    assertNotNull(auth.getOAuth2Request());
    verify(tokenStore).storeAccessToken(token, auth);
}
 
Example 18
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 19
Source Project: paascloud-master   Source File: TokenJwtEnhancer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Enhance o auth 2 access token.
 *
 * @param accessToken          the access token
 * @param oAuth2Authentication the o auth 2 authentication
 *
 * @return the o auth 2 access token
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication oAuth2Authentication) {
	Map<String, Object> info = new HashMap<>(8);
	info.put("timestamp", System.currentTimeMillis());
	Authentication authentication = oAuth2Authentication.getUserAuthentication();
	if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
		Object principal = authentication.getPrincipal();
		info.put("loginName", ((UserDetails) principal).getUsername());
	}

	((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);

	return accessToken;
}
 
Example 20
@Test
public void readAuthenticationForRefreshToken() throws Exception {
    when(tokenDAO.readAuthenticationForRefreshToken(Mockito.any(OAuth2RefreshToken.class))).thenReturn(Mockito.any(OAuth2Authentication.class));
    OAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken("value");
    OAuth2Authentication auth = this.tokenManager.readAuthenticationForRefreshToken(refreshToken);
    Assert.assertNull(auth);
    Mockito.verify(tokenDAO, Mockito.times(1)).readAuthenticationForRefreshToken(refreshToken);
}
 
Example 21
private UserJsonDto loadOauthUserJsonDto(OAuth2Authentication oAuth2Authentication) {
    UserJsonDto userJsonDto = new UserJsonDto();
    userJsonDto.setUsername(oAuth2Authentication.getName());

    final Collection<GrantedAuthority> authorities = oAuth2Authentication.getAuthorities();
    for (GrantedAuthority authority : authorities) {
        userJsonDto.getPrivileges().add(authority.getAuthority());
    }

    return userJsonDto;
}
 
Example 22
@GetMapping
Page<User> all(@PageableDefault(size = Integer.MAX_VALUE) Pageable pageable, OAuth2Authentication authentication) {
    String auth = (String) authentication.getUserAuthentication().getPrincipal();
    String role = authentication.getAuthorities().iterator().next().getAuthority();
    if (role.equals(User.Role.USER.name())) {
        return repository.findAllByEmail(auth, pageable);
    }
    return repository.findAll(pageable);
}
 
Example 23
/****
 * @param accessTokenValue no Bearer prefix
 */
@Override
public ClientDetails resolveClientDetails(String accessTokenValue) {
	accessTokenValue = extractHeaderToken(accessTokenValue);
	OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
	OAuth2Authentication authentication = tokenStore.readAuthentication(accessToken);
	return clientDetailConverter.convert(accessToken, authentication);
}
 
Example 24
Source Project: cola   Source File: AuthorizationServerConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public RedisTemplate<String, OAuth2Authentication> oauthRedisTemplate() {
	RedisTemplate<String, OAuth2Authentication> template = new RedisTemplate<>();
	template.setConnectionFactory(redisConnectionFactory);
	template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
	return template;
}
 
Example 25
Source Project: pig   Source File: PigRedisTokenStore.java    License: MIT License 5 votes vote down vote up
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

    this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token);
    this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication);
    this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), token);
    if (!authentication.isClientOnly()) {
        redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
    }

    redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);

    if (token.getExpiration() != null) {

        int seconds = token.getExpiresIn();
        redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS);

        redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS);
    }
    if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) {
        this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), token.getValue());
        this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), token.getRefreshToken().getValue());
    }
}
 
Example 26
Source Project: microservices-platform   Source File: OauthTokenAspect.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
@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 28
@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
@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 30
@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);
}