• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java MalformedJwtException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中io.jsonwebtoken.MalformedJwtException的典型用法代码示例。如果您正苦于以下问题:Java MalformedJwtException类的具体用法?Java MalformedJwtException怎么用?Java MalformedJwtException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: Verify

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
public static boolean Verify(String jwt, String type) throws Exception {
    
    try{
        Claims claims = Jwts.parser()
            .setSigningKey(DatatypeConverter.parseBase64Binary(Parameters.TOKENKEY))
            .parseClaimsJws(jwt).getBody();
        
        //verifica se o issuer é igual ao type
        return claims.getIssuer().equals(type);
        
    } catch (ExpiredJwtException | MalformedJwtException | SignatureException 
            | UnsupportedJwtException | IllegalArgumentException e) {
        System.out.println(e.getMessage());
        return false;
    }
}
 
开发者ID:Montanheiro,项目名称:SistemaAlmoxarifado,代码行数:17,代码来源:Token.java


示例2: parseTokenFromBase64EncodedString

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private Jws<Claims> parseTokenFromBase64EncodedString(final String base64EncodedToken) throws JwtException {
    try {
        return Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {
            @Override
            public byte[] resolveSigningKeyBytes(JwsHeader header, Claims claims) {
                final String identity = claims.getSubject();

                // Get the key based on the key id in the claims
                final String keyId = claims.get(KEY_ID_CLAIM, String.class);
                final Key key = keyService.getKey(keyId);

                // Ensure we were able to find a key that was previously issued by this key service for this user
                if (key == null || key.getKey() == null) {
                    throw new UnsupportedJwtException("Unable to determine signing key for " + identity + " [kid: " + keyId + "]");
                }

                return key.getKey().getBytes(StandardCharsets.UTF_8);
            }
        }).parseClaimsJws(base64EncodedToken);
    } catch (final MalformedJwtException | UnsupportedJwtException | SignatureException | ExpiredJwtException | IllegalArgumentException e) {
        // TODO: Exercise all exceptions to ensure none leak key material to logs
        final String errorMessage = "Unable to validate the access token.";
        throw new JwtException(errorMessage, e);
    }
}
 
开发者ID:apache,项目名称:nifi-registry,代码行数:26,代码来源:JwtService.java


示例3: doGetAuthorizationInfo

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  Collection<?> thisPrincipals = principals.fromRealm(getName());

  if(thisPrincipals != null && !thisPrincipals.isEmpty()) {
    Optional<List<String>> scopes = thisPrincipals.stream().map(p -> {
      try {
        if(p.toString().split("\\.").length == 3) return getScopesFromToken(p.toString());
      } catch(MalformedJwtException e) {
        //ignore
      }

      return null;
    }).filter(s -> s != null).findFirst();

    if (scopes.isPresent()) return new SimpleAuthorizationInfo(Sets.newHashSet(scopes.get()));
  }

  return new SimpleAuthorizationInfo();
}
 
开发者ID:obiba,项目名称:agate,代码行数:21,代码来源:AgateTokenRealm.java


示例4: should_throw_MalformedJwtException_whet_pass_token_without_expiration_and_type

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Test(expected = MalformedJwtException.class)
public void should_throw_MalformedJwtException_whet_pass_token_without_expiration_and_type() throws Exception {
    // Create payload
    Long userId = RandomUtils.nextLong(10, 1000);
    Set<Integer> actions = new HashSet<>();
    actions.add(0);
    Set<String> networkIds = new HashSet<>();
    networkIds.add("string");
    Set<String> deviceTypeIds = new HashSet<>();
    deviceTypeIds.add("string");
    Set<String> deviceIds = new HashSet<>();
    deviceIds.add("string");
    JwtUserPayload.JwtUserPayloadBuilder jwtUserPayloadBuilder = new JwtUserPayload.JwtUserPayloadBuilder();
    JwtUserPayload payload = jwtUserPayloadBuilder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload();

    // Generate key without expiration date and token type
    Map<String, Object> jwtMap = new HashMap<>();
    jwtMap.put(JwtUserPayload.JWT_CLAIM_KEY, payload);
    Claims claims = Jwts.claims(jwtMap);
    String malformedToken = Jwts.builder()
            .setClaims(claims)
            .signWith(SignatureAlgorithm.HS256, jwtSecretService.getJwtSecret())
            .compact();
    jwtClientService.getUserPayload(malformedToken);
}
 
开发者ID:devicehive,项目名称:devicehive-java-server,代码行数:26,代码来源:JwtClientServiceTest.java


