本文整理汇总了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();
}
示例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));
}
示例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();
}
示例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());
}
示例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();
}
示例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));
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}
示例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();
}