org.springframework.security.oauth2.core.user.OAuth2User Java Examples

The following examples show how to use org.springframework.security.oauth2.core.user.OAuth2User. 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 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 #3
Source File: AccountResourceIT.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void testGetExistingAccount() throws Exception {
    // create security-aware mockMvc
    restUserMockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

    Map<String, Object> userDetails = new HashMap<>();
    userDetails.put("sub", "test");
    userDetails.put("email", "[email protected]");
    Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, authorities, "oidc");
    TestSecurityContextHolder.getContext().setAuthentication(authentication);

    restUserMockMvc.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("test"))
        .andExpect(jsonPath("$.email").value("[email protected]"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #4
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 #5
Source File: PrincipalToRequestHeaderFilterFactory.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(final NameConfig config) {
    return (exchange, chain) -> exchange.getSession().
            flatMap(session -> Mono.justOrEmpty(Optional.ofNullable(
            cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(session.getId(), Session.class)).
            map(cachedSession -> {
                String principal = null;

                SecurityContext ctx = cachedSession.getAttribute(
                        WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME);
                if (ctx != null && ctx.getAuthentication() != null) {
                    if (ctx.getAuthentication().getPrincipal() instanceof OidcUser) {
                        principal = ((OidcUser) ctx.getAuthentication().getPrincipal()).
                                getIdToken().getTokenValue();
                    } else if (ctx.getAuthentication().getPrincipal() instanceof OAuth2User) {
                        principal = Objects.toString(((OAuth2User) ctx.getAuthentication().getPrincipal()).
                                getAttributes().get(StandardClaimNames.PREFERRED_USERNAME), null);
                    } else {
                        principal = ctx.getAuthentication().getName();
                    }
                }

                return principal;
            }))).
            transform(principal -> principal.flatMap(p -> StringUtils.isEmpty(p)
            ? chain.filter(exchange)
            : chain.filter(exchange.mutate().
                    request(exchange.getRequest().mutate().
                            headers(headers -> headers.add(config.getName(), p)).build()).
                    build()))).
            switchIfEmpty(chain.filter(exchange));
}
 
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: GitHubController.java    From blog-tutorials with MIT License 5 votes vote down vote up
@GetMapping
public String index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                    @AuthenticationPrincipal OAuth2User oauth2User,
                    Model model) {

    model.addAttribute("repositories", fetchAllRepositories(authorizedClient));
    model.addAttribute("username", oauth2User.getAttributes().get("login"));

    return "index";
}
 
Example #8
Source File: GitHubController.java    From blog-tutorials with MIT License 5 votes vote down vote up
@GetMapping
public String index(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                    @AuthenticationPrincipal OAuth2User oauth2User,
                    Model model) {

    model.addAttribute("repositories", fetchAllRepositories(authorizedClient));
    model.addAttribute("username", oauth2User.getAttributes().get("login"));

    return "index";
}
 
Example #9
Source File: OAuth2AuthenticationSuccessHandler.java    From jvue-admin with MIT License 5 votes vote down vote up
@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		super.onAuthenticationSuccess(request, response, authentication);
		// TODO 处理jvue用户绑定
//		logger.info("URI {}", request.getRequestURI());
//		request.getParameterMap().forEach((key, value) -> {
//			logger.info("param {} = {} ", key, value);
//		});
		
		String registrationId = null;
		String username = null;
		
		if (authentication instanceof OAuth2AuthenticationToken) {
			OAuth2AuthenticationToken oAuth2Authentication = (OAuth2AuthenticationToken)authentication;
			registrationId = oAuth2Authentication.getAuthorizedClientRegistrationId();
		} else {
			// registration取不到
			logger.warn("取不到 ClientRegistrationId");
			return;
		}
			
		
		if (authentication.getPrincipal() != null) {
			if (authentication.getPrincipal() instanceof OAuth2User) {
				OAuth2User oauth2User = (OAuth2User) authentication.getPrincipal();
				username = oauth2User.getName();
				
				// 这里可以根据不同的[registrationId]从[oauth2User.getAttributes()]里获取不同的用户数据
				// oauth2User.getAttributes()
			}
		}
		
		// save and update the principal
		logger.info("session {}", request.getSession());
		JwtUserDetails userDetails = userService.updateUser(registrationId, username);
		request.getSession(true).setAttribute("USER_INFO", userDetails);
	}
 
