Java Code Examples for com.auth0.jwt.JWT#decode()

The following examples show how to use com.auth0.jwt.JWT#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IdTokenVerifierTest.java    From auth0-java with MIT License 6 votes vote down vote up
@Test
public void succeedsWithValidTokenUsingDefaultClockAndHttpDomain() {
    String token = JWT.create()
            .withSubject("auth0|sdk458fks")
            .withAudience(AUDIENCE)
            .withIssuedAt(getYesterday())
            .withExpiresAt(getTomorrow())
            .withIssuer("http://" + DOMAIN + "/")
            .withClaim("nonce", "nonce")
            .sign(Algorithm.HMAC256("secret"));

    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    IdTokenVerifier.init("http://" + DOMAIN + "/", AUDIENCE, verifier)
            .build()
            .verify(token, "nonce");
}
 
Example 2
Source File: IdTokenVerifierTest.java    From auth0-java-mvc-common with MIT License 6 votes vote down vote up
@Test
public void succeedsWithValidTokenUsingDefaultClockAndHttpDomain() {
    String token = JWT.create()
            .withSubject("auth0|sdk458fks")
            .withAudience(AUDIENCE)
            .withIssuedAt(getYesterday())
            .withExpiresAt(getTomorrow())
            .withIssuer("http://" + DOMAIN + "/")
            .withClaim("nonce", "nonce")
            .sign(Algorithm.HMAC256("secret"));

    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    IdTokenVerifier.Options opts = new IdTokenVerifier.Options("http://" + DOMAIN + "/", AUDIENCE, verifier);
    opts.setNonce("nonce");

    new IdTokenVerifier().verify(token, opts);
}
 
Example 3
Source File: IdTokenVerifierTest.java    From auth0-java with MIT License 5 votes vote down vote up
@Test
public void succeedsWithValidTokenUsingDefaultClock() {
    String token = JWT.create()
            .withSubject("auth0|sdk458fks")
            .withAudience(AUDIENCE)
            .withIssuedAt(getYesterday())
            .withExpiresAt(getTomorrow())
            .withIssuer("https://" + DOMAIN + "/")
            .withClaim("nonce", "nonce")
            .sign(Algorithm.HMAC256("secret"));

    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    IdTokenVerifier.init("https://" + DOMAIN + "/", AUDIENCE, verifier)
            .build()
            .verify(token, "nonce");
}
 
Example 4
Source File: JwtSessionConfigurator.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Extracts the Database from the decoded JWT.
    */
   @Override
   public String getDatabase(String sessionId) {
try {
    DecodedJWT jwt = JWT.decode(sessionId);
    Map<String, Claim> claims = jwt.getClaims(); // Key is the Claim
						 // name
    Claim claim = claims.get("dbn");
    return claim.asString();

} catch (JWTDecodeException exception) {
    System.err.println(exception);
    return null;
}
   }
 
Example 5
Source File: JwtUtil.java    From watchdog-framework with MIT License 5 votes vote down vote up
/**
 * 获得token中的指定KEY值信息
 */
public static String get(String token,String key) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(key).asString();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example 6
Source File: TokenCheck.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isValidJWT(String jwt) {
	 
	if (StringUtils.countMatches(jwt, ".") != 2) {
		return false;
	}
	
	jwt=jwt.trim();
	if(StringUtils.contains(jwt," ")){
		return false;
	}

	String[] sArray=StringUtils.split(jwt,".");
	if(sArray.length < 3){
		return false;
	}
	for(String value:sArray){
		if(!value.matches("[A-Za-z0-9+/=_-]+")){
			return false;
		}
	}

	try {
		DecodedJWT decoded = JWT.decode(jwt);
		decoded.getAlgorithm();
		return true;
	} catch (Exception exception) {}
	
	return false;
}
 
Example 7
Source File: HMACAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldPassHMAC384Verification() throws Exception {
    String jwt = "eyJhbGciOiJIUzM4NCIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.uztpK_wUMYJhrRv8SV-1LU4aPnwl-EM1q-wJnqgyb5DHoDteP6lN_gE1xnZJH5vw";
    Algorithm algorithmString = Algorithm.HMAC384("secret");
    Algorithm algorithmBytes = Algorithm.HMAC384("secret".getBytes(StandardCharsets.UTF_8));
    DecodedJWT decoded = JWT.decode(jwt);
    algorithmString.verify(decoded);
    algorithmBytes.verify(decoded);
}
 
