当前位置: 首页>>代码示例>>Java>>正文


Java JWT.decode方法代码示例

本文整理汇总了Java中com.auth0.jwt.JWT.decode方法的典型用法代码示例。如果您正苦于以下问题:Java JWT.decode方法的具体用法?Java JWT.decode怎么用?Java JWT.decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.auth0.jwt.JWT的用法示例。


在下文中一共展示了JWT.decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: 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

示例2: 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

示例3: 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

示例4: getToken

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
@Override
public DecodedJWT getToken() throws IOException {
    String serviceLoginToken = JWT.create()
                .withClaim("uid", uid)
                .withExpiresAt(Date.from(Instant.now().plusSeconds(120)))
                .sign(signatureAlgorithm);

    JSONObject data = new JSONObject();
    data.put("uid", uid);
    data.put("token", serviceLoginToken);

    Request request = Request.Post(DcosConstants.IAM_AUTH_URL)
            .bodyString(data.toString(), ContentType.APPLICATION_JSON);
    String responseData = httpExecutor.execute(request).returnContent().asString();

    return JWT.decode(new JSONObject(responseData).getString("token"));
}
 
开发者ID:mesosphere,项目名称:dcos-commons,代码行数:18,代码来源:ServiceAccountIAMTokenClient.java

示例5: handle

import com.auth0.jwt.JWT; //导入方法依赖的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

示例6: doFilterInternal

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
@Override
protected void doFilterInternal(
    HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
  String token = request.getHeader(TOKEN_HEADER);
  if (token != null) {
    try {
      DecodedJWT decodedToken = tokenService.verify(token);
      JWT jwt = JWT.decode(decodedToken.getToken());
      Claim username = jwt.getClaim("username");
      // so long we don't have authorisation, we just set GrantedAuthority to null
      UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
          new UsernamePasswordAuthenticationToken(username.asString(), null, null);
      SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
    } catch (JWTVerificationException e) {
      // in case of verification error a further filter will take care about authentication error
      logger.error("Authentication error. Token is not valid", e);
    }
  }
  filterChain.doFilter(request, response);
}
 
开发者ID:reflectoring,项目名称:coderadar,代码行数:22,代码来源:AuthenticationTokenFilter.java

示例7: isValidBearerToken

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
/**
   * This method is used to validate the Bearer token. It validates the source and the expiration and if the token is about to expire in 30 seconds, set as invalid token
   * @param accessToken
   * @param profile
   * @param clientId
   * @return
   * @throws IOException
   */
  private static boolean isValidBearerToken(String accessToken, ServerProfile profile, String clientId) throws IOException{
  	boolean isValid = false;
  	try {
    JWT jwt = JWT.decode(accessToken);
    String jwtClientId = jwt.getClaim("client_id").asString();
    String jwtEmailId = jwt.getClaim("email").asString();
    long jwtExpiresAt = jwt.getExpiresAt().getTime()/1000;
    long difference = jwtExpiresAt - (System.currentTimeMillis()/1000);
    if(jwt!= null && jwtClientId!=null && jwtClientId.equals(clientId)
   		&& jwtEmailId!=null && jwtEmailId.equalsIgnoreCase(profile.getCredential_user())
   		&& profile.getTokenUrl().contains(jwt.getIssuer())
   		&& difference >= 30){
    	isValid = true;
    }
} catch (JWTDecodeException exception){
   throw new IOException(exception.getMessage());
}
  	return isValid;
  }
 
开发者ID:apigee,项目名称:apigee-deploy-maven-plugin,代码行数:28,代码来源:RestUtil.java

示例8: loadFromSaaS

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
public static GitAccount loadFromSaaS(String authHeader) {
    String jwtToken = authHeader;
    int idx = authHeader.indexOf(' ');
    jwtToken = jwtToken.substring(idx + 1, jwtToken.length());
    try {
        JWT.decode(jwtToken);
    } catch (JWTDecodeException e) {
        throw new KeyCloakFailureException("KeyCloak returned an invalid token. Are you sure you are logged in?", e);
    }
    String authToken = TokenHelper.getMandatoryTokenFor(KeycloakEndpoint.GET_GITHUB_TOKEN, authHeader);
    return new GitAccount(null, authToken, null, null);
}
 
