use of com.auth0.jwt.JWTCreator.Builder in project libresonic by Libresonic.
the class JWTSecurityServiceTest method addJWTToken.
@Test
public void addJWTToken() throws Exception {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriString);
String actualUri = service.addJWTToken(builder).build().toUriString();
String jwtToken = UriComponentsBuilder.fromUriString(actualUri).build().getQueryParams().getFirst(JWTSecurityService.JWT_PARAM_NAME);
DecodedJWT verify = verifier.verify(jwtToken);
Claim claim = verify.getClaim(JWTSecurityService.CLAIM_PATH);
assertEquals(expectedClaimString, claim.asString());
}
use of com.auth0.jwt.JWTCreator.Builder in project open-kilda by telstra.
the class PathVerificationService method generateDiscoveryPacket.
/**
* Return Discovery packet.
*
* @param srcSw source switch.
* @param port port.
* @param sign sign.
* @param packetId id of the packet.
* @return discovery packet.
*/
OFPacketOut generateDiscoveryPacket(IOFSwitch srcSw, OFPort port, boolean sign, Long packetId) {
try {
byte[] dpidArray = new byte[8];
ByteBuffer dpidBb = ByteBuffer.wrap(dpidArray);
DatapathId dpid = srcSw.getId();
dpidBb.putLong(dpid.getLong());
byte[] chassisId = new byte[] { 4, 0, 0, 0, 0, 0, 0 };
System.arraycopy(dpidArray, 2, chassisId, 1, 6);
// Set the optionalTLV to the full SwitchID
byte[] dpidTlvValue = Arrays.concatenate(ORGANIZATIONALLY_UNIQUE_IDENTIFIER, new byte[] { REMOTE_SWITCH_OPTIONAL_TYPE, 0, 0, 0, 0, 0, 0, 0, 0 });
System.arraycopy(dpidArray, 0, dpidTlvValue, LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES, 8);
// Set src mac to be able to detect the origin of the packet.
// NB: previously we set port's address instead of switch (some switches declare unique address per port)
byte[] srcMac = new byte[6];
System.arraycopy(dpidArray, 2, srcMac, 0, 6);
byte[] portId = new byte[] { 2, 0, 0 };
ByteBuffer portBb = ByteBuffer.wrap(portId, 1, 2);
portBb.putShort(port.getShortPortNumber());
byte[] ttlValue = new byte[] { 0, 0x78 };
DiscoveryPacket dp = DiscoveryPacket.builder().chassisId(makeIdLldptvPacket(chassisId, CHASSIS_ID_LLDPTV_PACKET_TYPE)).portId(makeIdLldptvPacket(portId, PORT_ID_LLDPTV_PACKET_TYPE)).ttl(makeIdLldptvPacket(ttlValue, TTL_LLDPTV_PACKET_TYPE)).build();
// Add TLV for t0, this will be overwritten by the switch if it supports switch timestamps
dp.getOptionalTlvList().add(switchTimestampTlv(SWITCH_T0_OPTIONAL_TYPE));
// Add TLV for t1, this will be overwritten by the switch if it supports switch timestamps
dp.getOptionalTlvList().add(switchTimestampTlv(SWITCH_T1_OPTIONAL_TYPE));
LLDPTLV dpidTlv = makeIdLldptvPacket(dpidTlvValue, OPTIONAL_LLDPTV_PACKET_TYPE);
dp.getOptionalTlvList().add(dpidTlv);
// Add T0 based on format from Floodlight LLDP
long time = System.currentTimeMillis();
long swLatency = srcSw.getLatency().getValue();
byte[] timestampTlvValue = ByteBuffer.allocate(Long.SIZE / 8 + LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES).put(ORGANIZATIONALLY_UNIQUE_IDENTIFIER).put(// 0x01 is what we'll use to differentiate DPID 0x00 from time 0x01
TIMESTAMP_OPTIONAL_TYPE).putLong(time + swLatency).array();
LLDPTLV timestampTlv = makeIdLldptvPacket(timestampTlvValue, OPTIONAL_LLDPTV_PACKET_TYPE);
dp.getOptionalTlvList().add(timestampTlv);
// Type
byte[] typeTlvValue = ByteBuffer.allocate(Integer.SIZE / 8 + LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES).put(ORGANIZATIONALLY_UNIQUE_IDENTIFIER).put(PATH_ORDINAL_OPTIONAL_TYPE).putInt(PathType.ISL.ordinal()).array();
LLDPTLV typeTlv = makeIdLldptvPacket(typeTlvValue, OPTIONAL_LLDPTV_PACKET_TYPE);
dp.getOptionalTlvList().add(typeTlv);
if (sign) {
Builder builder = JWT.create().withClaim("dpid", dpid.getLong()).withClaim("ts", time + swLatency);
if (packetId != null) {
builder.withClaim("id", packetId);
}
String token = builder.sign(algorithm);
byte[] tokenBytes = token.getBytes(Charset.forName("UTF-8"));
byte[] tokenTlvValue = ByteBuffer.allocate(LLDP_TLV_OPTIONAL_HEADER_SIZE_IN_BYTES + tokenBytes.length).put(ORGANIZATIONALLY_UNIQUE_IDENTIFIER).put(TOKEN_OPTIONAL_TYPE).put(tokenBytes).array();
LLDPTLV tokenTlv = makeIdLldptvPacket(tokenTlvValue, OPTIONAL_LLDPTV_PACKET_TYPE);
dp.getOptionalTlvList().add(tokenTlv);
}
MacAddress dstMac = MacAddress.of(config.getVerificationBcastPacketDst());
IPv4Address dstIp = IPv4Address.of(DISCOVERY_PACKET_IP_DST);
IPv4 l3 = new IPv4().setSourceAddress(IPv4Address.of(((InetSocketAddress) srcSw.getInetAddress()).getAddress().getAddress())).setDestinationAddress(dstIp).setTtl((byte) 64).setProtocol(IpProtocol.UDP);
UDP l4 = new UDP();
l4.setSourcePort(TransportPort.of(DISCOVERY_PACKET_UDP_PORT));
l4.setDestinationPort(TransportPort.of(DISCOVERY_PACKET_UDP_PORT));
Ethernet l2 = new Ethernet().setSourceMACAddress(MacAddress.of(srcMac)).setDestinationMACAddress(dstMac).setEtherType(EthType.IPv4);
l2.setPayload(l3);
l3.setPayload(l4);
l4.setPayload(dp);
byte[] data = l2.serialize();
OFPacketOut.Builder pob = srcSw.getOFFactory().buildPacketOut().setBufferId(OFBufferId.NO_BUFFER).setActions(getDiscoveryActions(srcSw, port)).setData(data);
OFMessageUtils.setInPort(pob, OFPort.CONTROLLER);
return pob.build();
} catch (Exception e) {
logger.error(String.format("error generating discovery packet: %s", e.getMessage()), e);
}
return null;
}
use of com.auth0.jwt.JWTCreator.Builder in project gravitee-management-rest-api by gravitee-io.
the class AbstractAuthenticationResource method connectUser.
protected Response connectUser(String userId, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
UserEntity user = userService.connect(userId);
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 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()));
}
// 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 sign = 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 Token tokenEntity = new Token();
tokenEntity.setTokenType(TokenTypeEnum.BEARER);
tokenEntity.setToken(sign);
if (idToken != null) {
tokenEntity.setAccessToken(accessToken);
tokenEntity.setIdToken(idToken);
}
if (state != null && !state.isEmpty()) {
tokenEntity.setState(state);
}
final Cookie bearerCookie = cookieGenerator.generate("Bearer%20" + sign);
servletResponse.addCookie(bearerCookie);
return Response.ok(tokenEntity).build();
}
use of com.auth0.jwt.JWTCreator.Builder in project gravitee-management-rest-api by gravitee-io.
the class CurrentUserResource method login.
@POST
@Path("/login")
@ApiOperation(value = "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 Map<String, Object> claims = new HashMap<>();
claims.put(Claims.ISSUER, environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER));
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> roles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getUsername());
if (!roles.isEmpty()) {
roles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
}
this.environmentService.findByOrganization(GraviteeContext.getCurrentOrganization()).stream().flatMap(env -> membershipService.getRoles(MembershipReferenceType.ENVIRONMENT, env.getId(), MembershipMemberType.USER, userDetails.getUsername()).stream()).filter(Objects::nonNull).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(userDetails.getUsername()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, userDetails.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, userDetails.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, userDetails.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
final TokenEntity tokenEntity = new TokenEntity();
tokenEntity.setType(BEARER);
tokenEntity.setToken(token);
final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
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 UserServiceImpl method search.
@Override
public Page<UserEntity> search(UserCriteria criteria, Pageable pageable) {
try {
LOGGER.debug("search users");
UserCriteria.Builder builder = new UserCriteria.Builder().organizationId(GraviteeContext.getCurrentOrganization()).statuses(criteria.getStatuses());
if (criteria.hasNoStatus()) {
builder.noStatus();
}
UserCriteria newCriteria = builder.build();
Page<User> users = userRepository.search(newCriteria, new PageableBuilder().pageNumber(pageable.getPageNumber() - 1).pageSize(pageable.getPageSize()).build());
List<UserEntity> entities = users.getContent().stream().map(u -> convert(u, false)).collect(toList());
populateUserFlags(entities);
return new Page<>(entities, users.getPageNumber() + 1, (int) users.getPageElements(), users.getTotalElements());
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to search users", ex);
throw new TechnicalManagementException("An error occurs while trying to search users", ex);
}
}
Aggregations