io.jsonwebtoken.Claims.setSubject()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(275)

本文整理了Java中io.jsonwebtoken.Claims.setSubject()方法的一些代码示例,展示了Claims.setSubject()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Claims.setSubject()方法的具体详情如下:
包路径:io.jsonwebtoken.Claims
类名称:Claims
方法名:setSubject

Claims.setSubject介绍

暂无

代码示例

代码示例来源:origin: jwtk/jjwt

@Override
public JwtParser requireSubject(String subject) {
  expectedClaims.setSubject(subject);
  return this;
}

代码示例来源:origin: jwtk/jjwt

@Override
public JwtBuilder setSubject(String sub) {
  if (Strings.hasText(sub)) {
    ensureClaims().setSubject(sub);
  } else {
    if (this.claims != null) {
      claims.setSubject(sub);
    }
  }
  return this;
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void refresh_token() {
 setSecretKey(A_SECRET_KEY);
 underTest.start();
 Date now = new Date();
 Date createdAt = DateUtils.parseDate("2016-01-01");
 // Expired in 10 minutes
 Date expiredAt = new Date(now.getTime() + 10 * 60 * 1000);
 Claims token = new DefaultClaims()
  .setId("id")
  .setSubject("subject")
  .setIssuer("sonarqube")
  .setIssuedAt(createdAt)
  .setExpiration(expiredAt);
 token.put("key", "value");
 // Refresh the token with a higher expiration time
 String encodedToken = underTest.refresh(token, 20 * 60);
 Claims result = underTest.decode(encodedToken).get();
 assertThat(result.getId()).isEqualTo("id");
 assertThat(result.getSubject()).isEqualTo("subject");
 assertThat(result.getIssuer()).isEqualTo("sonarqube");
 assertThat(result.getIssuedAt()).isEqualTo(createdAt);
 assertThat(result.get("key")).isEqualTo("value");
 // Expiration date has been changed
 assertThat(result.getExpiration()).isNotEqualTo(expiredAt)
  .isAfterOrEqualsTo(new Date(now.getTime() + 19 * 1000));
}

代码示例来源:origin: svlada/springboot-security-jwt

public JwtToken createRefreshToken(UserContext userContext) {
    if (StringUtils.isBlank(userContext.getUsername())) {
      throw new IllegalArgumentException("Cannot create JWT Token without username");
    }

    LocalDateTime currentTime = LocalDateTime.now();

    Claims claims = Jwts.claims().setSubject(userContext.getUsername());
    claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority()));
    
    String token = Jwts.builder()
     .setClaims(claims)
     .setIssuer(settings.getTokenIssuer())
     .setId(UUID.randomUUID().toString())
     .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
     .setExpiration(Date.from(currentTime
       .plusMinutes(settings.getRefreshTokenExpTime())
       .atZone(ZoneId.systemDefault()).toInstant()))
     .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
    .compact();

    return new AccessJwtToken(token, claims);
  }
}

代码示例来源:origin: svlada/springboot-security-jwt

/**
 * Factory method for issuing new JWT Tokens.
 * 
 * @param username
 * @param roles
 * @return
 */
public AccessJwtToken createAccessJwtToken(UserContext userContext) {
  if (StringUtils.isBlank(userContext.getUsername())) 
    throw new IllegalArgumentException("Cannot create JWT Token without username");
  if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty()) 
    throw new IllegalArgumentException("User doesn't have any privileges");
  Claims claims = Jwts.claims().setSubject(userContext.getUsername());
  claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
  LocalDateTime currentTime = LocalDateTime.now();
  
  String token = Jwts.builder()
   .setClaims(claims)
   .setIssuer(settings.getTokenIssuer())
   .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
   .setExpiration(Date.from(currentTime
     .plusMinutes(settings.getTokenExpirationTime())
     .atZone(ZoneId.systemDefault()).toInstant()))
   .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
  .compact();
  return new AccessJwtToken(token, claims);
}

代码示例来源:origin: io.jsonwebtoken/jjwt

@Override
public JwtParser requireSubject(String subject) {
  expectedClaims.setSubject(subject);
  return this;
}

代码示例来源:origin: io.jsonwebtoken/jjwt-impl

@Override
public JwtParser requireSubject(String subject) {
  expectedClaims.setSubject(subject);
  return this;
}

代码示例来源:origin: io.jsonwebtoken/jjwt

@Override
public JwtBuilder setSubject(String sub) {
  if (Strings.hasText(sub)) {
    ensureClaims().setSubject(sub);
  } else {
    if (this.claims != null) {
      claims.setSubject(sub);
    }
  }
  return this;
}

代码示例来源:origin: io.jsonwebtoken/jjwt-impl

@Override
public JwtBuilder setSubject(String sub) {
  if (Strings.hasText(sub)) {
    ensureClaims().setSubject(sub);
  } else {
    if (this.claims != null) {
      claims.setSubject(sub);
    }
  }
  return this;
}

代码示例来源:origin: murraco/spring-boot-jwt

public String createToken(String username, List<Role> roles) {
 Claims claims = Jwts.claims().setSubject(username);
 claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull).collect(Collectors.toList()));
 Date now = new Date();
 Date validity = new Date(now.getTime() + validityInMilliseconds);
 return Jwts.builder()//
   .setClaims(claims)//
   .setIssuedAt(now)//
   .setExpiration(validity)//
   .signWith(SignatureAlgorithm.HS256, secretKey)//
   .compact();
}

代码示例来源:origin: craftingjava/springuni-particles

