当前位置: 首页>>代码示例>>Java>>正文


Java JwtBuilder类代码示例

本文整理汇总了Java中io.jsonwebtoken.JwtBuilder的典型用法代码示例。如果您正苦于以下问题:Java JwtBuilder类的具体用法?Java JwtBuilder怎么用?Java JwtBuilder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


JwtBuilder类属于io.jsonwebtoken包,在下文中一共展示了JwtBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: Gerate

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
public static String Gerate(String issuer, int idSubject, int hours) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        
        //Hours to milliseconds
        long ttlMillis = hours * 3600000;
        String subject = String.valueOf(idSubject);
        
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        
        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setIssuedAt(now)
                                    .setSubject(subject)
                                    .setIssuer(issuer)
                                    .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }
 
开发者ID:Montanheiro,项目名称:SistemaAlmoxarifado,代码行数:33,代码来源:Token.java

示例2: generate

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
@Override
public TokenDto generate(final String username, final String password) {
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new BadCredentialsException("Input data can't be empty.");
    }
    final User user = userService.findByUsername(username);

    validateInputPassword(user.getPassword(), password);

    final Map<String, Object> tokenData = new HashMap<>();
    tokenData.put("username", user.getUsername());
    tokenData.put("password", user.getPassword());
    tokenData.put("create_date", LocalDateTime.now());
    final JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setClaims(tokenData);
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, expirationTime);
    jwtBuilder.setExpiration(calendar.getTime());
    final String token = jwtBuilder.signWith(SignatureAlgorithm.HS512, secretKey).compact();
    return new TokenDto(token, mapper.map(user, UserDto.class));
}
 
开发者ID:akraskovski,项目名称:product-management-system,代码行数:22,代码来源:JwtService.java

示例3: createJWT

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/**
 * 创建jwt
 * @param id
 * @param subject
 * @param ttlMillis
 * @return
 * @throws Exception
 */
public String createJWT(String id, String subject, long ttlMillis) throws Exception {

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = generalKey();
    JwtBuilder builder = Jwts.builder()
            .setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .signWith(signatureAlgorithm, key);
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
    return builder.compact();
}
 
开发者ID:TomChen001,项目名称:xmanager,代码行数:27,代码来源:JwtUtil.java

示例4: before

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
@Before
public void before(){
    String pk = org.apache.commons.codec.binary.Base64.encodeBase64String(keyPair.getPublic().getEncoded());

    stubFor(get("/oauth2/publickey").willReturn(aResponse().withStatus(200).withBody(pk)));
    
    JwtBuilder builder = jwtBuilder(System.currentTimeMillis()+3600*1000L)
            .signWith(SignatureAlgorithm.RS256,keyPair.getPrivate());
    jwtToken = builder.compact();

    SSOConfig config = new SSOConfig().autoConfigureUrls(baseUrl);
    config.setClientId("test");
    config.setClientSecret("test_secret");
    config.setResourceName("resourceName");
    config.setRedirectUri("http://www.example.com");
    client = new SSOClient(config);

    basicHeader = SSOUtils.encodeBasicAuthorizationHeader(config.getClientId(),config.getClientSecret());
}
 
开发者ID:bingo-oss,项目名称:sso-client,代码行数:20,代码来源:SSOClientTest.java

示例5: createJWT

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
public String createJWT(String id, String subject, long ttlMillis) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = jwtConfig.generalKey();
    JwtBuilder builder = Jwts.builder()
            .setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .signWith(signatureAlgorithm, key);
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
    return builder.compact();
}
 
开发者ID:hs-web,项目名称:hsweb-framework,代码行数:18,代码来源:JwtTokenGenerator.java

示例6: Can_create_a_jwt_token_with_no_expiry

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
@Test
public void Can_create_a_jwt_token_with_no_expiry() {

    final String principal = someString();

    final JwtBuilder builder = mock(JwtBuilder.class);
    final JwtBuilder principleBuilder = mock(JwtBuilder.class);
    final JwtBuilder secretBuilder = mock(JwtBuilder.class);

    final String expected = someString();

    // Given
    given(builderFactory.create()).willReturn(builder);
    given(builder.claim(PRINCIPAL, principal)).willReturn(principleBuilder);
    given(principleBuilder.signWith(algorithm, privateKey)).willReturn(secretBuilder);
    given(secretBuilder.compact()).willReturn(expected);

    // When
    final String actual = new JJwtEncryptor(builderFactory, algorithm, keyPair, -1, expiryUnit, clock)
        .encrypt(principal);

    // Then
    verifyZeroInteractions(clock);
    assertThat(actual, is(expected));
}
 
开发者ID:shiver-me-timbers,项目名称:smt-spring-security-parent,代码行数:26,代码来源:JJwtEncryptorTest.java

示例7: signCompact

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/**
 * <p>
 * 签名并生成 Token
 * </p>
 */
