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

The following examples show how to use org.springframework.security.oauth2.core.user.DefaultOAuth2User. 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: GitLabOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 7 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitLabOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #2
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 #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: FacebookTokenStore.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public AccessToken loadSecurityToken(OAuth2AuthenticationToken authentication) {
    DefaultOAuth2User user = (DefaultOAuth2User) authentication.getPrincipal();
    String id = (String) user.getAttributes().get("id");

    Optional<FacebookAuth> facebookAuth = repository.findById(id);

    if (facebookAuth.isPresent()) {
        FacebookAuth auth = facebookAuth.get();
        return new AccessToken(AccessToken.TokenType.BEARER, id,
            Instant.ofEpochSecond(auth.getIssuedAt()),
            Instant.ofEpochSecond(auth.getExpirationTime()));
    }

    return null;
}
 
Example #5
Source File: RegistryOAuth2Provider.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the data from the authorized client
 */
default OAuth2User getOAuth2User(DefaultOAuth2User user, OAuth2AuthorizedClient client) {
    return new OAuth2User(
            client.getClientRegistration().getRegistrationId(),
            client.getAccessToken().getTokenValue(),
            user.getAttributes());
}
 
Example #6
Source File: GitHubOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitHubOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #7
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 #8
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 #9
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 #10
Source File: ProfileController.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@GetMapping("/form")
public ModelAndView form() {
    DefaultOAuth2User user = (DefaultOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Optional<FacebookAuth> facebookAuth = facebookAccountRepository.findById((String) user.getAttributes().get("id"));
    Optional<Profile> profile = profileRepository.findByUser(facebookAuth.get().getUser());

    ModelAndView mv = new ModelAndView("form");
    if (profile.isPresent()) {
        mv.addObject("profile", profile.get());
    } else {
        mv.addObject("profile", new Profile());
    }

    return mv;
}
 
Example #11
Source File: ProfileController.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@PostMapping
public ModelAndView save(Profile profile) {
    DefaultOAuth2User user = (DefaultOAuth2User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    Optional<FacebookAuth> facebookAuth = facebookAccountRepository.findById((String) user.getAttributes().get("id"));
    profile.setUser(facebookAuth.get().getUser());

    Profile newProfile = profileRepository.save(profile);
    ModelAndView mv = new ModelAndView("redirect:/profile");
    mv.addObject("profile", newProfile);
    return mv;
}
 
Example #12
Source File: FacebookTokenStore.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void saveSecurityToken(AccessToken securityToken, OAuth2AuthenticationToken authentication) {
    DefaultOAuth2User oAuth2User = (DefaultOAuth2User) authentication.getPrincipal();
    FacebookAuth facebookAuth = new FacebookAuth();
    facebookAuth.setUser(new User());
    facebookAuth.setId((String) oAuth2User.getAttributes().get("id"));
    facebookAuth.setExpirationTime(securityToken.getExpiresAt().getEpochSecond());
    facebookAuth.setIssuedAt(securityToken.getIssuedAt().getEpochSecond());

    repository.save(facebookAuth);
}
 
Example #13
Source File: FacebookTokenStore.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void removeSecurityToken(OAuth2AuthenticationToken authentication) {
    DefaultOAuth2User oAuth2User = (DefaultOAuth2User) authentication.getPrincipal();
    String id = (String) oAuth2User.getAttributes().get("id");
    Optional<FacebookAuth> facebookAuth = repository.findById(id);
    if (facebookAuth.isPresent()) {
        repository.delete(facebookAuth.get());
    }
}
 
Example #14
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;
    };
}