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


Java JWTVerifier類代碼示例

本文整理匯總了Java中com.auth0.jwt.JWTVerifier的典型用法代碼示例。如果您正苦於以下問題:Java JWTVerifier類的具體用法?Java JWTVerifier怎麽用?Java JWTVerifier使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JWTVerifier類屬於com.auth0.jwt包,在下文中一共展示了JWTVerifier類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: recoverFrom

import com.auth0.jwt.JWTVerifier; //導入依賴的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: verify

import com.auth0.jwt.JWTVerifier; //導入依賴的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

示例3: getUserId

import com.auth0.jwt.JWTVerifier; //導入依賴的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

示例4: unsign

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
/**
 * 解密,傳入一個加密後的token字符串和解密後的類型
 * @param jwt
 * @param classT
 * @param <T>
 * @return
 */
public static<T> T unsign(String jwt, Class<T> classT) {
    final JWTVerifier verifier = new JWTVerifier(SECRET);
    try {
        final Map<String,Object> claims= verifier.verify(jwt);
        if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
            long exp = (Long)claims.get(EXP);
            long currentTimeMillis = System.currentTimeMillis();
            if (exp > currentTimeMillis) {
                String json = (String)claims.get(PAYLOAD);
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(json, classT);
            }
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}
 
開發者ID:MasonQAQ,項目名稱:WeatherSystem,代碼行數:26,代碼來源:JavaWebTokenUtil.java

示例5: validateToken

import com.auth0.jwt.JWTVerifier; //導入依賴的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

示例6: verifyToken

import com.auth0.jwt.JWTVerifier; //導入依賴的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

示例7: unsign

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
/**
 * get the object of jwt if not expired
 * @param jwt
 * @return POJO object
 */
public static<T> T unsign(String jwt, Class<T> classT) {
	final JWTVerifier verifier = new JWTVerifier(SECRET);
    try {
		final Map<String,Object> claims= verifier.verify(jwt);
		if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
			long exp = (Long)claims.get(EXP);
			long currentTimeMillis = System.currentTimeMillis();
			if (exp > currentTimeMillis) {
				String json = (String)claims.get(PAYLOAD);
				ObjectMapper objectMapper = new ObjectMapper();
				return objectMapper.readValue(json, classT);
			}
		}
		return null;
	} catch (Exception e) {
		return null;
	}
}
 
開發者ID:imchenglibin,項目名稱:spring-web-tutorial,代碼行數:24,代碼來源:JWT.java

示例8: handle

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Override
public void handle(Request request, Response response) throws Exception {
    String authorizationHeader = request.headers("Authorization");

    if (authorizationHeader == null) {
        AuthenticationUtilities.setUserAsAnonymous(request);
    } else {
        String token = authorizationHeader.replaceFirst("Bearer ", "");
        DecodedJWT decodedToken = JWT.decode(token);

        JWTVerifier verifier = selectVerifier(decodedToken);

        DecodedJWT decodedJWT = verifier.verify(token);
        AuthenticationUtilities.setUser(request, decodedJWT.getSubject());
    }
}
 
開發者ID:khartec,項目名稱:waltz,代碼行數:17,代碼來源:JWTAuthenticationFilter.java

示例9: verifyJwtToken

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
private void verifyJwtToken(Response response) throws NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, JWTVerifyException {
    String cookieContent = response.getCookies().get(HttpHeaders.AUTHORIZATION).getValue();
    assertThat(cookieContent, StringStartsWith.startsWith("Bearer "));
    String jwt = cookieContent.substring(7);

    JWTVerifier jwtVerifier = new JWTVerifier("myJWT4Gr4v1t33_S3cr3t");

    Map<String, Object> mapJwt = jwtVerifier.verify(jwt);

    assertEquals(mapJwt.get("sub"),"[email protected]");

    assertEquals(mapJwt.get("firstname"),"Jane");
    assertEquals(mapJwt.get("iss"),"gravitee-management-auth");
    assertEquals(mapJwt.get("sub"),"[email protected]");
    assertEquals(mapJwt.get("email"),"[email protected]");
    assertEquals(mapJwt.get("lastname"),"Doe");
}
 
開發者ID:gravitee-io,項目名稱:gravitee-management-rest-api,代碼行數:18,代碼來源:OAuth2AuthenticationResourceTest.java

示例10: doCredentialsMatch

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    JsonWebToken jsonWebToken = (JsonWebToken) token;
    JWTVerifier verifier = new JWTVerifier(secret, audience);
    try {
        Map<String, Object> map = verifier.verify(jsonWebToken.getToken());
        SimpleAuthenticationInfo authenticationInfo = (SimpleAuthenticationInfo) info;
        String realmName = authenticationInfo.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection();
        principals.add(map.get("iss"), realmName);
        authenticationInfo.setPrincipals(principals);
        return true;
    } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | SignatureException
            | IOException | JWTVerifyException e) {
        log.debug(e.getMessage());
        return false;
    }
}
 
