io.jsonwebtoken.Claims#get ( )源码实例Demo

下面列出了io.jsonwebtoken.Claims#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: trellis   文件: OAuthUtils.java
/**
 * Generate a Principal from a subject claim.
 * @param claims the JWT claims
 * @return a Principal, if one can be generated from standard claims
 */
public static Principal withSubjectClaim(final Claims claims) {
    final String subject = claims.getSubject();
    if (subject == null) return null;
    if (isUrl(subject)) {
        LOGGER.debug("Using JWT claim with sub: {}", subject);
        return new OAuthPrincipal(subject);
    }

    final String iss = claims.getIssuer();
    // combine the iss and sub fields if that appears possible
    if (iss != null && isUrl(iss)) {
        final String webid = iss.endsWith("/") ? iss + subject : iss + "/" + subject;
        LOGGER.debug("Using JWT claim with generated webid: {}", webid);
        return new OAuthPrincipal(webid);
    }

    // Use an OIDC website claim, if one exists
    if (claims.containsKey(WEBSITE)) {
        final String site = claims.get(WEBSITE, String.class);
        LOGGER.debug("Using JWT claim with website: {}", site);
        return new OAuthPrincipal(site);
    }
    return null;
}
 
源代码2 项目: hauth-java   文件: JwtService.java
public static RequestUserDTO getConnUser(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token == null) {
        token = getTokenFromCookis(request);
    }
    if (token != null) {
        // 解析 Token
        Claims claims = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token).getBody();

        return new RequestUserDTO(
                claims.get("DomainId", String.class),
                claims.get("UserId", String.class),
                claims.get("OrgUnitId", String.class));
    }
    return new RequestUserDTO();
}
 
源代码3 项目: iotplatform   文件: JwtTokenFactory.java
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
  Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
  Claims claims = jwsClaims.getBody();
  String subject = claims.getSubject();
  List<String> scopes = claims.get(SCOPES, List.class);
  if (scopes == null || scopes.isEmpty()) {
    throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
  }
  if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
    throw new IllegalArgumentException("Invalid Refresh Token scope");
  }
  boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
  UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME,
      subject);
  SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
  securityUser.setUserPrincipal(principal);
  return securityUser;
}
 
源代码4 项目: Groza   文件: JwtTokenFactory.java
public SecurityUser parseRefreshToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("Refresh Token doesn't have any scopes");
    }
    if (!scopes.get(0).equals(Authority.REFRESH_TOKEN.name())) {
        throw new IllegalArgumentException("Invalid Refresh Token scope");
    }
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    SecurityUser securityUser = new SecurityUser(new UserId(UUID.fromString(claims.get(USER_ID, String.class))));
    securityUser.setUserPrincipal(principal);
    return securityUser;
}
 
源代码5 项目: api-layer   文件: AuthenticationService.java
/**
 * Parses the JWT token and return a {@link QueryResponse} object containing the domain, user id, type (Zowe / z/OSMF),
 * date of creation and date of expiration
 *
 * @param jwtToken the JWT token
 * @return the query response
 */
public QueryResponse parseJwtToken(String jwtToken) {
    /*
     * Removes signature, because of z/OSMF we don't have key to verify certificate and
     * we just need to read claim. Verification is realized via REST call to z/OSMF.
     * JWT library doesn't parse signed key without verification.
     */
    final String withoutSign = removeSign(jwtToken);

    // parse to claims and construct QueryResponse
    try {
        Claims claims = Jwts.parser()
            .parseClaimsJwt(withoutSign)
            .getBody();
        return new QueryResponse(
            claims.get(DOMAIN_CLAIM_NAME, String.class),
            claims.getSubject(),
            claims.getIssuedAt(),
            claims.getExpiration(),
            QueryResponse.Source.valueByIssuer(claims.getIssuer())
        );
    } catch (RuntimeException exception) {
        throw handleJwtParserException(exception);
    }
}
 
源代码6 项目: common-project   文件: JwtUtils.java
/**
 * 解析token
 *
 * @param token
 * @return
 * @throws Exception
 */