Example #10
Source File: TokenRelayGatewayFilterFactoryTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test
public void whenPrincipalExistsAuthorizationHeaderAdded() {
	OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
	when(accessToken.getTokenValue()).thenReturn("mytoken");

	ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("myregistrationid")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.clientId("myclientid").tokenUri("mytokenuri").build();
	OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
			clientRegistration, "joe", accessToken);

	when(repository.loadAuthorizedClient(anyString(),
			any(OAuth2AuthenticationToken.class), any(ServerWebExchange.class)))
					.thenReturn(Mono.just(authorizedClient));

	OAuth2AuthenticationToken authenticationToken = new OAuth2AuthenticationToken(
			mock(OAuth2User.class), Collections.emptyList(), "myId");
	SecurityContextImpl securityContext = new SecurityContextImpl(
			authenticationToken);
	SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange(
			mockExchange, Mono.just(securityContext));

	filter.filter(exchange, filterChain).block(TIMEOUT);

	assertThat(request.getHeaders()).containsEntry(HttpHeaders.AUTHORIZATION,
			Collections.singletonList("Bearer mytoken"));
}
 
Example #11
Source File: UserService.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
public OAuth2User getOAuth2Principal() {
    var authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        var principal = authentication.getPrincipal();
        if (principal instanceof OAuth2User) {
            return (OAuth2User) principal;
        }
    }
    return null;
}
 
Example #12
Source File: UserServiceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(Map<String, Object> userDetails) {
    Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Constants.ANONYMOUS_USER, Constants.ANONYMOUS_USER, authorities);
    usernamePasswordAuthenticationToken.setDetails(userDetails);
    OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");

    return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
 
Example #13
Source File: UserServiceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(Map<String, Object> userDetails) {
    Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Constants.ANONYMOUS_USER, Constants.ANONYMOUS_USER, authorities);
    usernamePasswordAuthenticationToken.setDetails(userDetails);
    OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");

    return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
 
Example #14
Source File: UserServiceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(Map<String, Object> userDetails) {
    Collection<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(Constants.ANONYMOUS_USER, Constants.ANONYMOUS_USER, authorities);
    usernamePasswordAuthenticationToken.setDetails(userDetails);
    OAuth2User user = new DefaultOAuth2User(authorities, userDetails, "sub");

    return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
 
Example #15
Source File: GatewayApplication.java    From spring-cloud-gateway-demo with Apache License 2.0 5 votes vote down vote up
@GetMapping("/")
public String index(Model model,
					@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
					@AuthenticationPrincipal OAuth2User oauth2User) {
	model.addAttribute("userName", oauth2User.getName());
	model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
	model.addAttribute("userAttributes", oauth2User.getAttributes());
	return "index";
}
 
Example #16
Source File: UserService.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
protected UserData updateGitHubUser(OAuth2User principal) {
    var user = repositories.findUserByProviderId("github", principal.getName());
    if (user == null) {
        user = new UserData();
        user.setProvider("github");
        user.setProviderId(principal.getName());
        user.setLoginName(principal.getAttribute("login"));
        user.setFullName(principal.getAttribute("name"));
        user.setEmail(principal.getAttribute("email"));
        user.setProviderUrl(principal.getAttribute("html_url"));
        user.setAvatarUrl(principal.getAttribute("avatar_url"));
        entityManager.persist(user);
    } else {
        String loginName = principal.getAttribute("login");
        if (loginName != null && !loginName.equals(user.getLoginName()))
            user.setLoginName(loginName);
        String fullName = principal.getAttribute("name");
        if (fullName != null && !fullName.equals(user.getFullName()))
            user.setFullName(fullName);
        String email = principal.getAttribute("email");
        if (email != null && !email.equals(user.getEmail()))
            user.setEmail(email);
        String providerUrl = principal.getAttribute("html_url");
        if (providerUrl != null && !providerUrl.equals(user.getProviderUrl()))
            user.setProviderUrl(providerUrl);
        String avatarUrl = principal.getAttribute("avatar_url");
        if (avatarUrl != null && !avatarUrl.equals(user.getAvatarUrl()))
            user.setAvatarUrl(avatarUrl);
    }
    return user;
}
 
Example #17
Source File: UserService.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
public UserData updateUser(OAuth2User principal) {
    String url = principal.getAttribute("url");
    if (url != null && url.startsWith(GITHUB_API)) {
        return updateGitHubUser(principal);
    }
    throw new IllegalArgumentException("Unsupported principal: " + principal.getName());
}
 
Example #18
Source File: MainController.java    From tutorials with MIT License 4 votes vote down vote up
@GetMapping("/")
public Mono<String> index(@AuthenticationPrincipal Mono<OAuth2User> oauth2User) {
   return oauth2User
    .map(OAuth2User::getName)
    .map(name -> String.format("Hi, %s", name));
}
 
Example #19
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);
}
 
Example #20
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 #21
Source File: HelloController.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
@GetMapping
public Mono<String> hello(@AuthenticationPrincipal OAuth2User oauth2User) {
    return Mono.just("Hello, " + oauth2User.getAttributes().get("name") + "!");
}