本文整理汇总了Java中com.auth0.jwt.JWT类的典型用法代码示例。如果您正苦于以下问题:Java JWT类的具体用法?Java JWT怎么用?Java JWT使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JWT类属于com.auth0.jwt包,在下文中一共展示了JWT类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: recoverFrom
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Override
public Optional<Person> recoverFrom(String token) {
try {
JWTVerifier verifier = JWT.require(getAlgorithm())
.withIssuer(config.getString(ServerVariable.JWT_ISSUER))
.build();
verifier.verify(token);
JWT decode = JWT.decode(token);
String email = decode.getClaim(EMAIL_CLAIM).asString();
return repository.findByEmail(email);
} catch (UnsupportedEncodingException | SignatureVerificationException | JWTDecodeException e) {
return Optional.empty();
}
}
示例2: idToken
import com.auth0.jwt.JWT; //导入依赖的package包/类
public IdToken idToken(String id_token) {
try {
DecodedJWT jwt = JWT.decode(id_token);
return new IdToken(
jwt.getClaim("iss").asString(),
jwt.getClaim("sub").asString(),
jwt.getClaim("aud").asString(),
jwt.getClaim("ext").asLong(),
jwt.getClaim("iat").asLong(),
jwt.getClaim("nonce").asString(),
jwt.getClaim("name").asString(),
jwt.getClaim("picture").asString());
} catch (JWTDecodeException e) {
throw new RuntimeException(e);
}
}
示例3: verify
import com.auth0.jwt.JWT; //导入依赖的package包/类
public void verify() throws IOException, CertificateException {
PublicKey publicKey = loadPublicKey();
// Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
// cipher.init(Cipher.DECRYPT_MODE, publicKey);
// byte[] encryptedbytes = cipher.doFinal(Base64.getUrlDecoder().decode(signatureStr.getBytes()));
// String result = Base64.getUrlEncoder().encodeToString(encryptedbytes);
// System.out.println("---------------------------------");
// System.out.println(result);
// System.out.println(parts[0] + parts[1]);
//
// System.out.println("---------------------------------");
//TODO: possible decode without 3rd party library...
JWTVerifier verifier = JWT.require(Algorithm.RSA256((RSAKey) publicKey)).withIssuer(issuer).build();
DecodedJWT jwt = verifier.verify(token);
// System.out.println("DecodedJWT");
// System.out.println(jwt);
// System.out.println("---------------------------------");
}
示例4: getUserId
import com.auth0.jwt.JWT; //导入依赖的package包/类
@ModelAttribute("userId")
public String getUserId(@RequestHeader("Authorization") String authorization)
throws UnsupportedEncodingException {
Preconditions.checkNotNull(authorization,
"Authorization header is required");
String[] splitted = authorization.split(" ");
if (!"Bearer".equals(splitted[0])) {
throw new AccessDeniedException("Authorization must be Bearer");
}
String token = splitted[1];
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
String userId = jwt.getSubject();
LOG.info("User: {}", userId);
return userId;
}
示例5: shouldFailTokenMissingUid
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Test
public void shouldFailTokenMissingUid() throws Exception {
final String host = "http://test.com";
final String token = JWT
.create()
.withClaim("name", "adminuser")
.withClaim("url", host)
.withArrayClaim("roles", new String[] {"role1", "role2", "role3"})
.withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset)))
.withExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(offset)))
.sign(Algorithm.HMAC256("secret"));
final SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setAuthConstraint(true);
when(realm.findSecurityConstraints(request, request.getContext()))
.thenReturn(new SecurityConstraint[] { securityConstraint });
when(request.getHeader("Authorization"))
.thenReturn("Bearer " + token);
synValve.start();
synValve.invoke(request, response);
verify(request).getHeader("Authorization");
verify(response).sendError(401, "Token authentication failed.");
}
示例6: testClaimsWithoutVerify
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Test
public void testClaimsWithoutVerify() {
token = JWT.create()
.withArrayClaim("roles", new String[]{"Role1", "Role2"})
.withClaim("uid", 1)
.withClaim("name", "admin")
.withClaim("url", "http://test.com")
.withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset)))
.withExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(offset)))
.sign(Algorithm.none());
final Verifier verifier = Verifier.create(token);
assertEquals(1, verifier.getUid());
assertEquals("admin", verifier.getName());
assertEquals("http://test.com", verifier.getUrl());
final List<String> roles = verifier.getRoles();
assertEquals(2, roles.size());
assertEquals("Role1", roles.get(0));
assertEquals("Role2", roles.get(1));
}
示例7: testClaimsAndVerifyHmac
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Test
public void testClaimsAndVerifyHmac() throws Exception {
token = JWT.create()
.withArrayClaim("roles", new String[]{"Role1", "Role2"})
.withClaim("uid", 1)
.withClaim("name", "admin")
.withClaim("url", "http://test.com")
.withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset)))
.withExpiresAt(Date.from(LocalDateTime.now().plusHours(2).toInstant(offset)))
.sign(Algorithm.HMAC256("secret"));
final Verifier verifier = Verifier.create(token);
assertEquals(1, verifier.getUid());
assertEquals("admin", verifier.getName());
assertEquals("http://test.com", verifier.getUrl());
final List<String> roles = verifier.getRoles();
assertEquals(2, roles.size());
assertEquals("Role1", roles.get(0));
assertEquals("Role2", roles.get(1));
assertTrue(verifier.verify(Algorithm.HMAC256("secret")));
assertFalse(verifier.verify(Algorithm.HMAC256("wrong secret")));
}
示例8: testClaimsAndVerifyHmacBadIssueDate
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Test
public void testClaimsAndVerifyHmacBadIssueDate() throws Exception {
token = JWT.create()
.withArrayClaim("roles", new String[]{"Role1", "Role2"})
.withClaim("uid", 1)
.withClaim("name", "admin")
.withClaim("url", "http://test.com")
.withIssuedAt(Date.from(LocalDateTime.now().toInstant(offset)))
.withExpiresAt(Date.from(LocalDateTime.now().minusHours(2).toInstant(offset)))
.sign(Algorithm.HMAC256("secret"));
final Verifier verifier = Verifier.create(token);
assertEquals(1, verifier.getUid());
assertEquals("admin", verifier.getName());
assertEquals("http://test.com", verifier.getUrl());
final List<String> roles = verifier.getRoles();
assertEquals(2, roles.size());
assertEquals("Role1", roles.get(0));
assertEquals("Role2", roles.get(1));
assertFalse(verifier.verify(Algorithm.HMAC256("secret")));
}
示例9: signToken
import com.auth0.jwt.JWT; //导入依赖的package包/类
private String signToken(User user) {
try {
Algorithm algorithm = Algorithm.HMAC256(Constants.JWT_TOKEN_KEY);
Date expirationDate = Date.from(ZonedDateTime.now().plusHours(24).toInstant());
Date issuedAt = Date.from(ZonedDateTime.now().toInstant());
return JWT.create()
.withIssuedAt(issuedAt)
.withExpiresAt(expirationDate)
.withClaim("userId", user.getId())
.withIssuer("jwtauth")
.sign(algorithm);
} catch (UnsupportedEncodingException | JWTCreationException e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
示例10: validateToken
import com.auth0.jwt.JWT; //导入依赖的package包/类
private User validateToken(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(Constants.JWT_TOKEN_KEY);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("jwtauth")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
//Get the userId from token claim.
Claim userId = jwt.getClaim("userId");
// Find user by token subject(id).
UserDao userDao = new UserDao();
return userDao.findUserById(userId.asLong());
} catch (UnsupportedEncodingException | JWTVerificationException e){
LOGGER.error(e.getMessage(), e);
}
return null;
}
示例11: checkPermissions
import com.auth0.jwt.JWT; //导入依赖的package包/类
private void checkPermissions(ContainerRequestContext requestContext, List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
if(allowedRoles.isEmpty())
return;
String authorizationHeader
= requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
List<String> roles = new ArrayList();
if (!JWT.decode(token).getClaim("gty").isNull() && JWT.decode(token).getClaim("gty").asString().equals("client-credentials")) {
roles.add("service");
} else {
roles = JWT.decode(token).getClaim("roles").asList(String.class);
}
for(String role: roles) {
if(allowedRoles.contains(Role.valueOf(role)))
return;
}
throw new WebApplicationException(
Response.status(Response.Status.FORBIDDEN).build());
}
示例12: verifyToken
import com.auth0.jwt.JWT; //导入依赖的package包/类
void verifyToken(String token) {
try {//Cambiar por variables de entorno
String issuer = "https://isis2503-fernan.auth0.com/";
String audience;
//Access token
if (!JWT.decode(token).getClaim("gty").isNull() && JWT.decode(token).getClaim("gty").asString().equals("client-credentials")) {
audience = "uniandes.edu.co/thermalcomfort";
}
//ID token
else {
audience = "9lRhfqv61bbsblYJ22VkvtuaYOryTrps";
}
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(issuer)
.withAudience(audience)
.build(); //Reusable verifier instance
verifier.verify(token);
} catch (JWTVerificationException exception) {
Logger.getLogger(AuthenticationFilter.class.getName()).log(Level.SEVERE, null, exception);
throw exception;
}
}
示例13: logInUser
import com.auth0.jwt.JWT; //导入依赖的package包/类
@Test
public void logInUser() throws Exception {
signUpService.createSupervisor(signUpData);
String result = (String) logInRouter.logInUser(stringifiedLogInData)
.handle(mock(Request.class), mock(Response.class));
RESTResult restResult = mapper.readValue(result, RESTResult.class);
assertTrue(restResult.getSuccess());
String token = (String) restResult.getData();
String tokenEmail = JWT.decode(token).getClaim(JWTTokenGenerator.EMAIL_CLAIM).asString();
assertThat(tokenEmail, equalTo(logInData.getEmail()));
Optional<Person> byEmail = repository.findByEmail(logInData.getEmail());
repository.delete(byEmail.get().getId());
}
示例14: isValidJWT
import com.auth0.jwt.JWT; //导入依赖的package包/类
public static boolean isValidJWT(String jwt) {
if (StringUtils.countMatches(jwt, ".") != 2) {
return false;
}
try {
DecodedJWT decoded = JWT.decode(jwt);
decoded.getAlgorithm();
return true;
} catch (Exception exception) {}
return false;
}
示例15: createNewToken
import com.auth0.jwt.JWT; //导入依赖的package包/类
public String createNewToken(User user) {
String token = null;
try {
String secret = generateNewSecret();
Algorithm algorithm = Algorithm.HMAC256(secret);
token = JWT.create()
.withIssuer(Config.getCatalog().auth.issuer)
.withIssuedAt(new Date())
.withClaim("name", user.getTwitchAccount().getUserName())
.withClaim("twitchid", user.getTwitchAccount().getTwitchId())
.sign(algorithm);
user.setJWTSecret(secret);
Database.getStore().save(user);
} catch (Exception e) {
TwasiLogger.log.error(e);
}
return token;
}