Java 类io.jsonwebtoken.JwtException 实例源码

项目:SpringBootStudy    文件:JsonWebTokenUtility.java   
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;
}
项目:nifi-registry    文件:JwtService.java   
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;
    }
}
项目:nifi-registry    文件:JwtService.java   
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);
    }
}
项目:nifi-registry    文件:JwtIdentityProvider.java   
@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);
    }
}
项目:smt-spring-security-parent    文件:JJwtDecryptorTest.java   
@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);
}
项目:personal-garage-service    文件:JWTAuthorizationFilter.java   
@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);
}
项目:personal-garage-service    文件:JWTAuthorizationFilter.java   
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;
}
项目:hono    文件:HonoSaslAuthenticatorFactory.java   
@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()));
        }
    });

}
项目:hono    文件:RegistrationAssertionHelperImpl.java   
@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;
    }
}
项目:spring-boot-jwt-example    文件:JwtFilter.java   
@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);
}
项目:trivia-microservices    文件:JsonWebTokenUtility.java   
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;
}
项目:WebAPI    文件:TokenManager.java   
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;
}
项目:devicehive-java-server    文件:JwtTokenResourceImpl.java   
@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);
}
项目:yum    文件:SettingsApiController.java   
@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));

    }
项目:yum    文件:UsersApiController.java   
@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));
    }
项目:spring-boot-jwt    文件:JwtTokenProvider.java   
public boolean validateToken(String token) {
  try {
    Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
    return true;
  } catch (JwtException | IllegalArgumentException e) {
    throw new CustomException("Expired or invalid JWT token", HttpStatus.INTERNAL_SERVER_ERROR);
  }
}
项目:springuni-particles    文件:PersistentJwtTokenBasedRememberMeServices.java   
@Override
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
  try {
    Claims claims = Jwts.parser()
        .setSigningKey(getKey())
        .parseClaimsJws(cookieValue)
        .getBody();

    return new String[] { claims.getId(), claims.getSubject() };
  } catch (JwtException e) {
    LOGGER.warn(e.getMessage());
    throw new InvalidCookieException(e.getMessage());
  }
}
项目:ServiceComb-Company-WorkShop    文件:JwtTokenStore.java   
@Override
public String parse(String token) {
  try {
    return Jwts.parser()
        .setSigningKey(secretKey)
        .parseClaimsJws(token)
        .getBody()
        .getSubject();
  } catch (JwtException | IllegalArgumentException e) {
    throw new TokenException(e);
  }
}
项目:nifi-registry    文件:JwtService.java   
/**
 * Generates a signed JWT token from the provided IdentityProvider AuthenticationResponse
 *
 * @param authenticationResponse an instance issued by an IdentityProvider after identity claim has been verified as authentic
 * @return a signed JWT containing the user identity and the identity provider, Base64-encoded
 * @throws JwtException if there is a problem generating the signed token
 */