public static AuthTokenDetails parseToken(String token) throws Exception {
    Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    String userId = claims.getSubject();
    String appId = (String) claims.get(APP_ID_FIELD);
    String organizationId = (String) claims.get(ORGANIZATION_ID_FIELD);
    String roleId = (String) claims.get(ROLE_ID_FIELD);
    String roleType = (String) claims.get(ROLE_TYPE_FIELD);
    String language = (String) claims.get(LANGUAGE_FIELD);
    Date expirationDate = claims.getExpiration();

    AuthTokenDetails authTokenDetails = new AuthTokenDetails();
    authTokenDetails.setUserId(Long.valueOf(userId));
    authTokenDetails.setAppId(appId);
    authTokenDetails.setOrganizationId(Long.valueOf(organizationId));
    authTokenDetails.setRoleId(roleId == null ? null : Long.valueOf(roleId));
    authTokenDetails.setRoleType(RoleTypeEnum.valueOf(roleType));
    authTokenDetails.setExpirationDate(expirationDate);
    authTokenDetails.setLanguage(language);
    return authTokenDetails;
}
 
源代码7 项目: kisso   文件: SSOToken.java
public static SSOToken parser(String jwtToken, boolean header) {
    Claims claims = JwtHelper.verifyParser().parseClaimsJws(jwtToken).getBody();
    if (null == claims) {
        return null;
    }
    String origin = claims.get(SSOConstants.TOKEN_ORIGIN, String.class);
    if (header && StringUtils.isEmpty(origin)) {
        log.warn("illegal token request orgin.");
        return null;
    }
    SSOToken ssoToken = new SSOToken();
    ssoToken.setId(claims.getId());
    ssoToken.setIssuer(claims.getIssuer());
    String ip = claims.get(SSOConstants.TOKEN_USER_IP, String.class);
    if (StringUtils.isNotEmpty(ip)) {
        ssoToken.setIp(ip);
    }
    String userAgent = claims.get(SSOConstants.TOKEN_USER_AGENT, String.class);
    if (StringUtils.isNotEmpty(userAgent)) {
        ssoToken.setUserAgent(userAgent);
    }
    String flag = claims.get(SSOConstants.TOKEN_FLAG, String.class);
    if (StringUtils.isNotEmpty(flag)) {
        ssoToken.setFlag(TokenFlag.fromValue(flag));
    }
    String tenantId = claims.get(SSOConstants.TOKEN_TENANT_ID, String.class);
    if (StringUtils.isNotEmpty(tenantId)) {
        ssoToken.setTenantId(tenantId);
    }
    // TOKEN 来源
    if (StringUtils.isNotEmpty(origin)) {
        ssoToken.setOrigin(TokenOrigin.fromValue(origin));
    }
    ssoToken.setTime(claims.getIssuedAt().getTime());
    ssoToken.setClaims(claims);
    return ssoToken;
}
 
@SuppressWarnings("unchecked")
  protected String[] extractRoles(final Claims claims, final RestRequest request) {
  	// no roles key specified
  	if(rolesKey == null) {
  		return new String[0];
  	}
// try to get roles from claims, first as Object to avoid having to catch the ExpectedTypeException
  	final Object rolesObject = claims.get(rolesKey, Object.class);
  	if(rolesObject == null) {
  		log.warn("Failed to get roles from JWT claims with roles_key '{}'. Check if this key is correct and available in the JWT payload.", rolesKey);
  		return new String[0];
  	}

  	String[] roles = String.valueOf(rolesObject).split(",");

  	// We expect a String or Collection. If we find something else, convert to String but issue a warning
  	if (!(rolesObject instanceof String) && !(rolesObject instanceof Collection<?>)) {
  		log.warn("Expected type String or Collection for roles in the JWT for roles_key {}, but value was '{}' ({}). Will convert this value to String.", rolesKey, rolesObject, rolesObject.getClass());
} else if (rolesObject instanceof Collection<?>) {
    roles = ((Collection<String>) rolesObject).toArray(new String[0]);
}

  	for (int i = 0; i < roles.length; i++) {
  	    roles[i] = roles[i].trim();
  	}

  	return roles;
  }
 
源代码9 项目: light-security   文件: ReactiveUserOperator.java
/**
 * 解析token,获得用户信息
 *
 * @param token token
 * @return 用户信息
 */