開發者ID:howiefh,項目名稱:jee-restful-web,代碼行數:19,代碼來源:JsonWebTokenCredentialsMatcher.java

示例11: filter

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Override
public final void filter (final ContainerRequestContext crc) throws IOException {
    String token = crc.getUriInfo().getQueryParameters().getFirst("jwt");
    if (token == null) {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
    String jwtSecret = configuration.getJWTSecret();
    if (jwtSecret == null) {
        throw new ConfigurationException("Must set the " + EnvironmentConfiguration.JWT_SECRET
            + " environment variable.");
    }
    byte[] secret = DECODER.decodeBase64(jwtSecret);
    //Map<String,Object> payload;
    try {
        new JWTVerifier(
                secret,
                configuration.getJWTAudience().orElse(null),
                configuration.getJWTIssuer().orElse(null)
        ).verify(token);
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "JWT verification failed", ex);
        throw new WebApplicationException(Response.Status.FORBIDDEN);
    }
}
 
開發者ID:jonmbake,項目名稱:reports-micro-service,代碼行數:25,代碼來源:AuthFilter.java

示例12: shouldContains5Claims

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Test
public void shouldContains5Claims() throws Exception {
	String token = createToken();
	
	assertNotNull(token);
	
	JWTVerifier verifier = new JWTVerifier(SECRET);
	Map<String, Object> tokenObject = verifier.verify(token);
	
	assertNotNull(tokenObject);
	assertEquals(5, tokenObject.size());
	assertEquals(tokenObject.get(JwtConstants.USER_ID), "test");
	assertEquals(tokenObject.get(JwtConstants.ROLES), Arrays.asList("role1, role2"));
	
	long now = System.currentTimeMillis() / 1000L;
	long timeToExpire = ((int)tokenObject.get("exp")) - now;
	assertTrue(timeToExpire > 0);
	assertTrue(timeToExpire <= 10000);
	
	int issueTime = (int) tokenObject.get("iat");
	assertTrue(issueTime <= now);
}
 
開發者ID:andreacomo,項目名稱:tomcat-jwt-security,代碼行數:23,代碼來源:JwtTokenBuilderTest.java

示例13: shouldParseJwtFromString

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Test
public void shouldParseJwtFromString() throws Exception {
	String token = createToken();
	
	assertNotNull(token);
	
	JwtTokenBuilder from = JwtTokenBuilder.from(token, SECRET);
	String token2 = from.expirySecs(20000).notValidBeforeLeeway(10000).build();
	
	int now = (int) (System.currentTimeMillis() / 1000L);
	JWTVerifier verifier = new JWTVerifier(SECRET);
	Map<String, Object> tokenObject = verifier.verify(token2);

	int exp = (int) tokenObject.get("exp");
	assertTrue(exp <= now + 20000);
	assertTrue(exp > now);

	int nbf = (int) tokenObject.get("nbf");
	assertTrue(nbf >= now - 10000);
	assertTrue(nbf < now);
}
 
開發者ID:andreacomo,項目名稱:tomcat-jwt-security,代碼行數:22,代碼來源:JwtTokenBuilderTest.java

示例14: doFilter

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            boolean allowed = true;
            HttpServletRequest httpReq = (HttpServletRequest) request;
            HttpServletResponse httpResp = (HttpServletResponse) response;
            if (!"OPTIONS".equals(httpReq.getMethod())) {
                String authorization = httpReq.getHeader("Authorization");
                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);

                allowed = "hendy".equals(userId); // any custom logic here
            }
            if (allowed) {
                chain.doFilter(request, response);
            } else {
                httpResp.setStatus(403);
                httpResp.setHeader("Content-Type", "application/json");
                httpResp.getWriter().write(
                        "{\"error\": \"Unauthorized\", \"message\": \"Access denied\"}");
//                mapper.writeValue(httpResp.getWriter(),
//                        new Error("Unauthorized", "Access denied"));
            }
        } else {
            chain.doFilter(request, response);
        }
    }
 
開發者ID:ceefour,項目名稱:java-web-services-training,代碼行數:40,代碼來源:JwtAuthFilter.java

示例15: verify

import com.auth0.jwt.JWTVerifier; //導入依賴的package包/類
public boolean verify(final Algorithm algorithm) {
    final JWTVerifier verifier = JWT.require(algorithm).build();
    try {
        verifier.verify(this.token);
    } catch (JWTVerificationException exception) {
        return false;
    }

    return true;
}
 
開發者ID:Islandora-CLAW,項目名稱:Syn,代碼行數:11,代碼來源:Verifier.java


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