public String generateSignedToken(final AuthenticationResponse authenticationResponse) throws JwtException {
    if (authenticationResponse == null) {
        throw new IllegalArgumentException("Cannot generate a JWT for a null authenticationResponse");
    }

    return generateSignedToken(
            authenticationResponse.getIdentity(),
            authenticationResponse.getUsername(),
            authenticationResponse.getIssuer(),
            authenticationResponse.getIssuer(),
            authenticationResponse.getExpiration());
}
项目:nifi-registry    文件:AccessResource.java   
private String createAccessToken(IdentityProvider identityProvider, AuthenticationRequest authenticationRequest)
        throws InvalidCredentialsException, AdministrationException {

    final AuthenticationResponse authenticationResponse;

    try {
        authenticationResponse = identityProvider.authenticate(authenticationRequest);
        final String token = jwtService.generateSignedToken(authenticationResponse);
        return token;
    } catch (final IdentityAccessException | JwtException e) {
        throw new AdministrationException(e.getMessage());
    }

}
项目:SA-starter-kit    文件:StatelessAuthenticationFilter.java   
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    try {
        Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) req);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(req, res);
        SecurityContextHolder.getContext().setAuthentication(null);
    } catch (AuthenticationException | JwtException e) {
        SecurityContextHolder.clearContext();
        ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
项目:angular2-spring-boot    文件:TokenAuthenticationService.java   
public Authentication getExistingAuthentication(final HttpServletRequest request) {
    final String jwtToken = request.getHeader(AUTH_HEADER_NAME);
    if (jwtToken != null) {
        try {
            final User user = tokenHandler.parseUserFromJwtToken(jwtToken);
            return new UserAuthentication(user);
        } catch (final UsernameNotFoundException | JwtException e) {
            return null;
        }
    }

    return null;
}
项目:chat-rooms    文件:TokenHandler.java   
/**
 * Parse token details from provided jwt.
 *
 * @param rawToken raw jwt, can contain {@value BEARER} at the start of it.
 * @return decoded token details optional.
 */
public Optional<DecodedToken> parse(String rawToken) {
    if (StringUtils.isBlank(rawToken)) {
        return Optional.empty();
    }

    String token = rawToken
            .replaceFirst(BEARER, "");

    try {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();

        String version = Optional
                .ofNullable(claims.get(VERSION, String.class))
                .orElseThrow(() -> new ChatException("Token must include version", HttpStatus.BAD_REQUEST));

        return Optional.of(new DecodedToken(claims.getSubject(), UUID.fromString(version)));

    } catch (JwtException e) {
        LOGGER.error("Could not parse token: {}", token, e);

        return Optional.empty();
    }
}
项目:hono    文件:JwtHelper.java   
/**
 * Gets the value of the <em>exp</em> claim of a JWT.
 * 
 * @param token The token.
 * @return The expiration.
 * @throws NullPointerException if the token is {@code null}.
 * @throws IllegalArgumentException if the given token contains no <em>exp</em> claim.
 */
public static final Date getExpiration(final String token) {

    if (token == null) {
        throw new NullPointerException("token must not be null");
    }

    final AtomicReference<Date> result = new AtomicReference<>();

    try {
        Jwts.parser().setSigningKeyResolver(new SigningKeyResolverAdapter() {

            @SuppressWarnings("rawtypes")
            @Override
            public Key resolveSigningKey(JwsHeader header, Claims claims) {
                Date exp = claims.getExpiration();
                if (exp != null) {
                    result.set(exp);
                }
                return DUMMY_KEY;
            }
        }).parse(token);
    } catch (JwtException e) {
        // expected since we do not know the signing key
    }

    if (result.get() == null) {
        throw new IllegalArgumentException("token contains no exp claim");
    } else {
        return result.get();
    }
}
项目:microservices    文件:JwtUtil.java   
/**
 * Tries to parse specified String as a JWT token. If successful, returns User object with username, id
 * and role prefilled (extracted from token).
 * If unsuccessful (token is invalid or not containing all required user properties), throws exception.
 *
 * @param token the JWT token to parse
 * @return the User object extracted from specified token if a token is valid
 * @throws AuthenticationException if a token is invalid
 */
public User parseToken(final String token) throws AuthenticationException {
    try {
        final Claims body = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();

        return new User((String) body.get("userId"), body.getSubject(), (Set<String>) body.get("role"));
    } catch (JwtException | ClassCastException e) {
        throw (JwtTokenMalformedException) new JwtTokenMalformedException("JWT token is not valid").initCause(e);
    }
}
项目:WebAPI    文件:JwtAuthFilter.java   
@Override
protected JwtAuthToken createToken(ServletRequest request, ServletResponse response) throws Exception {
  String jwt = TokenManager.extractToken(request);
  String subject;
  try {
    subject = TokenManager.getSubject(jwt);
  } catch (JwtException e) {
    throw new AuthenticationException(e);
  }

  return new JwtAuthToken(subject);
}
项目:jjwt    文件:EllipticCurveProvider.java   
/**
 * Returns the expected signature byte array length (R + S parts) for
 * the specified ECDSA algorithm.
 *
 * @param alg The ECDSA algorithm. Must be supported and not
 *            {@code null}.
 *
 * @return The expected byte array length for the signature.
 *
 * @throws JwtException If the algorithm is not supported.
 */
public static int getSignatureByteArrayLength(final SignatureAlgorithm alg)
        throws JwtException {

    switch (alg) {
        case ES256: return 64;
        case ES384: return 96;
        case ES512: return 132;
        default:
            throw new JwtException("Unsupported Algorithm: " + alg.name());
    }
}
项目:jjwt    文件:EllipticCurveSigner.java   
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException, JwtException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return transcodeSignatureToConcat(sig.sign(), getSignatureByteArrayLength(alg));
}
项目:Biliomi    文件:AuthRestService.java   
@POST
@PermitAll
@Path("/refresh")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response refresh(RestRefreshTokenRequest refreshTokenRequest) throws InvalidKeySpecException, NoSuchAlgorithmException {
  RestAuthorizationResponse authorizationResponse = new RestAuthorizationResponse();

  // Check if username and password are defined in request
  if (refreshTokenRequest == null || StringUtils.isEmpty(refreshTokenRequest.getRefreshToken())) {
    authorizationResponse.setMessage(RestAuthorizationResponse.getFaultLoginEmptyMsg());
    return Responses.ok(authorizationResponse);
  }

  ApiSecuritySettings settings = settingsDao.getSettings(ApiSecuritySettings.class);

  // Decode refresh token
  Claims claims;
  try {
    claims = jwtGenerator.validateToken(settings.getSecret(), refreshTokenRequest.getRefreshToken(), TokenType.REFRESH);
  } catch (JwtException e) {
    authorizationResponse.setMessage(e.getMessage());
    return Responses.ok(authorizationResponse);
  }

  // Search for credentials by token subject (user display name, exact)
  User user = settings.getLogins().stream()
      .filter(apiLogin -> apiLogin.getUser().getUsername().equals(claims.getSubject()))
      .map(ApiLogin::getUser)
      .findFirst()
      .orElse(null);

  // Check if user was found within credentialsSets
  if (user == null) {
    authorizationResponse.setMessage(RestAuthorizationResponse.getFaultInvalidTokenMsg());
    return Responses.ok(authorizationResponse);
  }

  String token = jwtGenerator.generateAuthorizationToken(settings.getSecret(), user);
  String refreshToken = jwtGenerator.generateRefreshToken(settings.getSecret(), user);
  authorizationResponse.setMessage(RestAuthorizationResponse.getLoginOkMsg());
  authorizationResponse.setAuthorizationToken(token);
  authorizationResponse.setRefreshToken(refreshToken);
  return Responses.ok(authorizationResponse);
}
项目:spring-demo-jwt    文件:ExceptionController.java   
@ExceptionHandler(JwtException.class)
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ResponseBody
public ApiError jwtException(JwtException exception) {

    String message;

    if (exception instanceof ExpiredJwtException) {

        message = "Expired token";

    } else {

        message = "Invalid token";
    }

    return new ApiError(message);
}
项目:WebAPI    文件:TokenManager.java   
public static String getSubject(String jwt) throws JwtException {    
  return getBody(jwt).getSubject();
}
项目:jjwt    文件:EllipticCurveProvider.java   
/**
 * Transcodes the JCA ASN.1/DER-encoded signature into the concatenated
 * R + S format expected by ECDSA JWS.
 *
 * @param derSignature The ASN1./DER-encoded. Must not be {@code null}.
 * @param outputLength The expected length of the ECDSA JWS signature.
 *
 * @return The ECDSA JWS encoded signature.
 *
 * @throws JwtException If the ASN.1/DER signature format is invalid.
 */
