本文整理匯總了Java中io.jsonwebtoken.SignatureAlgorithm類的典型用法代碼示例。如果您正苦於以下問題:Java SignatureAlgorithm類的具體用法?Java SignatureAlgorithm怎麽用?Java SignatureAlgorithm使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SignatureAlgorithm類屬於io.jsonwebtoken包,在下文中一共展示了SignatureAlgorithm類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: Gerate
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的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: createRefreshToken
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
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);
}
示例3: encode
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
public static String encode(String subject, ArrayList<String> roles) {
// prepare expiration date according to application properties
Date expDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(expDate);
int unit;
switch (applicationProperties.getTokenExpiration().getUnit()) {
case "SECOND":
unit = Calendar.SECOND;
break;
case "MINUTE":
unit = Calendar.MINUTE;
break;
default:
unit = Calendar.HOUR;
}
calendar.add(unit, applicationProperties.getTokenExpiration().getValue());
expDate = calendar.getTime();
return Jwts.builder().setSubject(subject).claim("roles", roles).setIssuedAt(new Date()).setExpiration(expDate)
.signWith(SignatureAlgorithm.HS256, key).compact();
}
示例4: getAuthorization
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
@POST
@Path("authorize")
@Consumes(MediaType.TEXT_PLAIN)
public Response getAuthorization(String clientCode) {
if (clientCode != null && clientCode.equals(deskDroidService.code)) {
String jwt = Jwts.builder()
.setSubject("DeskDroid")
.signWith(SignatureAlgorithm.HS512,
KeyGenerator.getKey(deskDroidService.getApplicationContext()))
.compact();
LocalBroadcastManager.getInstance(deskDroidService.getApplicationContext())
.sendBroadcast(new Intent(DeskDroidService.CODE_ACCEPTED));
return Response.ok(jwt).build();
}
return Response.status(Response.Status.UNAUTHORIZED).build();
}
示例5: generateNewDeploymentToken
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
@SuppressWarnings("unchecked")
private static void generateNewDeploymentToken(File tokenFile) throws IOException {
deploymentHash = Util.computeSHA256(serverID);
JSONObject root = new JSONObject();
root.put("timestamp", System.currentTimeMillis());
root.put("hash", deploymentHash);
String jwt = Jwts.builder()
.setPayload(root.toJSONString())
.signWith(SignatureAlgorithm.ES384, configuration.getServerPrivateKey())
.compact(); // Sign and build the JWT
Util.putFileContents(jwt, tokenFile);
logger.info("Generated new deployment token.");
}
示例6: getEnterpriseToken
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
/**
* Get the enterprise token witch can used to invoke admin api,such as managing departments and groups
*
* @param enterpriseId Your enterprise id
* @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
* @return Detailed user access information
* @throws YfyException
*/
public YfyAuthFinish getEnterpriseToken(long enterpriseId, int expirationTimeSeconds) throws YfyException {
Claims claims = new DefaultClaims();
claims.put("yifangyun_sub_type", "enterprise");
claims.setSubject(String.valueOf(enterpriseId));
claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds));
claims.setIssuedAt(new Date());
claims.setId(getGeneratedJwtId(16));
final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact();
return YfyRequestUtil.doPostInAuth(
requestConfig,
YfyAppInfo.getHost().getAuth(),
"oauth/token",
new HashMap<String, String>() {{
put("grant_type", "jwt");
put("assertion", compactJws);
}},
YfyAuthFinish.class);
}
示例7: getUserToken
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
/**
* Get the user token witch can used to invoke personal api,such as get folder information
*
* @param userId The user you want to operate with
* @param expirationTimeSeconds Expiration time seconds in the future(can not be bigger than 60)
* @return Detailed user access information
* @throws YfyException
*/
public YfyAuthFinish getUserToken(long userId, int expirationTimeSeconds) throws YfyException {
Claims claims = new DefaultClaims();
claims.put("yifangyun_sub_type", "user");
claims.setSubject(String.valueOf(userId));
claims.setExpiration(getExpirationTimeSecondsInTheFuture(expirationTimeSeconds));
claims.setIssuedAt(new Date());
claims.setId(getGeneratedJwtId(16));
final String compactJws = Jwts.builder().setHeader(headers).setClaims(claims).signWith(SignatureAlgorithm.RS256, key).compact();
return YfyRequestUtil.doPostInAuth(
requestConfig,
YfyAppInfo.getHost().getAuth(),
"oauth/token",
new HashMap<String, String>() {{
put("grant_type", "jwt");
put("assertion", compactJws);
}},
YfyAuthFinish.class);
}
示例8: issueToken
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
/**
* Issue a JWT token
*
* @param authenticationTokenDetails
* @return
*/
public String issueToken(AuthenticationTokenDetails authenticationTokenDetails) {
return Jwts.builder()
.setId(authenticationTokenDetails.getId())
.setIssuer(settings.getIssuer())
.setAudience(settings.getAudience())
.setSubject(authenticationTokenDetails.getUsername())
.setIssuedAt(Date.from(authenticationTokenDetails.getIssuedDate().toInstant()))
.setExpiration(Date.from(authenticationTokenDetails.getExpirationDate().toInstant()))
.claim(settings.getAuthoritiesClaimName(), authenticationTokenDetails.getAuthorities())
.claim(settings.getRefreshCountClaimName(), authenticationTokenDetails.getRefreshCount())
.claim(settings.getRefreshLimitClaimName(), authenticationTokenDetails.getRefreshLimit())
.signWith(SignatureAlgorithm.HS256, settings.getSecret())
.compact();
}
示例9: addAuthentication
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
static void addAuthentication(HttpServletResponse response, String username) {
// 生成JWT
String JWT = Jwts.builder()
// 保存權限(角色)
.claim("authorities", "READ")
// 用戶名寫入標題
.setSubject(username)
// 有效期設置
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
// 簽名設置
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
// 將 JWT 寫入 body
try {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print("{\"token\":\"" + JWT + "\"}");
} catch (IOException e) {
e.printStackTrace();
}
}
示例10: addAuthentication
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
void addAuthentication(HttpServletResponse response, String username, Collection<? extends GrantedAuthority> authorities) throws IOException {
List<String> roles = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
Claims claims = Jwts.claims()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + expirationTime * 60 * 1000));
claims.put(ROLE_KEY, roles.stream().collect(Collectors.joining(ROLE_DELIMITER)));
String JWT = Jwts.builder()
.setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
response.addHeader(headerString, headerStartWith + JWT);
JwtAuthenticatedUser user = new JwtAuthenticatedUser(username, roles);
PrintWriter printWriter = response.getWriter();
printWriter.print(mapper.writeValueAsString(user));
printWriter.flush();
}
示例11: login
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
@JsonView(Views.Public.class)
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<?> login(@RequestBody LoginModel data) {
User user = userService.getByUsername(data.getUsername());
if (user == null) {
return new ResponseEntity(new LoginResponseBody(false, null, "User with that name isn't exist"),
HttpStatus.OK);
}
if (!Objects.equals(user.getPassword(), MD5.getHash(data.getPassword()))) {
return new ResponseEntity(new LoginResponseBody(false, null, "wrong_password"),
HttpStatus.OK);
}
String token = Jwts.builder()
.setSubject(data.getUsername())
.signWith(SignatureAlgorithm.HS512, key)
.compact();
return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK);
}
示例12: register
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
@JsonView(Views.Public.class)
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> register(@RequestBody LoginModel data) {
User user = userService.getByUsername(data.getUsername());
if (user != null) {
return new ResponseEntity(new LoginResponseBody(false, null, "User with that name has already existed"),
HttpStatus.OK);
}
User newUser = new User(data.getUsername(), MD5.getHash(data.getPassword()), new Date(), "active", 0);
userService.addUser(newUser);
String token = Jwts.builder()
.setSubject(newUser.getUsername())
.signWith(SignatureAlgorithm.HS512, key)
.compact();
return new ResponseEntity(new LoginResponseBody(true, token), HttpStatus.OK);
}
示例13: createJWT
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的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();
}
示例14: before
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的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());
}
示例15: getAsymmetricKeyAlgorithm
import io.jsonwebtoken.SignatureAlgorithm; //導入依賴的package包/類
@SuppressWarnings("incomplete-switch")
private static String getAsymmetricKeyAlgorithm(SignatureAlgorithm sa) {
switch (sa) {
case ES256:
return "EC";
case ES384:
return "EC";
case ES512:
return "EC";
case PS256:
return "RSA";
case PS384:
return "RSA";
case PS512:
return "RSA";
case RS256:
return "RSA";
case RS384:
return "RSA";
case RS512:
return "RSA";
default:
break;
}
return null;
}