本文整理汇总了Java中io.jsonwebtoken.MalformedJwtException类的典型用法代码示例。如果您正苦于以下问题:Java MalformedJwtException类的具体用法?Java MalformedJwtException怎么用?Java MalformedJwtException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MalformedJwtException类属于io.jsonwebtoken包,在下文中一共展示了MalformedJwtException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
}
示例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);
}
}
示例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();
}
示例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);
}
示例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();
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
}
示例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);
}
示例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;
}
示例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;
}
示例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());
}
}
示例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;
}
示例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));
}