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

The following examples show how to use org.springframework.security.oauth2.provider.OAuth2Authentication#getPrincipal() . 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: MyInfoAPI.java    From springboot-seed with 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 3
Source File: OpenTokenEnhancer.java    From open-cloud with MIT License 6 votes vote down vote up
/**
 * 生成token
 *
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
    final Map<String, Object> additionalInfo = new HashMap<>(8);
    if (!authentication.isClientOnly()) {
        if (authentication.getPrincipal() != null && authentication.getPrincipal() instanceof OpenUserDetails) {
            // 设置额外用户信息
            OpenUserDetails baseUser = ((OpenUserDetails) authentication.getPrincipal());
            additionalInfo.put(OpenSecurityConstants.OPEN_ID, baseUser.getUserId());
            additionalInfo.put(OpenSecurityConstants.DOMAIN, baseUser.getDomain());
        }
    }
    defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo);
    return super.enhance(defaultOAuth2AccessToken, authentication);
}
 
Example 4
Source File: JwtTokenEnhancer.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    // 给/oauth/token接口加属性roles,author
    JSONObject jsonObject = new JSONObject(authentication.getPrincipal());
    List<Object> authorities = jsonObject.getJSONArray("authorities").toList();
    StringBuilder stringBuilder = new StringBuilder();
    for (Object authority : authorities) {
        Map map = (Map) authority;
        stringBuilder.append(map.get("authority"));
        stringBuilder.append(",");
    }
    String roles = stringBuilder.toString();
    additionalInfo.put("roles", roles.substring(0, roles.length() - 1));
    additionalInfo.put("author", "sophia");
    // additionalInfo.put("createTime", df.format(LocalDateTime.now()));
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example 5
Source File: JwtTokenEnhancer.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    // 给/oauth/token接口加属性roles,author
    String roles = "";
    if (authentication.getAuthorities().size() > 0) {
        JSONObject jsonObject = new JSONObject(authentication.getPrincipal());
        List<Object> authorities = jsonObject.getJSONArray("authorities").toList();
        StringBuilder stringBuilder = new StringBuilder();
        for (Object authority : authorities) {
            Map map = (Map) authority;
            stringBuilder.append(map.get("authority"));
            stringBuilder.append(",");
        }
        roles = stringBuilder.toString();
    }
    if (StringUtils.isNotBlank(roles)) {
        additionalInfo.put("roles", roles.substring(0, roles.length() - 1));
    }
    additionalInfo.put("author", "sophia");
    additionalInfo.put("createTime", df.format(LocalDateTime.now()));
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}
 
Example 6
Source File: AdditionalClaimsTokenEnhancer.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(
    OAuth2AccessToken accessToken,
    OAuth2Authentication authentication) {

    Map<String, Object> additional = new HashMap<>();

    ResourceOwnerUserDetails user = (ResourceOwnerUserDetails)
        authentication.getPrincipal();
    additional.put("email", user.getEmail());

    DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
    token.setAdditionalInformation(additional);

    return accessToken;
}
 
Example 7
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 8
Source File: OpenApiTokenEnhancer.java    From spring-oauth2-jwt-jdbc with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    JwtAuthenticatedProfile user = (JwtAuthenticatedProfile) authentication.getPrincipal();
    final Map<String, Object> additionalInfo = new HashMap<>();

    additionalInfo.put("id_token", UUID.randomUUID().toString());

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

    return accessToken;
}
 
Example 9
Source File: CustomTokenEnhancer.java    From microservice-integration with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken,
                                 OAuth2Authentication authentication) {
    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
    authentication.getUserAuthentication().getPrincipal();
    Map<String, Object> info = new HashMap<>();
    info.put(TOKEN_SEG_USER_ID, userDetails.getUserId());

    DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);
    customAccessToken.setAdditionalInformation(info);

    OAuth2AccessToken enhancedToken = super.enhance(customAccessToken, authentication);
    enhancedToken.getAdditionalInformation().put(TOKEN_SEG_CLIENT, userDetails.getClientId());
    return enhancedToken;
}
 
Example 10
Source File: AuthorizationConfig.java    From Using-Spring-Oauth2-to-secure-REST with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    OAuth2AccessToken token = super.createAccessToken(authentication);
    Account account = (Account) authentication.getPrincipal();
    String jti = (String) token.getAdditionalInformation().get("jti");

    blackListService.addToEnabledList(
            account.getId(),
            jti,
            token.getExpiration().getTime() );
    return token;
}
 
Example 11
Source File: CustomTokenEnhancer.java    From springboot-seed with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    Map<String, Object> additionalInfo = new HashMap<>();
    SecurityUser user = (SecurityUser)authentication.getPrincipal();
    additionalInfo.put("detail", user);

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

    return accessToken;
}
 
Example 12
Source File: OpenJwtAccessTokenEnhancer.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 生成token
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
    if(authentication.getPrincipal()!=null && authentication.getPrincipal() instanceof OpenUserDetails){
        // 设置额外用户信息
        OpenUserDetails baseUser = ((OpenUserDetails) authentication.getPrincipal());
        final Map<String, Object> additionalInfo = new HashMap<>(8);
        additionalInfo.put(OpenSecurityConstants.OPEN_ID, baseUser.getUserId());
        additionalInfo.put(OpenSecurityConstants.DOMAIN, baseUser.getDomain());
        defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo);
    }

    return super.enhance(defaultOAuth2AccessToken, authentication);
}
 
Example 13
Source File: CustomJwtAccessTokenConverter.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * token增强器
 *
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (accessToken instanceof DefaultOAuth2AccessToken) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof PrexSecurityUser) {
            PrexSecurityUser user = (PrexSecurityUser) principal;
            HashMap<String, Object> map = new HashMap<>();
            map.put(USERNAME, user.getUsername());
            map.put("userId", user.getUserId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        }
    }
    return super.enhance(accessToken, authentication);
}
 
Example 14
Source File: CustomJwtAccessTokenConverter.java    From spring-security with Apache License 2.0 5 votes vote down vote up
/**
 * token增强器
 *
 * @param accessToken
 * @param authentication
 * @return
 */
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (accessToken instanceof DefaultOAuth2AccessToken) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof PrexSecurityUser) {
            PrexSecurityUser user = (PrexSecurityUser) principal;
            HashMap<String, Object> map = new HashMap<>();
            map.put(USERNAME, user.getUsername());
            map.put("userId", user.getUserId());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        }
    }
    return super.enhance(accessToken, authentication);
}
 
