當前位置: 首頁>>代碼示例>>Java>>正文


Java JWT類代碼示例

本文整理匯總了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();
    }
}
 
開發者ID:VendingOnTime,項目名稱:server-vot,代碼行數:17,代碼來源:JWTTokenGenerator.java

示例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);
    }
}
 
開發者ID:line,項目名稱:line-login-starter,代碼行數:17,代碼來源:LineAPIService.java

示例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("---------------------------------");
    }
 
開發者ID:yuhuachang,項目名稱:spring-boot-oauth2-azuread,代碼行數:22,代碼來源:AzureAdJwtToken.java

示例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;
}
 
開發者ID:ceefour,項目名稱:java-web-services-training,代碼行數:21,代碼來源:CountriesController.java

示例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.");
}
 
開發者ID:Islandora-CLAW,項目名稱:Syn,代碼行數:26,代碼來源:SynValveTest.java

示例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));
}
 
開發者ID:Islandora-CLAW,項目名稱:Syn,代碼行數:20,代碼來源:VerifierTest.java

示例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")));
}
 
開發者ID:Islandora-CLAW,項目名稱:Syn,代碼行數:24,代碼來源:VerifierTest.java

示例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")));
}
 
開發者ID:Islandora-CLAW,項目名稱:Syn,代碼行數:22,代碼來源:VerifierTest.java

示例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;
}
 
開發者ID:Petrakus,項目名稱:java-jwt-auth,代碼行數:17,代碼來源:RESTService.java

示例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;
}
 
開發者ID:Petrakus,項目名稱:java-jwt-auth,代碼行數:20,代碼來源:RESTService.java

示例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());
}
 
開發者ID:ISIS2503,項目名稱:ThermalComfortBack,代碼行數:23,代碼來源:AuthorizationFilter.java

示例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;
    }
}
 
開發者ID:ISIS2503,項目名稱:ThermalComfortBack,代碼行數:23,代碼來源:AuthenticationFilter.java

示例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());
}
 
開發者ID:VendingOnTime,項目名稱:server-vot,代碼行數:18,代碼來源:LogInRouterTest.java

示例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;
}
 
開發者ID:mvetsch,項目名稱:JWT4B,代碼行數:12,代碼來源:TokenCheck.java

示例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;
}
 
開發者ID:Twasi,項目名稱:twasi-core,代碼行數:22,代碼來源:JWTManager.java


注:本文中的com.auth0.jwt.JWT類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。