Java Code Examples for org.springframework.security.oauth2.provider.OAuth2Authentication#getUserAuthentication()

The following examples show how to use org.springframework.security.oauth2.provider.OAuth2Authentication#getUserAuthentication() . 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 vote down vote up
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: OsiamTokenEnhancer.java    From osiam with 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
Source File: AuthorizationServerConfig.java    From cloud-service with 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 4
Source File: OpenHelper.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 更新OpenUser
 *
 * @param openUser
 */
public static void updateOpenUser(TokenStore tokenStore, OpenUserDetails openUser) {
    if (openUser == null) {
        return;
    }
    Assert.notNull(openUser.getClientId(), "客户端ID不能为空");
    Assert.notNull(openUser.getUsername(), "用户名不能为空");
    // 动态更新客户端生成的token
    Collection<OAuth2AccessToken> accessTokens = tokenStore.findTokensByClientIdAndUserName(openUser.getClientId(), openUser.getUsername());
    if (accessTokens != null && !accessTokens.isEmpty()) {
        for (OAuth2AccessToken accessToken : accessTokens) {
            // 由于没有set方法,使用反射机制强制赋值
            OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(accessToken);
            if (oAuth2Authentication != null) {
                Authentication authentication = oAuth2Authentication.getUserAuthentication();
                ReflectionUtils.setFieldValue(authentication, "principal", openUser);
                // 重新保存
                tokenStore.storeAccessToken(accessToken, oAuth2Authentication);
            }
        }
    }
}
 
Example 5
Source File: ChoerodonAuthenticationKeyGenerator.java    From oauth-server with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: MeController.java    From osiam with MIT License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public MappingJacksonValue getCurrentUser(@RequestHeader("Authorization") String tokenHeader,
                                          @RequestParam(required = false) String attributes,
                                          HttpServletResponse response,
                                          UriComponentsBuilder builder) {

    if (Strings.isNullOrEmpty(tokenHeader)) {
        throw new IllegalArgumentException("No access token provided!"); // This should never happen!
    }

    String accessToken = tokenHeader.substring("Bearer ".length());

    OAuth2Authentication oAuth = resourceServerTokenServices.loadAuthentication(accessToken);
    if (oAuth.isClientOnly()) {
        throw new InvalidTokenException("Can't return an user. This access token belongs to a client.");
    }

    Authentication userAuthentication = oAuth.getUserAuthentication();

    Object principal = userAuthentication.getPrincipal();
    User user;
    if (principal instanceof User) {
        user = userProvisioning.getById(((User) principal).getId());
    } else {
        throw new IllegalArgumentException("User not authenticated.");
    }

    response.setHeader("Location", buildLocation(user, builder).toString());
    return buildResponse(user, attributes);
}
 
Example 7
Source File: KeycloakAuthenticationProvider.java    From camunda-bpm-identity-keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine) {

	// Extract authentication details
    OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return AuthenticationResult.unsuccessful();
    }
    Authentication userAuthentication = authentication.getUserAuthentication();
    if (userAuthentication == null || userAuthentication.getDetails() == null) {
        return AuthenticationResult.unsuccessful();
    }
    
    // Extract user ID from Keycloak authentication result - which is part of the requested user info
    @SuppressWarnings("unchecked")
    // String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("sub");
    String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("email"); // useEmailAsCamundaUserId = true
    // String userId = ((HashMap<String, String>) userAuthentication.getDetails()).get("preferred_username"); // useUsernameAsCamundaUserId = true
    if (StringUtils.isEmpty(userId)) {
        return AuthenticationResult.unsuccessful();
    }

    // Authentication successful
    AuthenticationResult authenticationResult = new AuthenticationResult(userId, true);
    authenticationResult.setGroups(getUserGroups(userId, engine));

    return authenticationResult;
}
 
Example 8
Source File: TokenJwtEnhancer.java    From paascloud-master with 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 9
Source File: FwRedisTokenStore.java    From fw-cloud-framework with MIT License 4 votes vote down vote up
private String getApprovalKey(OAuth2Authentication authentication) {
	String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication().getName();
	return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 10
Source File: LessStrictRedirectUriAuthorizationCodeTokenGranter.java    From osiam with MIT License 4 votes vote down vote up
@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 11
Source File: SecurityUtils.java    From JuniperBot with GNU General Public License v3.0 4 votes vote down vote up
public static Authentication getUserAuthentication() {
    OAuth2Authentication auth = getTokenAuthentication();
    return auth != null ? auth.getUserAuthentication() : null;
}
 
Example 12
Source File: CustomRedisTokenStore.java    From Auth-service with MIT License 4 votes vote down vote up
private static String getApprovalKey(OAuth2Authentication authentication) {
    String userName = authentication.getUserAuthentication() == null ? ""
            : authentication.getUserAuthentication().getName();
    return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 13
Source File: CustomAuthCodeTokenGranter.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@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 14
Source File: PigRedisTokenStore.java    From pig with MIT License 4 votes vote down vote up
private String getApprovalKey(OAuth2Authentication authentication) {
    String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication()
            .getName();
    return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 15
Source File: CustomRedisTokenStore.java    From microservices-platform with Apache License 2.0 4 votes vote down vote up
private static String getApprovalKey(OAuth2Authentication authentication) {
    String userName = authentication.getUserAuthentication() == null ? ""
            : authentication.getUserAuthentication().getName();
    return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 16
Source File: RedisTemplateTokenStore.java    From open-capacity-platform with Apache License 2.0 4 votes vote down vote up
private String getApprovalKey(OAuth2Authentication authentication) {
	String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication()
			.getName();
	return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 17
Source File: RedisTemplateTokenStore.java    From open-capacity-platform with Apache License 2.0 4 votes vote down vote up
private String getApprovalKey(OAuth2Authentication authentication) {
	String userName = authentication.getUserAuthentication() == null ? "" : authentication.getUserAuthentication()
			.getName();
	return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
 
Example 18
Source File: SysUserServiceImpl.java    From open-capacity-platform with Apache License 2.0 4 votes vote down vote up
@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;
}