本文整理汇总了Java中io.jsonwebtoken.JwtException类的典型用法代码示例。如果您正苦于以下问题:Java JwtException类的具体用法?Java JwtException怎么用?Java JwtException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JwtException类属于io.jsonwebtoken包,在下文中一共展示了JwtException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: parseAndValidate
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
public AuthTokenDetails parseAndValidate(String token) {
AuthTokenDetails authTokenDetails = null;
try {
Claims claims = Jwts.parser().setSigningKey(getSecretKey())
.parseClaimsJws(token)
.getBody();
String userId = claims.getSubject();
String username = (String) claims.get("username");
List<String> roleNames = (List) claims.get("roleNames");
Date expirationDate = claims.getExpiration();
authTokenDetails = new AuthTokenDetails();
authTokenDetails.setId(Long.valueOf(userId));
authTokenDetails.setUsername(username);
authTokenDetails.setRoleNames(roleNames);
authTokenDetails.setExpirationDate(expirationDate);
} catch (JwtException ex) {
logger.error(ex.getMessage(), ex);
}
return authTokenDetails;
}
示例2: getAuthenticationFromToken
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
public String getAuthenticationFromToken(final String base64EncodedToken) throws JwtException {
// The library representations of the JWT should be kept internal to this service.
try {
final Jws<Claims> jws = parseTokenFromBase64EncodedString(base64EncodedToken);
if (jws == null) {
throw new JwtException("Unable to parse token");
}
// Additional validation that subject is present
if (StringUtils.isEmpty(jws.getBody().getSubject())) {
throw new JwtException("No subject available in token");
}
// TODO: Validate issuer against active IdentityProvider?
if (StringUtils.isEmpty(jws.getBody().getIssuer())) {
throw new JwtException("No issuer available in token");
}
return jws.getBody().getSubject();
} catch (JwtException e) {
logger.debug("The Base64 encoded JWT: " + base64EncodedToken);
final String errorMessage = "There was an error validating the JWT";
logger.error(errorMessage, e);
throw e;
}
}
示例3: parseTokenFromBase64EncodedString
import io.jsonwebtoken.JwtException; //导入依赖的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);
}
}
示例4: authenticate
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public AuthenticationResponse authenticate(AuthenticationRequest authenticationRequest) throws InvalidCredentialsException, IdentityAccessException {
if (authenticationRequest == null) {
logger.info("Cannot authenticate null authenticationRequest, returning null.");
return null;
}
final Object credentials = authenticationRequest.getCredentials();
String jwtAuthToken = credentials != null && credentials instanceof String ? (String) credentials : null;
if (credentials == null) {
logger.info("JWT not found in authenticationRequest credentials, returning null.");
return null;
}
try {
final String jwtPrincipal = jwtService.getAuthenticationFromToken(jwtAuthToken);
return new AuthenticationResponse(jwtPrincipal, jwtPrincipal, expiration, issuer);
} catch (JwtException e) {
throw new InvalidAuthenticationException(e.getMessage(), e);
}
}
示例5: Can_fail_parse_a_jwt_token
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Test
public void Can_fail_parse_a_jwt_token() throws JwtInvalidTokenException {
final String token = someString();
final JwtParser parser = mock(JwtParser.class);
final JwtParser secretParser = mock(JwtParser.class);
final JwtException exception = new JwtException(someString());
// Given
given(parserFactory.create()).willReturn(parser);
given(parser.setSigningKey(publicKey)).willReturn(secretParser);
given(secretParser.parseClaimsJws(token)).willThrow(exception);
expectedException.expect(JwtInvalidTokenException.class);
expectedException.expectCause(is(exception));
// When
decryptor.decrypt(token, Object.class);
}
示例6: doFilterInternal
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader(configurerParams.getHeader());
if (header == null || !header.startsWith(configurerParams.getPrefix())) {
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = null;
try {
authentication = getAuthentication(request);
} catch (JwtException | IllegalArgumentException e) {
e.printStackTrace();
}
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
示例7: getAuthentication
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) throws JwtException, IllegalArgumentException {
String token = request.getHeader(configurerParams.getHeader());
if (token != null) {
String user = Jwts.parser()
.setSigningKey(configurerParams.getSecret().getBytes())
.parseClaimsJws(token.replace(configurerParams.getPrefix(), ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
}
return null;
}
return null;
}
示例8: authenticate
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public void authenticate(final JsonObject authRequest, final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {
final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS);
vertx.eventBus().send(AuthenticationConstants.EVENT_BUS_ADDRESS_AUTHENTICATION_IN, authRequest, options, reply -> {
if (reply.succeeded()) {
JsonObject result = (JsonObject) reply.result().body();
String token = result.getString(AuthenticationConstants.FIELD_TOKEN);
log.debug("received token [length: {}] in response to authentication request", token.length());
try {
Jws<Claims> expandedToken = tokenValidator.expand(result.getString(AuthenticationConstants.FIELD_TOKEN));
authenticationResultHandler.handle(Future.succeededFuture(new HonoUserImpl(expandedToken, token)));
} catch (JwtException e) {
authenticationResultHandler.handle(Future.failedFuture(e));
}
} else {
authenticationResultHandler.handle(Future.failedFuture(reply.cause()));
}
});
}
示例9: isValid
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public boolean isValid(final String token, final String tenantId, final String deviceId) {
try {
Jwts.parser()
.setSigningKey(key)
.requireSubject(Objects.requireNonNull(deviceId))
.require("ten", Objects.requireNonNull(tenantId))
.setAllowedClockSkewSeconds(10)
.parse(token);
return true;
} catch (JwtException e) {
// token is invalid for some reason
LOG.debug("failed to validate token", e);
return false;
}
}
示例10: doFilter
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String authHeaderVal = httpRequest.getHeader(authHeader);
if (null==authHeaderVal)
{
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
try
{
JwtUser jwtUser = jwtTokenService.getUser(authHeaderVal);
httpRequest.setAttribute("jwtUser", jwtUser);
}
catch(JwtException e)
{
httpResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
return;
}
chain.doFilter(httpRequest, httpResponse);
}
示例11: parseAndValidate
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
public AuthTokenDetailsDTO parseAndValidate(String token) {
AuthTokenDetailsDTO authTokenDetailsDTO = null;
try {
Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody();
String userId = claims.getSubject();
String email = (String) claims.get("email");
List<String> roleNames = (List<String>) claims.get("roles");
Date expirationDate = claims.getExpiration();
authTokenDetailsDTO = new AuthTokenDetailsDTO();
authTokenDetailsDTO.userId = userId;
authTokenDetailsDTO.email = email;
authTokenDetailsDTO.roleNames = roleNames;
authTokenDetailsDTO.expirationDate = expirationDate;
} catch (JwtException ex) {
System.out.println(ex);
}
return authTokenDetailsDTO;
}
示例12: invalidate
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
public static Boolean invalidate(String jwt) {
if (jwt == null)
return false;
String subject;
try {
subject = getSubject(jwt);
}
catch(JwtException e) {
return false;
}
if (!userToKeyMap.containsKey(subject))
return false;
userToKeyMap.remove(subject);
return true;
}
示例13: refreshTokenRequest
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public Response refreshTokenRequest(JwtRefreshTokenVO requestTokenVO) {
hiveValidator.validate(requestTokenVO);
JwtPayload payload;
try {
payload = tokenService.getPayload(requestTokenVO.getRefreshToken());
} catch (JwtException e) {
logger.error(e.getMessage());
return ResponseFactory.response(UNAUTHORIZED);
}
if (!payload.getTokenType().equals(TokenType.REFRESH.getId())) {
logger.warn("JwtToken: refresh token is not valid");
return ResponseFactory.response(UNAUTHORIZED, new ErrorResponse(UNAUTHORIZED.getStatusCode(),
INVALID_TOKEN_TYPE));
}
if (payload.getExpiration().before(timestampService.getDate())) {
logger.warn("JwtToken: refresh token has expired");
return ResponseFactory.response(UNAUTHORIZED, new ErrorResponse(UNAUTHORIZED.getStatusCode(),
EXPIRED_TOKEN));
}
return payload.isUserPayload() ? getRefreshResponse((JwtUserPayload) payload) :
getRefreshResponse((JwtPluginPayload) payload);
}
示例14: settingsPictureTokenGet
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
public ResponseEntity<Object> settingsPictureTokenGet(@RequestParam(value = "token", required = false) String token) throws ApiException{
// System.out.println("token:" + token);
if(token==null || token.trim().length()==0){
//throw new ApiException(403, "Invalid token");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
Long clientUserId = 0L;
try{
Claims claims = JwtCodec.decode(token);
clientUserId = Long.parseLong(claims.getSubject());
} catch(JwtException e){
//throw new ApiException(403, "Access denied");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
com.jrtechnologies.yum.data.entity.User userDAO = userRepo.findById(clientUserId);
if(!userDAO.hasPicture()){
//throw new ApiException(404, "No picture");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(userDAO.getPicture());
return ResponseEntity
.ok()
.contentLength(userDAO.getPictureLength())
.contentType(MediaType.parseMediaType("image/jpeg"))
.body(new InputStreamResource(inputStream));
}
示例15: usersIdPictureGet
import io.jsonwebtoken.JwtException; //导入依赖的package包/类
@Override
//@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> usersIdPictureGet(@RequestParam(value = "token", required = true) String token, @PathVariable("id") Integer id)throws ApiException {
com.jrtechnologies.yum.data.entity.User user = userRepo.findById(id);
// System.out.println("token:"+token);
// System.out.println("id:"+id);
if(user==null){
//throw new ApiException(404, "User not found");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
if(token==null || token.trim().length()==0){
//throw new ApiException(400, "No token")
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Long clientUserId = 0L;
try{
Claims claims = JwtCodec.decode(token);
clientUserId = Long.parseLong(claims.getSubject());
} catch(JwtException e){
//throw new ApiException(403, "Access denied");
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
if(!user.hasPicture()){
//throw new ApiException(404, "No picture");
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(user.getPicture());
return ResponseEntity
.ok()
.contentLength(user.getPictureLength())
.contentType(MediaType.parseMediaType("image/jpeg"))
.body(new InputStreamResource(inputStream));
}