use of com.auth0.json.mgmt.client.Client in project sharelock-android by auth0.
the class ComposeActivity method onEvent.
public void onEvent(RequestLinkEvent event) {
final Secret secret = event.getSecret();
final EventBus bus = this.bus;
SharedPreferences preferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
client = new LinkAPIClient(preferences.getString(LinkAPIClient.SHARELOCK_ENDPOINT_KEY, LinkAPIClient.DEFAULT_URL));
client.generateLinkForSecret(secret, this, new LinkAPIClient.LinkCallback() {
@Override
public void onSuccess(final Uri link) {
Log.d(TAG, "Obtained link path " + link);
handler.postDelayed(new Runnable() {
@Override
public void run() {
bus.postSticky(new NewLinkEvent(link));
final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
final ClipData clipData = ClipData.newRawUri("sharelocked-link", link);
clipboardManager.setPrimaryClip(clipData);
Snackbar snackbar = Snackbar.with(ComposeActivity.this).text(R.string.link_in_clipboard_message).duration(Snackbar.SnackbarDuration.LENGTH_SHORT);
SnackbarManager.show(snackbar);
}
}, DELAY_MILLIS);
}
@Override
public void onError(Throwable reason) {
Log.e(TAG, "Failed to generate link", reason);
bus.post(new SharelockAPIErrorEvent());
AlertDialog dialog = new AlertDialog.Builder(ComposeActivity.this).setTitle(R.string.link_generation_failed_title).setMessage(R.string.link_generation_failed).setCancelable(true).setPositiveButton(R.string.retry_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
bus.post(new RequestLinkEvent(secret));
}
}).setNegativeButton(R.string.cancel_button, null).create();
dialog.show();
}
});
}
use of com.auth0.json.mgmt.client.Client in project DragonProxy by DragonetMC.
the class LoginChainDecoder method decode.
/**
* decode the chain data in Login packet for MCPE Note: the credit of this
* function goes to Nukkit development team
*/
public void decode() {
Map<String, List<String>> map = gson.fromJson(new String(this.chainJWT, StandardCharsets.UTF_8), new TypeToken<Map<String, List<String>>>() {
}.getType());
if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty())
return;
List<DecodedJWT> chainJWTs = new ArrayList<>();
// Add the JWT tokens to a chain
for (String token : map.get("chain")) chainJWTs.add(JWT.decode(token));
DecodedJWT clientJWT = null;
if (this.clientDataJWT != null) {
clientJWT = JWT.decode(new String(this.clientDataJWT, StandardCharsets.UTF_8));
chainJWTs.add(clientJWT);
}
// first step, check if the public provided key can decode the received chain
try {
ECPublicKey prevPublicKey = null;
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
String encodedPublicKey = null;
ECPublicKey publicKey = null;
if (payload.has("identityPublicKey")) {
encodedPublicKey = payload.get("identityPublicKey").getAsString();
publicKey = (ECPublicKey) EC_KEY_FACTORY.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedPublicKey)));
}
// Trust the root ca public key and use it to verify the chain
if (ENCODED_ROOT_CA_KEY.equals(encodedPublicKey) && payload.has("certificateAuthority") && payload.get("certificateAuthority").getAsBoolean()) {
prevPublicKey = publicKey;
continue;
}
// This will happen if the root ca key we have does not match the one presented by the client chain
if (prevPublicKey == null)
throw new NullPointerException("No trusted public key found in chain, is the client logged in or cracked");
// Throws a SignatureVerificationException if the verification failed
Algorithm.ECDSA384(prevPublicKey, null).verify(jwt);
// Verification was successful since no exception was thrown
// Set the previous public key to this one so that it can be used
// to verify the next JWT token in the chain
prevPublicKey = publicKey;
}
// The for loop successfully verified all JWT tokens with no exceptions thrown
this.loginVerified = true;
Logger.getLogger(this.getClass().getSimpleName()).info("The LoginPacket has been successfully verified for integrity");
} catch (Exception e) {
this.loginVerified = false;
Logger.getLogger(this.getClass().getSimpleName()).info("Failed to verify the integrity of the LoginPacket");
e.printStackTrace();
}
// This is in its own for loop due to the possibility that the chain verification failed
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
// Get the information we care about - The UUID and display name
if (payload.has("extraData") && !payload.has("certificateAuthority")) {
extraData = payload.get("extraData").getAsJsonObject();
if (extraData.has("displayName"))
this.username = extraData.get("displayName").getAsString();
if (extraData.has("identity"))
this.clientUniqueId = UUID.fromString(extraData.get("identity").getAsString());
break;
}
}
// debug purpose
if (log_profiles_files) {
try {
BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".rawChainJTW"));
writer1.write(getChainJWT());
writer1.close();
BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + ".rawClientDataJTW"));
writer.write(getClientDataJWT());
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// debug purpose
int index = 0;
for (DecodedJWT jwt : chainJWTs) {
JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + "_" + index + ".decodedChain"));
writer.write(payload.toString());
writer.close();
index++;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
// client data & skin
if (clientJWT != null) {
this.clientData = gson.fromJson(new String(Base64.getDecoder().decode(clientJWT.getPayload()), StandardCharsets.UTF_8), JsonObject.class);
// debug purpose
if (log_profiles_files) {
try {
BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".decodedData"));
writer1.write(this.clientData.toString());
writer1.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (this.clientData.has("ClientRandomId"))
this.clientId = this.clientData.get("ClientRandomId").getAsLong();
if (this.clientData.has("SkinData") && this.clientData.has("SkinId")) {
this.skin = new Skin(this.clientData.get("SkinData").getAsString(), this.clientData.get("SkinId").getAsString());
if (this.clientData.has("CapeData"))
this.skin.setCape(this.skin.new Cape(Base64.getDecoder().decode(this.clientData.get("CapeData").getAsString())));
} else
this.skin = Skin.DEFAULT_SKIN_STEVE;
if (this.clientData.has("SkinGeometryName"))
this.skinGeometryName = this.clientData.get("SkinGeometryName").getAsString();
if (this.clientData.has("SkinGeometry"))
this.skinGeometry = Base64.getDecoder().decode(this.clientData.get("SkinGeometry").getAsString());
}
}
use of com.auth0.json.mgmt.client.Client in project hopsworks by logicalclocks.
the class JWTController method verifyToken.
/**
* Verify a token
*
* @param token
* @param issuer
* @param audiences
* @param roles
* @return
* @throws SigningKeyNotFoundException
* @throws VerificationException
*/
public DecodedJWT verifyToken(String token, String issuer, Set<String> audiences, Set<String> roles) throws SigningKeyNotFoundException, VerificationException {
JsonWebToken jwt = new JsonWebToken(JWT.decode(token));
issuer = issuer == null || issuer.isEmpty() ? jwt.getIssuer() : issuer;
DecodedJWT djwt = verifyToken(token, issuer, jwt.getExpLeeway(), algorithmFactory.getAlgorithm(jwt));
if (isTokenInvalidated(djwt)) {
throw new VerificationException("Invalidated token.");
}
Set<String> rolesSet = new HashSet<>(jwt.getRole());
if (roles != null && !roles.isEmpty()) {
if (!intersect(roles, rolesSet)) {
throw new AccessLocalException("Client not authorized for this invocation.");
}
}
Set<String> audiencesSet = new HashSet<>(jwt.getAudience());
if (audiences != null && !audiences.isEmpty()) {
if (!intersect(audiences, audiencesSet)) {
throw new AccessLocalException("Token not issued for this recipient.");
}
}
return djwt;
}
use of com.auth0.json.mgmt.client.Client in project hopsworks by logicalclocks.
the class JWTFilter method jwtFilter.
public void jwtFilter(ContainerRequestContext requestContext) throws IOException {
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
Object responseEntity;
if (authorizationHeader == null) {
LOGGER.log(Level.FINEST, "Authorization header not set.");
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Authorization header not set.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
if (!authorizationHeader.startsWith(BEARER)) {
LOGGER.log(Level.FINEST, "Invalid token. AuthorizationHeader : {0}", authorizationHeader);
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
String token = authorizationHeader.substring(BEARER.length()).trim();
DecodedJWT jwt = JWT.decode(token);
Claim expLeewayClaim = jwt.getClaim(EXPIRY_LEEWAY);
String issuer = getIssuer();
int expLeeway = expLeewayClaim.asInt();
try {
Algorithm algorithm = getAlgorithm(jwt);
JWTVerifier verifier = JWT.require(algorithm).withIssuer(issuer == null || issuer.isEmpty() ? jwt.getIssuer() : issuer).acceptExpiresAt(expLeeway == 0 ? DEFAULT_EXPIRY_LEEWAY : expLeeway).build();
jwt = verifier.verify(token);
} catch (Exception exception) {
LOGGER.log(Level.FINE, "JWT Verification Exception: {0}", exception.getMessage());
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, exception.getMessage());
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
if (!isTokenValid(jwt)) {
LOGGER.log(Level.FINEST, "JWT Verification Exception: Invalidated token.");
responseEntity = responseEntity(Response.Status.UNAUTHORIZED, "Invalidated token.");
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, WWW_AUTHENTICATE_VALUE).entity(responseEntity).build());
return;
}
Claim rolesClaim = jwt.getClaim(ROLES);
String[] userRoles = rolesClaim == null ? new String[0] : rolesClaim.asArray(String.class);
Set<String> allowedRolesSet = allowedRoles();
if (allowedRolesSet != null && !allowedRolesSet.isEmpty()) {
if (!intersect(allowedRolesSet, Arrays.asList(userRoles))) {
LOGGER.log(Level.FINE, "JWT Access Exception: Client not authorized for this invocation.");
responseEntity = responseEntity(Response.Status.FORBIDDEN, "Client not authorized for this invocation.");
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
return;
}
}
List<String> audience = jwt.getAudience();
Set<String> accepts = acceptedTokens();
if (accepts != null && !accepts.isEmpty()) {
if (!intersect(accepts, audience)) {
LOGGER.log(Level.FINE, "JWT Access Exception: Token not issued for this recipient.");
responseEntity = responseEntity(Response.Status.FORBIDDEN, "Token not issued for this recipient.");
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(responseEntity).build());
return;
}
}
postJWTFilter(requestContext, jwt);
}
use of com.auth0.json.mgmt.client.Client in project mycore by MyCoRe-Org.
the class MCRSessionFilter method addJWTToResponse.
/**
* If request was authenticated via JSON Web Token add a new token if <code>aud</code> was
* {@link MCRRestAPIAuthentication#AUDIENCE}.
*
* If the response has a status code that represents a client error (4xx), the JSON Web Token is ommited.
* If the response already has a JSON Web Token no changes are made.
*/
private static void addJWTToResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
MCRSession currentSession = MCRSessionMgr.getCurrentSession();
boolean renewJWT = Optional.ofNullable(requestContext.getProperty(PROP_RENEW_JWT)).map(Boolean.class::cast).orElse(Boolean.FALSE);
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).filter(s -> s.startsWith("Bearer ")).filter(s -> !responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.CLIENT_ERROR)).filter(s -> responseContext.getHeaderString(HttpHeaders.AUTHORIZATION) == null).map(h -> renewJWT ? ("Bearer " + MCRRestAPIAuthentication.getToken(currentSession, currentSession.getCurrentIP()).orElseThrow(() -> new InternalServerErrorException("Could not get JSON Web Token"))) : h).ifPresent(h -> {
responseContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, h);
// Authorization header may never be cached in public caches
Optional.ofNullable(requestContext.getHeaderString(HttpHeaders.CACHE_CONTROL)).map(RuntimeDelegate.getInstance().createHeaderDelegate(CacheControl.class)::fromString).filter(cc -> !cc.isPrivate()).ifPresent(cc -> {
cc.setPrivate(true);
responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
});
});
}
Aggregations