public static byte[] transcodeSignatureToConcat(final byte[] derSignature, int outputLength)
        throws JwtException {

    if (derSignature.length < 8 || derSignature[0] != 48) {
        throw new JwtException("Invalid ECDSA signature format");
    }

    int offset;
    if (derSignature[1] > 0) {
        offset = 2;
    } else if (derSignature[1] == (byte) 0x81) {
        offset = 3;
    } else {
        throw new JwtException("Invalid ECDSA signature format");
    }

    byte rLength = derSignature[offset + 1];

    int i = rLength;
    while ((i > 0)
            && (derSignature[(offset + 2 + rLength) - i] == 0))
        i--;

    byte sLength = derSignature[offset + 2 + rLength + 1];

    int j = sLength;
    while ((j > 0)
            && (derSignature[(offset + 2 + rLength + 2 + sLength) - j] == 0))
        j--;

    int rawLen = Math.max(i, j);
    rawLen = Math.max(rawLen, outputLength / 2);

    if ((derSignature[offset - 1] & 0xff) != derSignature.length - offset
            || (derSignature[offset - 1] & 0xff) != 2 + rLength + 2 + sLength
            || derSignature[offset] != 2
            || derSignature[offset + 2 + rLength] != 2) {
        throw new JwtException("Invalid ECDSA signature format");
    }

    final byte[] concatSignature = new byte[2 * rawLen];

    System.arraycopy(derSignature, (offset + 2 + rLength) - i, concatSignature, rawLen - i, i);
    System.arraycopy(derSignature, (offset + 2 + rLength + 2 + sLength) - j, concatSignature, 2 * rawLen - j, j);

    return concatSignature;
}
项目:jjwt    文件:EllipticCurveProvider.java   
/**
 * Transcodes the ECDSA JWS signature into ASN.1/DER format for use by
 * the JCA verifier.
 *
 * @param jwsSignature The JWS signature, consisting of the
 *                     concatenated R and S values. Must not be
 *                     {@code null}.
 *
 * @return The ASN.1/DER encoded signature.
 *
 * @throws JwtException If the ECDSA JWS signature format is invalid.
 */
