org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest Java Examples

The following examples show how to use org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest. 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: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 7 votes vote down vote up
private OAuth2UserService<OAuth2UserRequest, OAuth2User> mockUserService() {
	Map<String, Object> attributes = new HashMap<>();
	attributes.put("id", "joeg");
	attributes.put("first-name", "Joe");
	attributes.put("last-name", "Grandja");
	attributes.put("email", "[email protected]");

	GrantedAuthority authority = new OAuth2UserAuthority(attributes);
	Set<GrantedAuthority> authorities = new HashSet<>();
	authorities.add(authority);

	DefaultOAuth2User user = new DefaultOAuth2User(authorities, attributes, "email");

	OAuth2UserService userService = mock(OAuth2UserService.class);
	when(userService.loadUser(any())).thenReturn(user);
	return userService;
}
 
Example #2
Source File: CustomOAuth2UserService.java    From spring-boot-react-blog with Apache License 2.0 6 votes vote down vote up
private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) {
    OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes());
    if(StringUtils.isEmpty(oAuth2UserInfo.getEmail())) {
        throw new ApiException("Email not found from OAuth2 provider", HttpStatus.NOT_FOUND);
    }

    Optional<User> userOptional = userRepository.findByEmail(oAuth2UserInfo.getEmail());
    User user;
    if(userOptional.isPresent()) {
        user = userOptional.get();
        if(!user.getProvider().equals(AuthProvider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))) {
            throw new ApiException("Looks like you're signed up with " +
                    user.getProvider() + " account. Please use your " + user.getProvider() +
                    " account to login.", HttpStatus.NOT_FOUND);
        }
        user = updateExistingUser(user, oAuth2UserInfo);
    } else {
        user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo);
    }

    return CustomUserDetails.create(user, oAuth2User.getAttributes());
}
 
Example #3
Source File: CustomOAuth2UserService.java    From training with MIT License 6 votes vote down vote up
private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) {
    OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes());
    if(StringUtils.isEmpty(oAuth2UserInfo.getEmail())) {
        throw new OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider");
    }

    Optional<User> userOptional = userRepository.findByEmail(oAuth2UserInfo.getEmail());
    User user;
    if(userOptional.isPresent()) {
        user = userOptional.get();
        if(!user.getProvider().equals(AuthProvider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))) {
            throw new OAuth2AuthenticationProcessingException("Looks like you're signed up with " +
                    user.getProvider() + " account. Please use your " + user.getProvider() +
                    " account to login.");
        }
        user = updateExistingUser(user, oAuth2UserInfo);
    } else {
        user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo);
    }

    return UserPrincipal.create(user, oAuth2User.getAttributes());
}
 
Example #4
Source File: CustomOAuth2UserService.java    From spring-boot-react-blog with Apache License 2.0 5 votes vote down vote up
private User registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) {
    User user = new User();

    user.setProvider(AuthProvider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()));
    user.setProviderId(oAuth2UserInfo.getId());
    user.setUserName(oAuth2UserInfo.getName());
    user.setEmail(oAuth2UserInfo.getEmail());
    user.setImageUrl(oAuth2UserInfo.getImageUrl());
    return userRepository.save(user);
}
 
Example #5
Source File: CustomOAuth2UserService.java    From training with MIT License 5 votes vote down vote up
private User registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) {
    User user = new User();

    user.setProvider(AuthProvider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()));
    user.setProviderId(oAuth2UserInfo.getId());
    user.setName(oAuth2UserInfo.getName());
    user.setEmail(oAuth2UserInfo.getEmail());
    user.setImageUrl(oAuth2UserInfo.getImageUrl());
    return userRepository.save(user);
}
 
Example #6
Source File: OAuth2MappingUserService.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    OAuth2User auth = super.loadUser(userRequest);
    Map<String, Object> map = auth.getAttributes();

    UserData data = new UserData(map);

    Registration.User user = registration.getOrRegister(data.id(), data.email(), data.readableName());
    
    return user;
}
 
Example #7
Source File: SecurityConfig.java    From oauth2-client with MIT License 4 votes vote down vote up
/**
 * 从access_token中直接抽取角色等信息
 * https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2login-advanced-map-authorities-oauth2userservice
 *
 * @return
 */
