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