public static byte[] transcodeSignatureToDER(byte[] jwsSignature)
        throws JwtException {

    int rawLen = jwsSignature.length / 2;

    int i = rawLen;

    while((i > 0)
            && (jwsSignature[rawLen - i] == 0))
        i--;

    int j = i;

    if (jwsSignature[rawLen - i] < 0) {
        j += 1;
    }

    int k = rawLen;

    while ((k > 0)
            && (jwsSignature[2 * rawLen - k] == 0))
        k--;

    int l = k;

    if (jwsSignature[2 * rawLen - k] < 0) {
        l += 1;
    }

    int len = 2 + j + 2 + l;

    if (len > 255) {
        throw new JwtException("Invalid ECDSA signature format");
    }

    int offset;

    final byte derSignature[];

    if (len < 128) {
        derSignature = new byte[2 + 2 + j + 2 + l];
        offset = 1;
    } else {
        derSignature = new byte[3 + 2 + j + 2 + l];
        derSignature[1] = (byte) 0x81;
        offset = 2;
    }

    derSignature[0] = 48;
    derSignature[offset++] = (byte) len;
    derSignature[offset++] = 2;
    derSignature[offset++] = (byte) j;

    System.arraycopy(jwsSignature, rawLen - i, derSignature, (offset + j) - i, i);

    offset += j;

    derSignature[offset++] = 2;
    derSignature[offset++] = (byte) l;

    System.arraycopy(jwsSignature, 2 * rawLen - k, derSignature, (offset + l) - k, k);

    return derSignature;
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 生成Token
 *
 * @param claims
 * @param expiration
 * @param secretKey
 * @return
 */
public static String generateToken(Claims claims, Long expiration, String secretKey) throws JwtException {
    return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate(expiration))
            .signWith(SignatureAlgorithm.HS512, secretKey)
            .compact();
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 从Token获取信息
 *
 * @param token
 * @param secretKey
 * @return
 */
public static Claims getClaims(String token, String secretKey) throws JwtException {
    return Jwts.parser()
            .setSigningKey(secretKey)
            .parseClaimsJws(token)
            .getBody();
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 从Token获取受众
 *
 * @param token
 * @param secretKey
 * @return
 */
public static String getAudience(String token, String secretKey) throws JwtException {
    return getClaims(token, secretKey).getAudience();
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 从Token获取受众
 *
 * @param claims
 * @return
 */
public static String getAudience(Claims claims) throws JwtException {
    return claims.getAudience();
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 有效期是否期满,过期为true
 *
 * @param token
 * @param secretKey
 * @return
 */
public static Boolean isTokenExpired(String token, String secretKey) throws JwtException {
    Claims claims = getClaims(token, secretKey);
    Date expiration = claims.getExpiration();
    return expiration.before(new Date());
}
项目:xq_seckill_microservice    文件:JwtTokenUtil.java   
/**
 * 有效期是否期满,过期为true
 *
 * @param claims
 * @return
 */
public static Boolean isTokenExpired(Claims claims) throws JwtException {
    Date expiration = claims.getExpiration();
    return expiration.before(new Date());
}