@SuppressWarnings("unchecked")
@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {

    return (userRequest) -> {
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (!StringUtils.hasText(userNameAttributeName)) {
            userNameAttributeName = "sub";
        }
        OAuth2AccessToken accessToken = userRequest.getAccessToken();
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        try {
            SignedJWT jwt = SignedJWT.parse(accessToken.getTokenValue());
            String claimJsonString = jwt.getJWTClaimsSet().toJSONObject().toJSONString();
            Object document = com.jayway.jsonpath.Configuration.defaultConfiguration().jsonProvider().parse(claimJsonString);

            List<Object> authorities = JsonPath.using(conf).parse(document).read("$..roles");

            if (authorities == null || authorities.size() == 0) {
                authorities = JsonPath.using(conf).parse(document).read("$..authorities");
            }
            Collection<String> roles = new ArrayList<>();
            authorities.forEach(authorityItem -> {
                if (authorityItem instanceof String) {
                    roles.add((String) authorityItem);
                } else if (authorityItem instanceof JSONArray) {
                    roles.addAll((Collection<String>) authorityItem);
                } else if (authorityItem instanceof Collection) {
                    roles.addAll((Collection<String>) authorityItem);
                }
            });

            for (String authority : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority));
            }
            Map<String, Object> userAttributes = new HashMap<>(16);
            userAttributes.put(userNameAttributeName, JsonPath.using(conf).parse(document).read("$." + userNameAttributeName));
            userAttributes.put("preferred_username", JsonPath.using(conf).parse(document).read("$.preferred_username"));
            userAttributes.put("email", JsonPath.using(conf).parse(document).read("$.email"));
            OAuth2User oAuth2User = new DefaultOAuth2User(grantedAuthorities, userAttributes, userNameAttributeName);

            return oAuth2User;
        } catch (Exception e) {
            log.error("oauth2UserService Exception", e);
        }
        return null;
    };
}
 
Example #8
Source File: RefreshExpiredTokenFilter.java    From oauth2-client with MIT License 4 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
    log.debug("entering Refresh ExpiredToken Filter......");
    /**
     * check if authentication is done.
     */
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (null != authentication && authentication instanceof OAuth2AuthenticationToken) {

        OAuth2AuthenticationToken oldOAuth2Token = (OAuth2AuthenticationToken) authentication;
        OAuth2AuthorizedClient authorizedClient = this.oAuth2AuthorizedClientService
            .loadAuthorizedClient(oldOAuth2Token.getAuthorizedClientRegistrationId(), oldOAuth2Token.getName());
        /**
         * Check whether token is expired.
         */
        if (authorizedClient != null && isExpired(authorizedClient.getAccessToken())) {

            try {
                log.info("===================== Token Expired , trying to refresh");
                ClientRegistration clientRegistration = authorizedClient.getClientRegistration();
                /*
                 * Call Auth server token endpoint to refresh token.
                 */
                OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, authorizedClient.getAccessToken(), authorizedClient.getRefreshToken());
                OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(refreshTokenGrantRequest);

                OAuth2User newOAuth2User = oAuth2UserService.loadUser(new OAuth2UserRequest(clientRegistration, accessTokenResponse.getAccessToken()));

                /*
                 * Create new authentication(OAuth2AuthenticationToken).
                 */
                OAuth2AuthenticationToken updatedUser = new OAuth2AuthenticationToken(newOAuth2User, newOAuth2User.getAuthorities(), oldOAuth2Token.getAuthorizedClientRegistrationId());
                /*
                 * Update access_token and refresh_token by saving new authorized client.
                 */
                OAuth2AuthorizedClient updatedAuthorizedClient = new OAuth2AuthorizedClient(clientRegistration,
                    oldOAuth2Token.getName(), accessTokenResponse.getAccessToken(),
                    accessTokenResponse.getRefreshToken());
                this.oAuth2AuthorizedClientService.saveAuthorizedClient(updatedAuthorizedClient, updatedUser);
                /*
                 * Set new authentication in SecurityContextHolder.
                 */
                SecurityContextHolder.getContext().setAuthentication(updatedUser);

                Cookie tokenCookie = new Cookie("access_token", accessTokenResponse.getAccessToken().getTokenValue());
                tokenCookie.setHttpOnly(true);
                tokenCookie.setDomain(cookieDomain);
                tokenCookie.setPath("/");
                response.addCookie(tokenCookie);
                log.info("===================== Refresh Token Done !");
            } catch (OAuth2AuthorizationException e) {
                log.info("Refresh ExpiredToken exception", e);
                SecurityContextHolder.getContext().setAuthentication(null);
            }

        }

    }
    log.debug("exit Refresh ExpiredToken Filter......");
    filterChain.doFilter(request, response);
}