@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
@Override public byte[] sign(byte[] data) { try { return doSign(data); } catch (InvalidKeyException e) { throw new SignatureException("Invalid Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (java.security.SignatureException e) { throw new SignatureException("Unable to calculate signature using Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (JwtException e) { throw new SignatureException("Unable to convert signature to JOSE format. " + e.getMessage(), e); } }
accessStatus.setMessage("You are already logged in."); } catch (JwtException e) { throw new InvalidAuthenticationException(e.getMessage(), e);
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final JwtAuthenticationRequestToken request = (JwtAuthenticationRequestToken) authentication; try { final String jwtPrincipal = jwtService.getAuthenticationFromToken(request.getToken()); final String mappedIdentity = mapIdentity(jwtPrincipal); final NiFiUser user = new Builder().identity(mappedIdentity).groups(getUserGroups(mappedIdentity)).clientAddress(request.getClientAddress()).build(); return new NiFiAuthenticationToken(new NiFiUserDetails(user)); } catch (JwtException e) { throw new InvalidAuthenticationException(e.getMessage(), e); } }
private Optional<Principal> authenticate(final String token) { try { return authenticator.authenticate(token); } catch (final SecurityException ex) { LOGGER.debug("Invalid signature, ignoring JWT token: {}", ex.getMessage()); } catch (final JwtException ex) { LOGGER.warn("Problem reading JWT value: {}", ex.getMessage()); } return empty(); }
/** * Check JWT signature and get claims. * * @param jwt JSON Web Token * @param rsaVerifier Public key to check JWT signature * @return JWT Claims */ private Jws<Claims> getClaims(String jwt, PublicKey rsaVerifier) throws JwtProcessingException { try { return parser.setSigningKey(rsaVerifier).parseClaimsJws(jwt); } catch (JwtException e) { throw new JwtProcessingException(e.getMessage(), e); } }
private Claims getClaimsFromToken(String token) { Claims claims = null; try { claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } catch (JwtException e) { log.error(e.getMessage(), e); } return claims; } }
@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
@Override public Authentication parseJwtToken(String jwtToken) throws AuthenticationException { try { Claims claims = Jwts.parser() .setSigningKey(secretkey) .parseClaimsJws(jwtToken) .getBody(); return JwtAuthenticationToken.of(claims); } catch (ExpiredJwtException | SignatureException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (UnsupportedJwtException | MalformedJwtException e) { throw new AuthenticationServiceException(e.getMessage(), e); } catch (IllegalArgumentException e) { throw new InternalAuthenticationServiceException(e.getMessage(), e); } }
@Override public Principal authenticate(HttpServletRequest request) throws AuthenticationException { String header = nullToEmpty(request.getHeader(AUTHORIZATION)); int space = header.indexOf(' '); if ((space < 0) || !header.substring(0, space).equalsIgnoreCase("bearer")) { throw needAuthentication(null); } String token = header.substring(space + 1).trim(); if (token.isEmpty()) { throw needAuthentication(null); } try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String subject = claimsJws.getBody().getSubject(); return new BasicPrincipal(subject); } catch (JwtException e) { throw needAuthentication(e.getMessage()); } catch (RuntimeException e) { throw new RuntimeException("Authentication error", e); } }
@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()); } }
public void consume() { log.info("Starting consumer..."); consumer = new KafkaConsumer<>(kafkaProps); consumer.subscribe(Collections.singletonList(topic)); while (true) { ConsumerRecords<String, String> records = consumer.poll(1000); for (ConsumerRecord<String, String> record : records) { log.info("record offset: {}, record value: {}", record.offset(), record.value()); AccountResponse accountResponse = null; try { accountResponse = accountService.getAccount(record.value()); } catch (JwtException e) { log.error("Unable to get account: {}", e.getMessage()); } if (accountResponse != null && accountResponse.getAccount() != null) { log.info("Account name extracted from JWT: {}", accountResponse.getAccount().getFirstName() + " " + accountResponse.getAccount().getLastName()); } } } } }
@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); }
@Override public byte[] sign(byte[] data) { try { return doSign(data); } catch (InvalidKeyException e) { throw new SignatureException("Invalid Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (java.security.SignatureException e) { throw new SignatureException("Unable to calculate signature using Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (JwtException e) { throw new SignatureException("Unable to convert signature to JOSE format. " + e.getMessage(), e); } }
@Override public byte[] sign(byte[] data) { try { return doSign(data); } catch (InvalidKeyException e) { throw new SignatureException("Invalid Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (java.security.SignatureException e) { throw new SignatureException("Unable to calculate signature using Elliptic Curve PrivateKey. " + e.getMessage(), e); } catch (JwtException e) { throw new SignatureException("Unable to convert signature to JOSE format. " + e.getMessage(), e); } }
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) { log.error(ex.getMessage(), ex); } return authTokenDetails; }
@Override public String validateAuthToken(String authToken, Exchange exchange) { try { Jws<Claims> claims = Jwts.parser().setSigningKey(key).parseClaimsJws(authToken); String username = claims.getBody().getSubject(); Long authSessionId = claims.getBody().get(CLAIM_AUTH_SESSION_ID, Long.class); if (authSessionId == null || authTokenSessions.getIfPresent(authSessionId) == null) { throw new RestApiInvalidAuthTokenServerException("Invalid or expired authentication token"); } return username; } catch (JwtException e) { throw new RestApiInvalidAuthTokenServerException(e.getMessage(), e); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { final JwtAuthenticationRequestToken request = (JwtAuthenticationRequestToken) authentication; try { final String jwtPrincipal = jwtService.getAuthenticationFromToken(request.getToken()); final String mappedIdentity = mapIdentity(jwtPrincipal); final NiFiUser user = new Builder().identity(mappedIdentity).groups(getUserGroups(mappedIdentity)).clientAddress(request.getClientAddress()).build(); return new NiFiAuthenticationToken(new NiFiUserDetails(user)); } catch (JwtException e) { throw new InvalidAuthenticationException(e.getMessage(), e); } }
@Override public Account verifyPasswordResetToken(String token) { try { // parsing validate the JWT, so we only need to grab the href Jws<Claims> jwt = Jwts.parser() .setSigningKey(getDataStore().getApiKey().getSecret()) .require("tokenType", "reset") .parseClaimsJws(token); String userHref = jwt.getBody().get("userHref", String.class); return getDataStore().getResource(userHref, Account.class); } catch(JwtException e) { log.debug("Failed to parse JWT", e); Error error = new DefaultError() .setCode(404) .setStatus(404) .setDeveloperMessage(e.getMessage()) .setMessage("Invalid Token"); throw new ResourceException(error); } }
@Override public Account verifyPasswordResetToken(String token) { try { // parsing validate the JWT, so we only need to grab the href Jws<Claims> jwt = Jwts.parser() .setSigningKey(getDataStore().getApiKey().getSecret()) .require("tokenType", "reset") .parseClaimsJws(token); String userHref = jwt.getBody().get("userHref", String.class); return getDataStore().getResource(userHref, Account.class); } catch(JwtException e) { log.debug("Failed to parse JWT", e); Error error = new DefaultError() .setCode(404) .setStatus(404) .setDeveloperMessage(e.getMessage()) .setMessage("Invalid Token"); throw new ResourceException(error); } }