Example 15
Source File: OAuth2TokenDAO.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void storeAccessToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    Connection conn = null;
    PreparedStatement stat = null;
    try {
        conn = this.getConnection();
        String tokenValue = accessToken.getValue();
        if (null != this.getAccessToken(tokenValue, conn)) {
            logger.debug("storeAccessToken: Stored Token already exists");
            return;
        }
        conn.setAutoCommit(false);
        stat = conn.prepareStatement(INSERT_TOKEN);
        stat.setString(1, accessToken.getValue());
        if (accessToken instanceof OAuth2AccessTokenImpl) {
            stat.setString(2, ((OAuth2AccessTokenImpl) accessToken).getClientId());
        } else if (null != authentication.getOAuth2Request()) {
            stat.setString(2, authentication.getOAuth2Request().getClientId());
        } else {
            stat.setNull(2, Types.VARCHAR);
        }
        stat.setTimestamp(3, new Timestamp(accessToken.getExpiration().getTime()));
        stat.setString(4, accessToken.getRefreshToken().getValue());
        if (accessToken instanceof OAuth2AccessTokenImpl) {
            stat.setString(5, ((OAuth2AccessTokenImpl) accessToken).getGrantType());
            stat.setString(6, ((OAuth2AccessTokenImpl) accessToken).getLocalUser());
        } else {
            if (null != authentication.getOAuth2Request()) {
                stat.setString(5, authentication.getOAuth2Request().getGrantType());
            } else {
                stat.setNull(5, Types.VARCHAR);
            }
            if (authentication.getPrincipal() instanceof UserDetails) {
                stat.setString(6, ((UserDetails) authentication.getPrincipal()).getUsername());
            } else {
                stat.setString(6, authentication.getPrincipal().toString());
            }
        }
        stat.executeUpdate();
        conn.commit();
    } catch (Exception t) {
        this.executeRollback(conn);
        logger.error("Error while adding an access token", t);
        throw new RuntimeException("Error while adding an access token", t);
    } finally {
        closeDaoResources(null, stat, conn);
    }
}
 
Example 16
Source File: ResSvrApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@CrossOrigin
@GetMapping("/hello")
public String hello(OAuth2Authentication oauth) {
	return "hello " + oauth.getPrincipal();
}
 
Example 17
Source File: ResSvrApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@GetMapping("/hello")
public String hello(OAuth2Authentication oauth) {
	return "hello " + oauth.getPrincipal();
}
 
Example 18
Source File: ResSvrApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@GetMapping("/hello")
public String hello(OAuth2Authentication oauth) {
	return "hello " + oauth.getPrincipal();
}
 
Example 19
Source File: OAuth2Configuration.java    From spring-boot-oauth2-jwt with MIT License 4 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
	User user = (User) authentication.getPrincipal();

	Map<String, Object> info = new LinkedHashMap<String, Object>(accessToken.getAdditionalInformation());

	info.put("email", user.getEmail());

	DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);

	// Get the authorities from the user
	Set<GrantedAuthority> authoritiesSet = new HashSet<>(authentication.getAuthorities());

	// Generate String array
	String[] authorities = new String[authoritiesSet.size()];

	int i = 0;
	for (GrantedAuthority authority : authoritiesSet)
		authorities[i++] = authority.getAuthority();

	info.put("authorities", authorities);
	customAccessToken.setAdditionalInformation(info);

	return super.enhance(customAccessToken, authentication);
}
 
Example 20
Source File: OAuth2Configuration.java    From spring-boot-2-oauth2-authorization-jwt with MIT License 3 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
	User user = (User) authentication.getPrincipal();

	Map<String, Object> info = new LinkedHashMap<String, Object>(accessToken.getAdditionalInformation());

	info.put("email", user.getEmail());

	DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);
	customAccessToken.setAdditionalInformation(info);

	return super.enhance(customAccessToken, authentication);
}