开发者ID:fabric8-launcher,项目名称:launcher-backend,代码行数:13,代码来源:GitAccount.java

示例9: create

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
public static Verifier create(final String token) {
    final Verifier verifier = new Verifier();
    verifier.token = token;
    try {
        verifier.jwt = JWT.decode(token);
        if (verifier.jwt.getClaim("uid").isNull()) {
            return null;
        }
        if (verifier.jwt.getClaim("url").isNull()) {
            return null;
        }
        if (verifier.jwt.getClaim("name").isNull()) {
            return null;
        }
        if (verifier.jwt.getClaim("roles").isNull()) {
            return null;
        }
        if (verifier.jwt.getExpiresAt() == null) {
            return null;
        }
        if (verifier.jwt.getIssuedAt() == null) {
            return null;
        }
    } catch (JWTDecodeException exception) {
        log.error("Error decoding token: " + token, exception);
        return null;
    }
    return verifier;
}
 
开发者ID:Islandora-CLAW,项目名称:Syn,代码行数:30,代码来源:Verifier.java

示例10: getUid

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
public static int getUid(String token) {
    try {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim("uid").asInt();
    } catch (JWTDecodeException e) {
        return 0;
    }
}
 
开发者ID:Eagle-OJ,项目名称:eagle-oj-api,代码行数:9,代码来源:JWTUtil.java

示例11: getUsername

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
/**
    * Extracts the username from the decoded JWT.
    */
   @Override
   public String getUsername(String sessionId) {
try {
    DecodedJWT jwt = JWT.decode(sessionId);
    Map<String, Claim> claims = jwt.getClaims();    //Key is the Claim name
    Claim claim = claims.get("usr");
    return claim.asString();
	    
    
} catch (JWTDecodeException exception){
    exception.printStackTrace();
    return null;
}
   }
 
开发者ID:kawansoft,项目名称:aceql-http,代码行数:18,代码来源:JwtSessionConfigurator.java

