use of com.auth0.jwt.JWTCreator.Builder in project open-kilda by telstra.
the class PathVerificationService method parseDiscoveryPacket.
@VisibleForTesting
DiscoveryPacketData parseDiscoveryPacket(DiscoveryPacket discoveryPacket, long switchLatency) {
ByteBuffer portBb = ByteBuffer.wrap(discoveryPacket.getPortId().getValue());
portBb.position(1);
OFPort remotePort = OFPort.of(portBb.getShort());
DiscoveryPacketData.DiscoveryPacketDataBuilder builder = DiscoveryPacketData.builder();
builder.remotePort(remotePort);
builder.pathOrdinal(10);
builder.switchT0(-1);
builder.switchT1(-1);
for (LLDPTLV lldptlv : discoveryPacket.getOptionalTlvList()) {
if (matchOptionalLldptlv(lldptlv, REMOTE_SWITCH_OPTIONAL_TYPE, 12)) {
ByteBuffer dpidBb = ByteBuffer.wrap(lldptlv.getValue());
builder.remoteSwitchId(DatapathId.of(dpidBb.getLong(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES)));
} else if (matchOptionalLldptlv(lldptlv, TIMESTAMP_OPTIONAL_TYPE, 12)) {
// skip OpenFlow OUI (4 bytes above)
ByteBuffer tsBb = ByteBuffer.wrap(lldptlv.getValue());
long sendTime = tsBb.getLong(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES);
// include the RX switch latency to "subtract" it
builder.timestamp(sendTime + switchLatency);
} else if (matchOptionalLldptlv(lldptlv, PATH_ORDINAL_OPTIONAL_TYPE, 8)) {
ByteBuffer typeBb = ByteBuffer.wrap(lldptlv.getValue());
builder.pathOrdinal(typeBb.getInt(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES));
} else if (matchOptionalLldptlv(lldptlv, SWITCH_T0_OPTIONAL_TYPE, 12)) {
builder.switchT0(noviflowTimestamp(Arrays.copyOfRange(lldptlv.getValue(), LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES, lldptlv.getValue().length)));
} else if (matchOptionalLldptlv(lldptlv, SWITCH_T1_OPTIONAL_TYPE, 12)) {
builder.switchT1(noviflowTimestamp(Arrays.copyOfRange(lldptlv.getValue(), LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES, lldptlv.getValue().length)));
} else if (matchOptionalLldptlv(lldptlv, TOKEN_OPTIONAL_TYPE)) {
ByteBuffer bb = ByteBuffer.wrap(lldptlv.getValue());
bb.position(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES);
byte[] tokenArray = new byte[lldptlv.getLength() - LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES];
bb.get(tokenArray, 0, tokenArray.length);
String token = new String(tokenArray);
try {
DecodedJWT jwt = verifier.verify(token);
Claim idClaim = jwt.getClaim("id");
if (!idClaim.isNull()) {
builder.packetId(idClaim.asLong());
}
builder.signed(true);
} catch (JWTVerificationException e) {
logger.error("Packet verification failed", e);
builder.signed(false);
}
}
}
return builder.build();
}
use of com.auth0.jwt.JWTCreator.Builder in project gravitee-management-rest-api by gravitee-io.
the class UserServiceTest method shouldUpdateUser_UpdateFields_And_CreateFields.
@Test
public void shouldUpdateUser_UpdateFields_And_CreateFields() throws Exception {
final String USER_ID = "userid";
User user = new User();
user.setId(USER_ID);
user.setSourceId("sourceId");
Date updatedAt = new Date(1234567890L);
user.setUpdatedAt(updatedAt);
user.setFirstname("john");
user.setLastname("doe");
user.setEmail("john.doe@mail.domain");
when(userRepository.findById(USER_ID)).thenReturn(of(user));
UpdateUserEntity toUpdate = new UpdateUserEntity();
toUpdate.setEmail(user.getEmail());
toUpdate.setFirstname(user.getFirstname());
toUpdate.setLastname(user.getLastname());
toUpdate.setCustomFields(Maps.<String, Object>builder().put("fieldToUpdate", "valueUpdated").put("fieldToCreate", "newValue").build());
UserMetadataEntity existingField = new UserMetadataEntity();
existingField.setValue("value1");
existingField.setUserId(USER_ID);
existingField.setFormat(MetadataFormat.STRING);
existingField.setName("fieldToUpdate");
existingField.setKey("fieldToUpdate");
when(userMetadataService.findAllByUserId(USER_ID)).thenReturn(Arrays.asList(existingField));
userService.update(USER_ID, toUpdate);
verify(userMetadataService).update(argThat(entity -> entity.getKey().equals(existingField.getKey()) && entity.getName().equals(existingField.getName()) && entity.getUserId().equals(existingField.getUserId()) && entity.getValue().equals(toUpdate.getCustomFields().get(existingField.getKey()))));
verify(userMetadataService).create(argThat(entity -> entity.getName().equals("fieldToCreate") && entity.getUserId().equals(existingField.getUserId()) && entity.getValue().equals(toUpdate.getCustomFields().get("fieldToCreate"))));
}
use of com.auth0.jwt.JWTCreator.Builder in project gravitee-management-rest-api by gravitee-io.
the class AuthResource method login.
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public Response login(@Context final javax.ws.rs.core.HttpHeaders headers, @Context final HttpServletResponse servletResponse) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
// JWT signer
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured environment role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, GraviteeContext.getCurrentEnvironment(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String sign = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(userDetails.getUsername()).withClaim(Claims.PERMISSIONS, authorities).withClaim(Claims.EMAIL, userDetails.getEmail()).withClaim(Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final Token tokenEntity = new Token();
tokenEntity.setTokenType(TokenTypeEnum.BEARER);
tokenEntity.setToken(sign);
final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
servletResponse.addCookie(bearerCookie);
return ok(tokenEntity).build();
}
return ok().build();
}
use of com.auth0.jwt.JWTCreator.Builder in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUserInternal.
protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// Manage authorities, initialize it with dynamic permissions from the IDP
List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
// We must also load permissions from repository for configured management or portal role
Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
if (!userRoles.isEmpty()) {
userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
// JWT signer
Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
Date issueAt = new Date();
Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
final String token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
if (idToken != null) {
tokenEntity.setAccessToken(accessToken);
tokenEntity.setIdToken(idToken);
}
if (state != null && !state.isEmpty()) {
tokenEntity.setState(state);
}
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
servletResponse.addCookie(bearerCookie);
return Response.ok(tokenEntity).build();
}
use of com.auth0.jwt.JWTCreator.Builder in project java-rest-api by messagebird.
the class RequestValidator method validateSignature.
/**
* Returns raw signature payload after validating a signature successfully,
* otherwise throws {@code RequestValidationException}.
* <p>
* This JWT is signed with a MessageBird account unique secret key, ensuring the request is from MessageBird and
* a specific account.
* The JWT contains the following claims:
* </p>
* <ul>
* <li>"url_hash" - the raw URL hashed with SHA256 ensuring the URL wasn't altered.</li>
* <li> "payload_hash" - the raw payload hashed with SHA256 ensuring the payload wasn't altered.</li>
* <li> "jti" - a unique token ID to implement an optional non-replay check (NOT validated by default).</li>
* <li> "nbf" - the not before timestamp.</li>
* <li> "exp" - the expiration timestamp is ensuring that a request isn't captured and used at a later time.</li>
* <li> "iss" - the issuer name, always MessageBird.</li>
* </ul>
*
* @param clock custom {@link Clock} instance to validate timestamp claims.
* @param signature the actual signature.
* @param url the raw url including the protocol, hostname and query string,
* {@code https://example.com/?example=42}.
* @param requestBody the raw request body.
* @return raw signature payload as {@link DecodedJWT} object.
* @throws RequestValidationException when the signature is invalid.
* @see <a href="https://developers.messagebird.com/docs/verify-http-requests">Verify HTTP Requests</a>
*/
public DecodedJWT validateSignature(Clock clock, String signature, String url, byte[] requestBody) throws RequestValidationException {
if (signature == null || signature.length() == 0)
throw new RequestValidationException("The signature can not be empty.");
if (!skipURLValidation && (url == null || url.length() == 0))
throw new RequestValidationException("The url can not be empty.");
DecodedJWT jwt = JWT.decode(signature);
Algorithm algorithm;
switch(jwt.getAlgorithm()) {
case "HS256":
algorithm = HMAC256;
break;
case "HS384":
algorithm = HMAC384;
break;
case "HS512":
algorithm = HMAC512;
break;
default:
throw new RequestValidationException(String.format("The signing method '%s' is invalid.", jwt.getAlgorithm()));
}
BaseVerification builder = (BaseVerification) JWT.require(algorithm).withIssuer("MessageBird").ignoreIssuedAt().acceptLeeway(1);
if (!skipURLValidation)
builder.withClaim("url_hash", calculateSha256(url.getBytes()));
boolean payloadHashClaimExist = !jwt.getClaim("payload_hash").isNull();
if (requestBody != null && requestBody.length > 0) {
if (!payloadHashClaimExist) {
throw new RequestValidationException("The Claim 'payload_hash' is not set but payload is present.");
}
builder.withClaim("payload_hash", calculateSha256(requestBody));
} else if (payloadHashClaimExist) {
throw new RequestValidationException("The Claim 'payload_hash' is set but actual payload is missing.");
}
JWTVerifier verifier = clock == null ? builder.build() : builder.build(clock);
try {
return verifier.verify(jwt);
} catch (SignatureVerificationException e) {
throw new RequestValidationException("Signature is invalid.", e);
} catch (JWTVerificationException e) {
throw new RequestValidationException(e.getMessage(), e.getCause());
}
}
Aggregations