public static String signCompact(JwtBuilder jwtBuilder) {
    SSOConfig config = SSOConfig.getInstance();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm());
    if (SSOConstants.SIGN_RSA.equals(signatureAlgorithm.getFamilyName())) {
        try {
            ClassPathResource resource = new ClassPathResource(config.getRsaKeystore());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(resource.getInputStream(), config.getRsaStorepass().toCharArray());
            Key key = keystore.getKey(config.getRsaAlias(), config.getRsaKeypass().toCharArray());
            // RSA 签名
            return jwtBuilder.signWith(signatureAlgorithm, key).compact();
        } catch (Exception e) {
            throw new KissoException("signCompact error.", e);
        }
    }
    // 普通签名
    return jwtBuilder.signWith(signatureAlgorithm, config.getSignkey()).compact();
}
 
开发者ID:baomidou,项目名称:kisso,代码行数:24,代码来源:JwtHelper.java

示例8: login

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
@Path("login")
@POST
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public String login(@FormParam(value = "id") String id) throws IOException {
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
	 
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
 
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRECT);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
 
    JwtBuilder builder = Jwts.builder()
                                .setIssuedAt(now)
                                .setIssuer(id)
                                .signWith(signatureAlgorithm, signingKey);
 
    long expMillis = nowMillis + EXPIRE	;
       Date exp = new Date(expMillis);
       builder.setExpiration(exp);
     
    return builder.compact();
}
 
开发者ID:nphau,项目名称:Angular2-OnlineCinema,代码行数:24,代码来源:AccountController.java

示例9: issueJwt

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public String issueJwt(String subject, Map<String, Object> claims) {
    Assert.hasText(subject, "Subject can't be null or empty!!");
    Instant now = Instant.now();
    JwtBuilder jwtBuilder = Jwts.builder()
            .setHeaderParam(TYPE, JWT_TYPE)
            .setClaims(claims)
            .setSubject(subject)
            .setIssuer(this.jwtConfig.issuer())
            .setIssuedAt(Date.from(now))
            .setExpiration(Date.from(now.plus(this.jwtConfig.expirationTime(), MINUTES)))
            .setId(UUID.randomUUID().toString());
    this.signWith(jwtBuilder);
    return jwtBuilder.compact();
}
 
开发者ID:AdeptJ,项目名称:adeptj-modules,代码行数:19,代码来源:JwtServiceImpl.java

示例10: createUserJWT

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/**
 * Creates the jwt for the given dawg credentials
 * @param dawgCreds The credentials to encode
 * @return
 */
public String createUserJWT(DawgCreds dawgCreds) {

    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    Key signingKey = new SecretKeySpec(jwtSecret.getBytes(), SIGNATURE_ALG.getJcaName());
    Map<String, Object> claims = new HashMap<String, Object>();
    claims.put(DawgJwt.JWT_FIELD_CREDS, dawgCreds);

    JwtBuilder builder = Jwts.builder()
            .setClaims(claims)
            .setId(UUID.randomUUID().toString())
            .setIssuedAt(now) 
            .setSubject(JWT_SUBJECT)
            .setIssuer(this.jwtIssuer)
            .signWith(SIGNATURE_ALG, signingKey);

    if (this.ttlMillis >= 0) {
        long expMillis = nowMillis + this.ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }

    return builder.compact();
}
 
开发者ID:Comcast,项目名称:dawg,代码行数:30,代码来源:DawgJwtEncoder.java

示例11: createJwtRsa

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("RSA");

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:19,代码来源:MqttExample.java

示例12: createJwtEs

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("ES256");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:19,代码来源:MqttExample.java

示例13: createJwtRsa

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/** Create a RSA-based JWT for the given project id, signed with the given private key. */
private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("RSA");

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:19,代码来源:HttpExample.java

示例14: createJwtEs

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
/** Create an ES-based JWT for the given project id, signed with the given private key. */
private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("ES256");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
开发者ID:GoogleCloudPlatform,项目名称:java-docs-samples,代码行数:19,代码来源:HttpExample.java

示例15: createJWT

import io.jsonwebtoken.JwtBuilder; //导入依赖的package包/类
private String createJWT(String id, String issuer, String subject, Date expiration){
	//The JWT signature algorithm we will be using to sign the token
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	Date now = new Date(System.currentTimeMillis());
	
	//We will sign our JWT with our ApiKey secret
	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	//Let's set the JWT Claims
	JwtBuilder builder = Jwts.builder()
			.setId(id)
			.setIssuedAt(now)
			.setSubject(subject)
			.setIssuer(issuer)
			.setExpiration(expiration)
			.signWith(signatureAlgorithm, signingKey);

	//Builds the JWT and serializes it to a compact, URL-safe string
	return builder.compact();
}
 
开发者ID:rodrigojmlourenco,项目名称:CycleOurCity,代码行数:23,代码来源:CycleOurCitySecurityManager.java


注:本文中的io.jsonwebtoken.JwtBuilder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。