示例12: getDatabase

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
/**
    * 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;
}
   }
 
开发者ID:kawansoft,项目名称:aceql-http,代码行数:17,代码来源:JwtSessionConfigurator.java

示例13: getCreationTime

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
@Override
   public long getCreationTime(String sessionId) {
try {
    DecodedJWT jwt = JWT.decode(sessionId);
    Date issuedAt = jwt.getIssuedAt();
    return issuedAt.getTime();
	   
} catch (JWTDecodeException exception){
    System.err.println(exception);
    return 0;
}
   }
 
开发者ID:kawansoft,项目名称:aceql-http,代码行数:13,代码来源:JwtSessionConfigurator.java

示例14: shouldBeAbleToProduceAJWTTokenForClients

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
@Test
public void shouldBeAbleToProduceAJWTTokenForClients() throws Exception {
	AuthorityRepresentation authority1 = authority().thatIs().persistent(token).build();
	AuthorityRepresentation authority2 = authority().thatIs().persistent(token).build();

	AudienceRepresentation audience1 = audience().thatIs().persistent(token).build();
	AudienceRepresentation audience2 = audience().thatIs().persistent(token).build();

	ScopeRepresentation scope1 = scope().thatIs().persistent(token).build();
	ScopeRepresentation scope2 = scope().thatIs().persistent(token).build();

	ClientRepresentation representation = client().withToken(token).withAudiences(audience1, audience2).withScopes(scope1, scope2).withAuthorities(authority1, authority2).withClientSecret("ssalR34w3AtX34!33#").withGrantTypes("client_credentials", "password", "refresh_token").build();
	assertThat(clientsClient.create(representation, this.token.getAccessToken())).accepted().withResponseCode(201);

	Result<AccessTokenRepresentation> response = tokensClient.getAccessToken(new ClientCredentials(representation.getClientId(), "ssalR34w3AtX34!33#"));
	assertThat(response).accepted();

	DecodedJWT jwt = JWT.decode(response.getInstance().getAccessToken());

	assertThat(jwt.getAlgorithm()).isEqualTo("RS256");

	assertThat(jwt.getIssuer()).isEqualTo(ISSUER);
	assertThat(jwt.getIssuedAt()).isNotNull();
	assertThat(jwt.getExpiresAt()).isNotNull();
	assertThat(jwt.getId()).isNotNull();
	assertThat(jwt.getAudience()).containsOnly(audience1.getName().toLowerCase(), audience2.getName().toLowerCase());
	assertThat(jwt.getSubject()).isEqualTo(representation.getClientId());

	List<String> clientAuthorities = jwt.getClaim("client_authorities").asList(String.class);
	assertThat(clientAuthorities).containsOnly(authority1.getName(), authority2.getName());

	List<String> userRoles = jwt.getClaim("authorities").asList(String.class);
	assertThat(userRoles).isNull();

	List<String> scopes = jwt.getClaim("scope").asList(String.class);
	assertThat(scopes).containsOnly(scope1.getName(), scope2.getName());

	String clientId = jwt.getClaim("client_id").asString();
	assertThat(clientId).containsSequence(representation.getClientId());
}
 
开发者ID:PatternFM,项目名称:tokamak,代码行数:41,代码来源:JWTAcceptanceTest.java

示例15: shouldBeAbleToProduceAJWTTokenForUsers

import com.auth0.jwt.JWT; //导入方法依赖的package包/类
@Test
public void shouldBeAbleToProduceAJWTTokenForUsers() throws Exception {
	AuthorityRepresentation authority1 = authority().thatIs().persistent(token).build();
	AuthorityRepresentation authority2 = authority().thatIs().persistent(token).build();

	AudienceRepresentation audience1 = audience().thatIs().persistent(token).build();
	AudienceRepresentation audience2 = audience().thatIs().persistent(token).build();

	ScopeRepresentation scope1 = scope().thatIs().persistent(token).build();
	ScopeRepresentation scope2 = scope().thatIs().persistent(token).build();

	ClientRepresentation representation = client().withToken(token).withAudiences(audience1, audience2).withScopes(scope1, scope2).withAuthorities(authority1, authority2).withClientSecret("ssalR34w3AtX34!33#").withGrantTypes("client_credentials", "password", "refresh_token").build();
	assertThat(clientsClient.create(representation, this.token.getAccessToken())).accepted().withResponseCode(201);

	Result<AccessTokenRepresentation> response = tokensClient.getAccessToken(new ClientCredentials(representation.getClientId(), "ssalR34w3AtX34!33#"), account.getUsername(), password);
	assertThat(response).accepted();

	DecodedJWT jwt = JWT.decode(response.getInstance().getAccessToken());

	assertThat(jwt.getAlgorithm()).isEqualTo("RS256");

	assertThat(jwt.getIssuer()).isEqualTo(ISSUER);
	assertThat(jwt.getIssuedAt()).isNotNull();
	assertThat(jwt.getExpiresAt()).isNotNull();
	assertThat(jwt.getId()).isNotNull();
	assertThat(jwt.getAudience()).containsOnly(audience1.getName().toLowerCase(), audience2.getName().toLowerCase());
	assertThat(jwt.getSubject()).isEqualTo(account.getId());

	List<String> clientAuthorities = jwt.getClaim("client_authorities").asList(String.class);
	assertThat(clientAuthorities).containsOnly(authority1.getName(), authority2.getName());

	List<String> userRoles = jwt.getClaim("authorities").asList(String.class);
	assertThat(userRoles).containsExactly(role.getName());

	List<String> scopes = jwt.getClaim("scope").asList(String.class);
	assertThat(scopes).containsOnly(scope1.getName(), scope2.getName());

	String clientId = jwt.getClaim("client_id").asString();
	assertThat(clientId).containsSequence(representation.getClientId());
}
 
开发者ID:PatternFM,项目名称:tokamak,代码行数:41,代码来源:JWTAcceptanceTest.java


注:本文中的com.auth0.jwt.JWT.decode方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。