Example 8
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
public static Long getUserId(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("userId").asLong();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example 9
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("username").asString();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example 10
Source File: AuthUtils.java    From mdw with Apache License 2.0 5 votes vote down vote up
private static boolean checkBearerAuthenticationHeader(String authHeader, Map<String,String> headers) {
    try {
        // Do NOT try to authenticate if it's not Bearer
        if (authHeader == null || !authHeader.startsWith("Bearer"))
            throw new Exception("Invalid MDW Auth Header");  // This should never happen

        authHeader = authHeader.replaceFirst("Bearer ", "");
        DecodedJWT jwt = JWT.decode(authHeader);  // Validate it is a JWT and see which kind of JWT it is

        if (MDW_AUTH.equals(jwt.getIssuer()))  // JWT was issued by MDW Central
            verifyMdwJWT(authHeader, headers);
        else if (verifierCustom.get(jwt.getIssuer()) != null ||
                (PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT) != null &&
                 PropertyManager.getInstance().getProperties(PropertyNames.MDW_JWT).values().contains(jwt.getIssuer())))  // Support for other issuers of JWTs
            verifyCustomJWT(authHeader, jwt.getAlgorithm(), jwt.getIssuer(), headers);
        else
            throw new Exception("Invalid JWT Issuer");
    }
    catch (Throwable ex) {
        if (!ApplicationContext.isDevelopment()) {
            headers.put(Listener.AUTHENTICATION_FAILED, "Authentication failed for JWT '" + authHeader + "' " + ex.getMessage());
            logger.error("Authentication failed for JWT '"+authHeader+"' " + ex.getMessage(), ex);
        }
        return false;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Bearer authentication successful for user '"+headers.get(Listener.AUTHENTICATED_USER_HEADER)+"'");
    }
    if (PropertyManager.getBooleanProperty(PropertyNames.MDW_JWT_PRESERVE, false))
        headers.put(Listener.AUTHENTICATED_JWT, authHeader);
    return true;
}
 
Example 11
Source File: IdTokenVerifierTest.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
private IdTokenVerifier.Options configureOptions(String token) {
    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    IdTokenVerifier.Options opts = new IdTokenVerifier.Options("https://" + DOMAIN + "/", AUDIENCE, verifier);
    opts.setClock(DEFAULT_CLOCK);
    return opts;
}
 
Example 12
Source File: AthenzAccessToken.java    From vespa with Apache License 2.0 5 votes vote down vote up
private DecodedJWT jwt() {
    if (jwt == null) {
        // Decoding a token is expensive and involves construction of at least one Jackson ObjectMapper instance
        // TODO Cache encoder/decoder as static field in AthenzAccessToken
        jwt = JWT.decode(this.value);
    }
    return jwt;
}
 
Example 13
Source File: CallbackController.java    From auth0-spring-security-mvc-sample with MIT License 5 votes vote down vote up
private void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        Tokens tokens = controller.handle(request, response);
        TokenAuthentication tokenAuth = new TokenAuthentication(JWT.decode(tokens.getIdToken()));
        SecurityContextHolder.getContext().setAuthentication(tokenAuth);
        response.sendRedirect(redirectOnSuccess);
    } catch (AuthenticationException | IdentityVerificationException e) {
        e.printStackTrace();
        SecurityContextHolder.clearContext();
        response.sendRedirect(redirectOnFail);
    }
}
 
Example 14
Source File: JwtUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 *
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
	try {
		DecodedJWT jwt = JWT.decode(token);
		return jwt.getClaim("username").asString();
	} catch (JWTDecodeException e) {
		return null;
	}
}
 
Example 15
Source File: HMACAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldPassHMAC512Verification() throws Exception {
    String jwt = "eyJhbGciOiJIUzUxMiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.VUo2Z9SWDV-XcOc_Hr6Lff3vl7L9e5Vb8ThXpmGDFjHxe3Dr1ZBmUChYF-xVA7cAdX1P_D4ZCUcsv3IefpVaJw";
    Algorithm algorithmString = Algorithm.HMAC512("secret");
    Algorithm algorithmBytes = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8));
    DecodedJWT decoded = JWT.decode(jwt);
    algorithmString.verify(decoded);
    algorithmBytes.verify(decoded);
}
 
Example 16
Source File: TokenService.java    From coderadar with MIT License 4 votes vote down vote up
/**
 * Returns username from the tokens claim <code>username</code>.
 *
 * @param refreshToken a jwt token
 */
public String getUsername(String refreshToken) {
  JWT jwt = JWT.decode(refreshToken);
  Claim claim = jwt.getClaim("username");
  return claim.asString();
}
 
Example 17
Source File: JwtTokenExtractor.java    From botbuilder-java with MIT License 4 votes vote down vote up
private boolean hasAllowedIssuer(String token) {
    DecodedJWT decodedJWT = JWT.decode(token);
    return this.tokenValidationParameters.validIssuers != null
        && this.tokenValidationParameters.validIssuers.contains(decodedJWT.getIssuer());
}
 
Example 18
Source File: JwtToken.java    From Moss with Apache License 2.0 4 votes vote down vote up
public JwtToken(String token) {
    this.token = token;
    this.jwt = JWT.decode(token);
}
 
Example 19
Source File: JwtUtil.java    From ShiroJwt with MIT License 4 votes vote down vote up
/**
 * 获得Token中的信息无需secret解密也能获得
 * @param token
 * @param claim
 * @return java.lang.String
 * @author Wang926454
 * @date 2018/9/7 16:54
 */
public static String getClaim(String token, String claim) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        // 只能输出String类型,如果是其他类型返回null
        return jwt.getClaim(claim).asString();
    } catch (JWTDecodeException e) {
        logger.error("解密Token中的公共信息出现JWTDecodeException异常:{}", e.getMessage());
        throw new CustomException("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
    }
}
 
Example 20
Source File: JwtUtil.java    From spring-boot-plus with Apache License 2.0 2 votes vote down vote up
/**
 * 解析token,获取token数据
 *
 * @param token
 * @return
 */
public static DecodedJWT getJwtInfo(String token) {
    return JWT.decode(token);
}