@Override
public String createJwtToken(Authentication authentication, int minutes) {
 Claims claims = Jwts.claims()
   .setId(String.valueOf(IdentityGenerator.generate()))
   .setSubject(authentication.getName())
   .setExpiration(new Date(currentTimeMillis() + minutes * 60 * 1000))
   .setIssuedAt(new Date());
 String authorities = authentication.getAuthorities()
   .stream()
   .map(GrantedAuthority::getAuthority)
   .map(String::toUpperCase)
   .collect(Collectors.joining(","));
 claims.put(AUTHORITIES, authorities);
 return Jwts.builder()
   .setClaims(claims)
   .signWith(HS512, secretkey)
   .compact();
}

代码示例来源:origin: Jasig/uPortal

protected Claims createClaims(
    Class<? extends ITokenizable> clazz, String username, Date expires) {
  // Registered claims
  final Claims rslt =
      Jwts.claims()
          .setIssuer(JWT_ISSUER)
          .setSubject(username)
          .setExpiration(expires)
          .setIssuedAt(new Date())
          .setId(UUID.randomUUID().toString());
  // Deserialization class
  rslt.put(JwtClaims.CLASS.getName(), clazz.getName());
  return rslt;
}

代码示例来源:origin: hantsy/springboot-jwt-sample

public String createToken(String username, List<String> roles) {
  Claims claims = Jwts.claims().setSubject(username);
  claims.put("roles", roles);
  Date now = new Date();
  Date validity = new Date(now.getTime() + validityInMilliseconds);
  return Jwts.builder()//
    .setClaims(claims)//
    .setIssuedAt(now)//
    .setExpiration(validity)//
    .signWith(SignatureAlgorithm.HS256, secretKey)//
    .compact();
}

代码示例来源:origin: qaprosoft/zafira

/**
 * Generates JWT auth token storing id, username, email, roles of the user and specifies expiration date.
 * 
 * @param user
 *            - for token generation
 * @return generated JWT token
 */
public String generateAuthToken(final User user, final String tenant)
{
  Claims claims = Jwts.claims().setSubject(user.getId().toString());
  claims.put("username", user.getUsername());
  claims.put("groupIds", user.getGroups().stream().map(Group::getId).collect(Collectors.toList()));
  claims.put("tenant", tenant);
  return buildToken(claims, authTokenExp);
}

代码示例来源:origin: Apereo-Learning-Analytics-Initiative/OpenLRW

public JwtToken createRefreshToken(UserContext userContext) {
   if (StringUtils.isBlank(userContext.getTenantId())) 
    throw new IllegalArgumentException("Cannot create JWT Token without tenantId");

   if (StringUtils.isBlank(userContext.getOrgId())) 
    throw new IllegalArgumentException("Cannot create JWT Token without orgId");

    DateTime currentTime = new DateTime();

    Claims claims = Jwts.claims().setSubject(userContext.getOrgId());
    claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
    claims.put("tenant", userContext.getTenantId());
    
    String token = Jwts.builder()
     .setClaims(claims)
     .setIssuer(settings.getTokenIssuer())
     .setId(UUID.randomUUID().toString())
     .setIssuedAt(currentTime.toDate())
     .setExpiration(currentTime.plusMinutes(settings.getRefreshTokenExpTime()).toDate())
     .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey())
    .compact();

    return new AccessJwtToken(token, claims);
  }
}

代码示例来源:origin: craftingjava/springuni-particles

@Override
protected String encodeCookie(String[] cookieTokens) {
 Claims claims = Jwts.claims()
   .setId(cookieTokens[0])
   .setSubject(cookieTokens[1])
   .setExpiration(new Date(currentTimeMillis() + getTokenValiditySeconds() * 1000L))
   .setIssuedAt(new Date());
 return Jwts.builder()
   .setClaims(claims)
   .signWith(HS512, getKey())
   .compact();
}

代码示例来源:origin: qaprosoft/zafira

/**
 * Generates JWT refresh token storing id, username, password of the user and specifies expiration date.
 * 
 * @param user
 *            - for token refresh
 * @return generated JWT token
 */
public String generateRefreshToken(final User user, final String tenant)
{
  Claims claims = Jwts.claims().setSubject(user.getId().toString());
  claims.put("password", user.getPassword());
  claims.put("tenant", tenant);
  return buildToken(claims, refreshTokenExp);
}

代码示例来源:origin: qaprosoft/zafira

/**
 * Generates JWT access token storing id, password of the user and specifies expiration (that never expires).
 * 
 * @param user
 *            - for token generation
 * @return generated JWT token
 */
public String generateAccessToken(User user, String tenant)
{
  Claims claims = Jwts.claims().setSubject(user.getId().toString());
  claims.put("password", user.getPassword());
  claims.put("tenant", tenant);
  return buildToken(claims, Integer.MAX_VALUE);
}

代码示例来源:origin: BHRother/spring-boot-security-jwt

public static String generateToken(JwtUserDto u, String secret) {
    Claims claims = Jwts.claims().setSubject(u.getUsername());
    claims.put("role", u.getRole());

    return Jwts.builder()
        .setClaims(claims)
        .signWith(SignatureAlgorithm.HS512, secret)
        .setExpiration(DateTime.now().plusSeconds(30).toDate())
        .compact();
  }
}

代码示例来源:origin: TechPrimers/jwt-security-example

public String generate(JwtUser jwtUser) {

    Claims claims = Jwts.claims()
        .setSubject(jwtUser.getUserName());
    claims.put("userId", String.valueOf(jwtUser.getId()));
    claims.put("role", jwtUser.getRole());

    return Jwts.builder()
        .setClaims(claims)
        .signWith(SignatureAlgorithm.HS512, "youtube")
        .compact();
  }
}

相关文章