@SuppressWarnings("unchecked")
private User getUserFromToken(String token) {
    // 从token中获取user
    Claims claims = jwtOperator.getClaimsFromToken(token);
    Object roles = claims.get(JwtOperator.ROLES);
    Object userId = claims.get(JwtOperator.USER_ID);
    Object username = claims.get(JwtOperator.USERNAME);

    return User.builder()
            .id((Integer) userId)
            .username((String) username)
            .roles((List<String>) roles)
            .build();
}
 
private LinkedHashMap<String, Object> getPayloadMap(String jwtToken) {
    Claims claims = Jwts.parser()
            .setSigningKey(jwtSecretService.getJwtSecret())
            .parseClaimsJws(jwtToken)
            .getBody();
    return (LinkedHashMap<String, Object>) claims.get(JWT_CLAIM_KEY);
}
 
源代码11 项目: IOT-Technical-Guide   文件: JwtTokenFactory.java
public SecurityUser parseAccessJwtToken(RawAccessJwtToken rawAccessToken) {
    Jws<Claims> jwsClaims = rawAccessToken.parseClaims(settings.getTokenSigningKey());
    Claims claims = jwsClaims.getBody();
    String subject = claims.getSubject();
    List<String> scopes = claims.get(SCOPES, List.class);
    if (scopes == null || scopes.isEmpty()) {
        throw new IllegalArgumentException("JWT Token doesn't have any scopes");
    }

    SecurityUser securityUser = new SecurityUser();
    securityUser.setEmail(subject);
    securityUser.setAuthority(Authority.parse(scopes.get(0)));
    securityUser.setEnabled(claims.get(ENABLED, Boolean.class));
    boolean isPublic = claims.get(IS_PUBLIC, Boolean.class);
    UserPrincipal principal = new UserPrincipal(isPublic ? UserPrincipal.Type.PUBLIC_ID : UserPrincipal.Type.USER_NAME, subject);
    securityUser.setUserPrincipal(principal);
    String tenantId = claims.get(TENANT_ID, String.class);
    if (tenantId != null) {
        securityUser.setTenantId(1l);
    }
    String customerId = claims.get(CUSTOMER_ID, String.class);
    if (customerId != null) {
        securityUser.setCustomerId(1L);
    }

    return securityUser;
}
 
源代码12 项目: SuperBoot   文件: JWT_Utils.java
/**
 * 获取用户名
 *
 * @param token TOKEN信息
 * @return
 */
public String getUsernameFromToken(String token) {
    String username;
    try {
        Claims claims = getClaimsFromToken(token);
        username = (String) claims.get(CLAIM_KEY_USERNAME);
    } catch (Exception e) {
        throw new BaseException(StatusCode.TOKEN_INVALID);
    }
    return username;
}
 
源代码13 项目: line-sdk-android   文件: IdTokenParser.java
private static LineIdToken.Address buildAddress(final Claims claims) {
    final Map<String, String> addressClaims = claims.get("address", Map.class);

    if (addressClaims == null) {
        return null;
    }

    return new LineIdToken.Address.Builder()
            .streetAddress(addressClaims.get("street_address"))
            .locality(addressClaims.get("locality"))
            .region(addressClaims.get("region"))
            .postalCode(addressClaims.get("postal_code"))
            .country(addressClaims.get("country"))
            .build();
}
 
源代码14 项目: scava   文件: JwtTokenAuthenticationFilter.java
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain)
		throws ServletException, IOException {
	rsp.addHeader("Access-Control-Allow-Origin", "*");
	rsp.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
	rsp.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Authorization");
	rsp.addHeader("Access-Control-Allow-Methods", "GET");
	rsp.addHeader("Access-Control-Allow-Methods", "POST");
	rsp.addHeader("Access-Control-Allow-Methods", "PUT");
	rsp.addHeader("Access-Control-Allow-Methods", "DELETE");
	String token = req.getHeader(config.getHeader());
	if(req.getMethod().equals("OPTIONS")) {
       	rsp.setStatus(HttpServletResponse.SC_OK);
       } else {
       	if (token != null && token.startsWith(config.getPrefix() + " ")) {
   			token = token.replace(config.getPrefix() + " ", "");
   			try {
   				Claims claims = Jwts.parser().setSigningKey(config.getSecret().getBytes()).parseClaimsJws(token)
   						.getBody();
   				String username = claims.getSubject();
   				@SuppressWarnings("unchecked")
   				List<String> authorities = claims.get("authorities", List.class);
   				if (username != null) {
   					UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null,
   							authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
   					SecurityContextHolder.getContext().setAuthentication(auth);
   				}
   			} catch (Exception ignore) {
   				SecurityContextHolder.clearContext();
   			}
   		}
   		filterChain.doFilter(req, rsp);
       }
}
 