示例5: getJwtPayload

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private JwtPayload getJwtPayload(JwtPayload.JwtPayloadBuilder jwtPayloadBuilder, LinkedHashMap<String, Object> payloadMap) {
    Optional<Long> expiration = Optional.ofNullable((Long)payloadMap.get(EXPIRATION));
    Optional<Integer> tokenType = Optional.ofNullable((Integer) payloadMap.get(TOKEN_TYPE));

    if (!tokenType.isPresent() && !expiration.isPresent()) {
        throw new MalformedJwtException("Token type and expiration date should be provided in the token");
    } else {
        if (tokenType.isPresent())
            jwtPayloadBuilder.withTokenType(tokenType.get());
        else
            throw new MalformedJwtException("Token type should be provided in the token");
        if (expiration.isPresent())
            jwtPayloadBuilder.withExpirationDate(new Date(expiration.get()));
        else
            throw new MalformedJwtException("Expiration date should be provided in the token");
        return jwtPayloadBuilder.buildPayload();
    }
}
 
开发者ID:devicehive,项目名称:devicehive-java-server,代码行数:19,代码来源:BaseJwtClientService.java


示例6: parseToken

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private Jws<Claims> parseToken(final String token) {
    if (token != null) {
        try {
            return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
                | SignatureException | IllegalArgumentException e) {
            return null;
        }
    }
    return null;
}
 
开发者ID:vlsidlyarevich,项目名称:Spring-Boot-MongoDB-JWT,代码行数:12,代码来源:JsonWebTokenAuthenticationService.java


示例7: parseClaims

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
/**
 * Parses and validates JWT Token signature.
 * 
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 * 
 */
public Jws<Claims> parseClaims(String signingKey) {
    try {
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
    } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
        logger.error("Invalid JWT Token", ex);
        throw new BadCredentialsException("Invalid JWT token: ", ex);
    } catch (ExpiredJwtException expiredEx) {
        logger.info("JWT Token is expired", expiredEx);
        throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
    }
}
 
开发者ID:Apereo-Learning-Analytics-Initiative,项目名称:OpenLRW,代码行数:19,代码来源:RawAccessJwtToken.java


示例8: parseClaims

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
/**
 * Parses and validates JWT Token signature.
 *
 * @throws BadCredentialsException
 * @throws JwtExpiredTokenException
 *
 */
public Jws<Claims> parseClaims(String signingKey) {
  try {
    return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token);
  } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) {
    logger.error("Invalid JWT Token", ex);
    throw new BadCredentialsException("Invalid JWT token: ", ex);
  } catch (ExpiredJwtException expiredEx) {
    logger.info("JWT Token is expired", expiredEx);
    throw new JwtExpiredTokenException(this, "JWT Token expired", expiredEx);
  }
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:19,代码来源:RawAccessJwtToken.java


示例9: authenticate

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) {
    log.debug("Authenticating: {}", authentication);
    try {
        final String token = authentication.getCredentials().toString();
        final Claims claims = jwtParser.parseClaimsJws(token).getBody();
        checkClaims(claims);
        return new JwtToken(token, claims);
    } catch (ExpiredJwtException | MalformedJwtException | PrematureJwtException | SignatureException | UnsupportedJwtException e) {
        log.warn("{}", e);
        throw new BadCredentialsException(e.getMessage(), e);
    }
}
 
开发者ID:nus-ncl,项目名称:services-in-one,代码行数:14,代码来源:JwtAuthenticationProvider.java


示例10: testAuthenticateMalformedJwtException

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Test
public void testAuthenticateMalformedJwtException() throws Exception {
    final String token = "token";
    doReturn(token).when(authentication).getCredentials();
    doThrow(new MalformedJwtException(null)).when(jwtParser).parseClaimsJws(anyString());

    exception.expect(BadCredentialsException.class);
    exception.expectCause(is(instanceOf(MalformedJwtException.class)));

    jwtAuthenticationProvider.authenticate(authentication);
}
 
开发者ID:nus-ncl,项目名称:services-in-one,代码行数:12,代码来源:JwtAuthenticationProviderTest.java


示例11: getUsernameFromToken

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private String getUsernameFromToken(String authToken) {
    String username = null;
    try {
        username = jwtTokenService.getUsernameFromToken(authToken);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException |
            IllegalArgumentException e) {
        log.error("getUsernameFromToken error, token was malformed: {}", authToken, e);
    }
    return username;
}
 
开发者ID:johanaschan,项目名称:queue-ticket-api,代码行数:11,代码来源:JwtAuthenticationTokenFilter.java


