当前位置: 首页>>代码示例>>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;未经允许,请勿转载。