protected void validateTokenType(Claims claims) {
    String tokenType = claims.get(ApplicationConstants.JwtInfo.CLAIM_KEY_TYPE, String.class);
    if (!ApplicationConstants.JwtInfo.TOKEN_TYPE_REFRESH.equals(tokenType)) {
        log.error("such token type [{}] is not expected.", tokenType);
        throw new BadCredentialsException("bad refresh token type.");
    }
}
 
源代码16 项目: Milkomeda   文件: Crust.java
/**
 * 根据请求令牌获取登录认证信息
 *
 * @return Authentication
 */
Authentication getAuthenticationFromToken() {
    Authentication authentication = null;
    // 获取请求携带的令牌
    String token = getToken();
    if (token != null) {
        // 当前上下文认证信息不存在
        if (getAuthentication() == null) {
            String unSignKey = getUnSignKey();
            Claims claims = JwtUtil.parseToken(token, unSignKey);
            if (claims == null) {
                return null;
            }
            String username = claims.getSubject();
            if (username == null) {
                return null;
            }
            if (JwtUtil.isTokenExpired(token, unSignKey)) {
                return null;
            }
            String uid = (String) claims.get(UID);
            long issuedAt = (long) claims.get(CREATED);
            long expire = claims.getExpiration().getTime();
            // 设置Token元数据
            CrustTokenMetaData tokenMetaData = new CrustTokenMetaData(username, uid, issuedAt, expire);
            tokenMetaDataThreadLocal.set(tokenMetaData);
            Object RoleIdsObj = claims.get(ROLE_IDS);
            List<Long> roleIds = null;
            if (RoleIdsObj != null) {
                roleIds = Arrays.stream(((String) RoleIdsObj).split(",")).map(Long::parseLong).collect(Collectors.toList());
            }
            List<String> authoritiesList = getCrustUserDetailsService().findAuthorities(uid);
            List<GrantedAuthority> authorities = null;
            if (authoritiesList != null) {
                authorities = authoritiesList.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
            }
            CrustUserDetails userDetails = new CrustUserDetails(uid, username, authorities, roleIds);
            authentication = new CrustAuthenticationToken(userDetails, null, authorities, token);
        } else {
            // 当前上下文认证信息存在,验证token是否正确匹配
            if (validateToken(token, getUsername())) {
                // 如果上下文中Authentication非空,且请求令牌合法,直接返回当前登录认证信息
                authentication = getAuthentication();
            }
        }
    }
    return authentication;
}
 
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
		throws ServletException, IOException {
	
	// 1. get the authentication header. Tokens are supposed to be passed in the authentication header
	String header = request.getHeader(jwtConfig.getHeader());
	
	// 2. validate the header and check the prefix
	if(header == null || !header.startsWith(jwtConfig.getPrefix())) {
		chain.doFilter(request, response);  		// If not valid, go to the next filter.
		return;
	}
	
	// If there is no token provided and hence the user won't be authenticated. 
	// It's Ok. Maybe the user accessing a public path or asking for a token.
	
	// All secured paths that needs a token are already defined and secured in config class.
	// And If user tried to access without access token, then he won't be authenticated and an exception will be thrown.
	
	// 3. Get the token
	String token = header.replace(jwtConfig.getPrefix(), "");
	
	try {	// exceptions might be thrown in creating the claims if for example the token is expired
		
		// 4. Validate the token
		Claims claims = Jwts.parser()
				.setSigningKey(jwtConfig.getSecret().getBytes())
				.parseClaimsJws(token)
				.getBody();
		
		String username = claims.getSubject();
		if(username != null) {
			@SuppressWarnings("unchecked")
			List<String> authorities = (List<String>) claims.get("authorities");
			
			// 5. Create auth object
			// UsernamePasswordAuthenticationToken: A built-in object, used by spring to represent the current authenticated / being authenticated user.
			// It needs a list of authorities, which has type of GrantedAuthority interface, where SimpleGrantedAuthority is an implementation of that interface
			 UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
							 username, null, authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
			 
			 // 6. Authenticate the user
			 // Now, user is authenticated
			 SecurityContextHolder.getContext().setAuthentication(auth);
		}
		
	} catch (Exception e) {
		// In case of failure. Make sure it's clear; so guarantee user won't be authenticated
		SecurityContextHolder.clearContext();
	}
	
	// go to the next filter in the filter chain
	chain.doFilter(request, response);
}
 