示例12: parseToken

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private Optional<Jws<Claims>> parseToken(final String token) {
    Optional<Jws<Claims>> result = Optional.empty();

    if (Objects.nonNull(token)) {
        try {
            result = Optional.ofNullable(Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token));
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
                | SignatureException | IllegalArgumentException e) {
            log.warn(e.getMessage());
        }
    }

    return result;
}
 
开发者ID:vlsidlyarevich,项目名称:unity,代码行数:15,代码来源:JsonWebTokenAuthenticationService.java


示例13: filter

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	
	String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
	
	if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
		throw new NotAuthorizedException("Authorization header must be provided");
	}
	String token = authorizationHeader.substring("Bearer".length()).trim();
	
	try {
		Role userRole = Role.valueOf(TokenServices.validateToken(token));
		
		List<Role> classRoles = extractRoles(resourceInfo.getResourceClass());
		List<Role> methodRoles = extractRoles(resourceInfo.getResourceMethod());
		
		if (methodRoles.size() > 0) {
			if (!methodRoles.contains(userRole)) {
				requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
			}
		}
		if (classRoles.size() > 0) {
			if (!classRoles.contains(userRole)) {
				requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
			}
		}
	} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
		requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
	}
	
}
 
开发者ID:ard333,项目名称:jax-rs-jjwt,代码行数:32,代码来源:AuthorizationFilter.java


示例14: validateToken

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
public static String validateToken(String token)throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
	Claims claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody();
	String role = null;
	role = claims.get("role").toString();
	Jwts.parser()
		.requireSubject(claims.getSubject())
		.setSigningKey(signingKey)
		.parseClaimsJws(token);
	
	return role;
}
 
开发者ID:ard333,项目名称:jax-rs-jjwt,代码行数:12,代码来源:TokenServices.java


示例15: validateJwt

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
private Map<String, Object> validateJwt(String token, ApiRequest request, JWTPolicyBean config)
        throws ExpiredJwtException, PrematureJwtException, MalformedJwtException, SignatureException, InvalidClaimException {
    JwtParser parser = Jwts.parser()
            .setSigningKey(config.getSigningKey())
            .setAllowedClockSkewSeconds(config.getAllowedClockSkew());

    // Set all claims
    config.getRequiredClaims().stream() // TODO add type variable to allow dates, etc
        .forEach(requiredClaim -> parser.require(requiredClaim.getClaimName(), requiredClaim.getClaimValue()));

    return parser.parse(token, new ConfigCheckingJwtHandler(config));
}
 
开发者ID:apiman,项目名称:apiman-plugins,代码行数:13,代码来源:JWTPolicy.java


示例16: testJwt

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Test
public void testJwt() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException, CertificateException {
    Claims testClaims = Jwts.claims();
    testClaims.put("aud", "test");
    String newJwt = Jwts.builder().setHeaderParam("kid", "test").setClaims(testClaims)
            .signWith(SignatureAlgorithm.RS256, getKey()).compact();
    assertNotNull("could not build jwt using test certificate",newJwt);
    Jws<Claims> jwt = Jwts.parser().setSigningKey(getCertificate().getPublicKey()).parseClaimsJws(newJwt);
    assertNotNull("could not decode jwt using test certificate",jwt);
}
 
开发者ID:gameontext,项目名称:gameon-player,代码行数:11,代码来源:CertificateUtils.java


示例17: readValue

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@SuppressWarnings("unchecked")
protected Map<String, Object> readValue(String val) {
    try {
        return objectMapper.readValue(val, Map.class);
    } catch (IOException e) {
        throw new MalformedJwtException("Unable to read JSON value: " + val, e);
    }
}
 
开发者ID:jwtk,项目名称:jjwt,代码行数:9,代码来源:DefaultJwtParser.java


示例18: getAuthenticationInvalidToken

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
@Test(expected = MalformedJwtException.class)
public void getAuthenticationInvalidToken() {
  String invalidJwt = "invalidJwt";

  this.tokenProvider.getAuthentication(invalidJwt);
}
 
开发者ID:Cobrijani,项目名称:jwt-security-spring-boot-starter,代码行数:7,代码来源:TokenProviderTests.java


示例19: jwtMalformed

import io.jsonwebtoken.MalformedJwtException; //导入依赖的package包/类
public PolicyFailure jwtMalformed(IPolicyContext context, MalformedJwtException e) {
    return createAuthenticationPolicyFailure(context, AUTH_JWT_MALFORMED,
            e.getLocalizedMessage());
}
 
开发者ID:apiman,项目名称:apiman-plugins,代码行数:5,代码来源:PolicyFailureFactory.java



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ZKSplitLog类代码示例发布时间:2022-05-21
下一篇:
Java ChannelProgressiveFuture类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap