Java Code Examples for io.jsonwebtoken.JwtException

The following examples show how to use io.jsonwebtoken.JwtException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: incubator-iotdb   Source File: OpenIdAuthorizer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * So not with the token!
 * @param token Usually the JWT but could also be just the name of the user ({@link #getUsername(String)}.
 * @return true if the user is an admin
 */
@Override
boolean isAdmin(String token) {
    Claims claims;
    if (this.loggedClaims.containsKey(token)) {
        // This is a username!
        claims = this.loggedClaims.get(token);
    } else {
        // Its a token
        try {
            claims = validateToken(token);
        } catch (JwtException e) {
            logger.warn("Unable to validate token {}!", token, e);
            return false;
        }
    }
    // Get available roles (from keycloack)
    List<String> availableRoles = ((Map<String, List<String>>) claims.get("realm_access")).get("roles");
    if (!availableRoles.contains(IOTDB_ADMIN_ROLE_NAME)) {
        logger.warn("Given Token has no admin rights, is there a ROLE with name {} in 'realm_access' role set?", IOTDB_ADMIN_ROLE_NAME);
        return false;
    }
    return true;
}
 
Example 2
Source Project: nifi   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
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 Integer keyId = claims.get(KEY_ID_CLAIM, Integer.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 | AdministrationException 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);
    }
}
 
Example 3
Source Project: localization_nifi   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
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 registry?
        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;
    }
}
 
Example 4
Source Project: localization_nifi   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
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 Integer keyId = claims.get(KEY_ID_CLAIM, Integer.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 | AdministrationException 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);
    }
}
 
Example 5
Source Project: localization_nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGenerateTokenWithMissingKey() throws Exception {
    // Arrange
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken("alopresto",
            EXPIRATION_MILLIS,
            "MockIdentityProvider");
    logger.debug("Generating token for " + loginAuthenticationToken);

    // Set up the bad key service
    KeyService missingKeyService = Mockito.mock(KeyService.class);
    when(missingKeyService.getOrCreateKey(anyString())).thenThrow(new AdministrationException("Could not find a "
            + "key for that user"));
    jwtService = new JwtService(missingKeyService);

    // Act
    jwtService.generateSignedToken(loginAuthenticationToken);

    // Assert
    // Should throw exception
}
 
Example 6
Source Project: nifi-registry   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 7
Source Project: nifi-registry   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 8
Source Project: nifi-registry   Source File: JwtIdentityProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 9
Source Project: trellis   Source File: FederatedJwtAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Claims parse(final String credentials) {
    // Parse the JWT claims
    return Jwts.parserBuilder().setSigningKeyResolver(new SigningKeyResolverAdapter() {
        @Override
        public Key resolveSigningKey(final JwsHeader header, final Claims claims) {
            if (header.getKeyId() == null) {
                throw new JwtException("Missing Key ID (kid) header field");
            }
            try {
                if (keyIds.contains(header.getKeyId()) && keyStore.containsAlias(header.getKeyId())) {
                    return keyStore.getCertificate(header.getKeyId()).getPublicKey();
                }
            } catch (final KeyStoreException ex) {
                throw new SecurityException("Error retrieving key from keystore", ex);
            }
            throw new SecurityException("Could not locate key in keystore: " + header.getKeyId());
        }
    }).build().parseClaimsJws(credentials).getBody();
}
 
Example 10
Source Project: trellis   Source File: JwksAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Claims parse(final String token) {
    return Jwts.parserBuilder().setSigningKeyResolver(new SigningKeyResolverAdapter() {
        @Override
        public Key resolveSigningKey(final JwsHeader header, final Claims claims) {
            final String keyid = header.getKeyId();
            if (keyid == null) {
                throw new JwtException("Missing Key ID (kid) header field");
            }
            if (keys.containsKey(keyid)) {
                return keys.get(keyid);
            }
            throw new SecurityException("Could not locate key: " + keyid);
        }
    }).build().parseClaimsJws(token).getBody();
}
 
Example 11
Source Project: nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldLogOutUser() throws Exception {
    // Arrange
    expectedException.expect(JwtException.class);
    expectedException.expectMessage("Unable to validate the access token.");

    // Token expires in 60 seconds
    final int EXPIRATION_MILLIS = 60000;
    LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken(DEFAULT_IDENTITY,
            EXPIRATION_MILLIS,
            "MockIdentityProvider");
    logger.debug("Generating token for " + loginAuthenticationToken);

    // Act
    String token = jwtService.generateSignedToken(loginAuthenticationToken);
    logger.debug("Generated JWT: " + token);
    String authID = jwtService.getAuthenticationFromToken(token);
    assertEquals(DEFAULT_IDENTITY, authID);
    logger.debug("Logging out user: " + DEFAULT_IDENTITY);
    jwtService.logOut(token);
    logger.debug("Logged out user: " + DEFAULT_IDENTITY);
    jwtService.getAuthenticationFromToken(token);

    // Assert
    // Should throw exception when user is not found
}
 
Example 12
Source Project: auto-subtitle-tool   Source File: ApiUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取当前用户id
 */
public static Long currentUid(String jwt) {
    Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes());
    Long userId = null;
    Date expireDate = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getExpiration();
    if (expireDate.getTime() < new Date().getTime()) {
        throw new LoginException(ErrorCodeEnum.AUTHENTICATION_EXPIRE);
    }
    try {
        userId = Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getId());
    } catch (JwtException e) {
        throw new LoginException(ErrorCodeEnum.UNAUTHORIZED);
    }
    return userId;
}
 
Example 13
Source Project: spring-boot-security-rest   Source File: JwtTokenProvider.java    License: MIT License 5 votes vote down vote up
public boolean validateToken(String token) {
    try {
        Jws<Claims> claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        if (claims.getBody().getExpiration().before(new Date())) {
            return false;
        }
        return true;
    } catch (JwtException | IllegalArgumentException e) {
        throw new JwtException("Expired or invalid JWT token");
    }
}
 
Example 14
Source Project: nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGetAuthenticationForTokenFromEmptyIdentityProvider() throws Exception {
    // Arrange
    String token = NO_ISSUER_TOKEN;

    // Act
    String identity = jwtService.getAuthenticationFromToken(token);
    logger.debug("Extracted identity: " + identity);

    // Assert
    // Should fail
}
 
Example 15
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 16
Source Project: MeetingFilm   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截jwt相关异常
 */
@ExceptionHandler(JwtException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip jwtException(JwtException e) {
    return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
}
 
Example 17
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 18
Source Project: MeetingFilm   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截jwt相关异常
 */
@ExceptionHandler(JwtException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip jwtException(JwtException e) {
    return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
}
 
Example 19
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 20
Source Project: MeetingFilm   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截jwt相关异常
 */
@ExceptionHandler(JwtException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip jwtException(JwtException e) {
    return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
}
 
Example 21
Source Project: nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Ignore("Not yet implemented")
@Test(expected = JwtException.class)
public void testShouldNotGetAuthenticationForTokenFromUnknownIdentityProvider() throws Exception {
    // Arrange
    String token = UNKNOWN_ISSUER_TOKEN;

    // Act
    String identity = jwtService.getAuthenticationFromToken(token);
    logger.debug("Extracted identity: " + identity);

    // Assert
    // Should fail
}
 
Example 22
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 23
Source Project: MeetingFilm   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截jwt相关异常
 */
@ExceptionHandler(JwtException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip jwtException(JwtException e) {
    return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
}
 
Example 24
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 25
Source Project: MeetingFilm   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截jwt相关异常
 */
@ExceptionHandler(JwtException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip jwtException(JwtException e) {
    return new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage());
}
 
Example 26
Source Project: MeetingFilm   Source File: AuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
        chain.doFilter(request, response);
        return;
    }
    final String requestHeader = request.getHeader(jwtProperties.getHeader());
    String authToken = null;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = jwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return;
    }
    chain.doFilter(request, response);
}
 
Example 27
Source Project: WebStack-Guns   Source File: RestApiInteceptor.java    License: MIT License 5 votes vote down vote up
private boolean check(HttpServletRequest request, HttpServletResponse response) {
    if (request.getServletPath().equals(JwtConstants.AUTH_PATH)) {
        return true;
    }
    final String requestHeader = request.getHeader(JwtConstants.AUTH_HEADER);
    String authToken;
    if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
        authToken = requestHeader.substring(7);

        //验证token是否过期,包含了验证jwt是否正确
        try {
            boolean flag = JwtTokenUtil.isTokenExpired(authToken);
            if (flag) {
                RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
                return false;
            }
        } catch (JwtException e) {
            //有异常就是token解析失败
            RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
            return false;
        }
    } else {
        //header没有带Bearer字段
        RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
        return false;
    }
    return true;
}
 
Example 28
Source Project: nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGetAuthenticationForImposterToken() throws Exception {
    // Arrange
    String token = IMPOSTER_SIGNED_TOKEN;

    // Act
    String identity = jwtService.getAuthenticationFromToken(token);
    logger.debug("Extracted identity: " + identity);

    // Assert
    // Should fail
}
 
Example 29
Source Project: scaffold   Source File: JwtTokenStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String validate(String token) {
  try {
    return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
  } catch (JwtException | IllegalArgumentException e) {
    LOGGER.info("validateToken token : " + token + " failed", e);
  }
  return null;
}
 
Example 30
Source Project: localization_nifi   Source File: JwtServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = JwtException.class)
public void testShouldNotGetAuthenticationForInvalidToken() throws Exception {
    // Arrange
    String token = INVALID_SIGNED_TOKEN;

    // Act
    String identity = jwtService.getAuthenticationFromToken(token);
    logger.debug("Extracted identity: " + identity);

    // Assert
    // Should fail
}