源代码18 项目: poseidon   文件: JwtTokenAuthenticationFilter.java
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request,
		@NonNull HttpServletResponse response, @NonNull FilterChain chain)
		throws ServletException, IOException {
	// 1. get the authentication header. Tokens are supposed to be passed in the
	// authentication header

	if (request.getMethod().equals("OPTIONS")) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST,GET,PUT,OPTIONS,DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers",
				"Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
		return;
	}
	String header = request.getHeader(jwtConfig.getHeader());

	// 2. validate the header and check the prefix
	if (header == null || !header.startsWith(jwtConfig.getPrefix())) {
		chain.doFilter(request, response); // If not valid, go to the next filter.
		return;
	}

	// If there is no token provided and hence the user won't be authenticated.
	// It's Ok. Maybe the user accessing a public path or asking for a token.

	// All secured paths that needs a token are already defined and secured in config
	// class.
	// And If user tried to access without access token, then he won't be
	// authenticated and an exception will be thrown.

	// 3. Get the token
	String token = header.replace(jwtConfig.getPrefix(), "");

	try { // exceptions might be thrown in creating the claims if for example the
			// token is expired

		// 4. Validate the token
		Claims claims = Jwts.parser().setSigningKey(jwtConfig.getSecret().getBytes())
				.parseClaimsJws(token).getBody();

		String username = claims.getSubject();
		if (username != null) {
			@SuppressWarnings("unchecked")
			List<String> authorities = (List<String>) claims.get("authorities");

			// 5. Create auth object
			// UsernamePasswordAuthenticationToken: A built-in object, used by spring
			// to represent the current authenticated / being authenticated user.
			// It needs a list of authorities, which has type of GrantedAuthority
			// interface, where SimpleGrantedAuthority is an implementation of that
			// interface
			UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
					username, null,
					authorities.stream().map(SimpleGrantedAuthority::new)
							.collect(Collectors.toList()));

			// 6. Authenticate the user
			// Now, user is authenticated
			SecurityContextHolder.getContext().setAuthentication(auth);
		}

	}
	catch (Exception e) {
		// In case of failure. Make sure it's clear; so guarantee user won't be
		// authenticated
		SecurityContextHolder.clearContext();
	}

	// go to the next filter in the filter chain
	chain.doFilter(request, response);
}
 
源代码19 项目: sanshanblog   文件: JWTHelper.java
/**
 * 获取token中的用户信息
 *
 * @param token
 * @param pubKeyPath
 * @return
 * @throws Exception
 */
public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
    Claims body = claimsJws.getBody();
    return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(UserInfoConstance.JWT_KEY_USER_ID)),body.get(UserInfoConstance.JWT_KEY_CREATED,Date.class));
}
 
源代码20 项目: sanshanblog   文件: JWTHelper.java
/**
 * 获取token中的用户信息
 *
 * @param token
 * @param pubKey
 * @return
 * @throws Exception
 */
public static IJWTInfo getInfoFromToken(String token, byte[] pubKey) throws Exception {
    Jws<Claims> claimsJws = parserToken(token, pubKey);
    Claims body = claimsJws.getBody();
    return new JWTInfo(body.getSubject(), StringHelper.getObjectValue(body.get(UserInfoConstance.JWT_KEY_USER_ID)),body.get(UserInfoConstance.JWT_KEY_CREATED,Date.class));
}