Search in sources :

Example 56 with Client

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();
        }
    });
}
Also used : ClipboardManager(android.content.ClipboardManager) AlertDialog(android.app.AlertDialog) SharedPreferences(android.content.SharedPreferences) DialogInterface(android.content.DialogInterface) EventBus(de.greenrobot.event.EventBus) Uri(android.net.Uri) RequestLinkEvent(com.auth0.sharelock.event.RequestLinkEvent) NewLinkEvent(com.auth0.sharelock.event.NewLinkEvent) ClipData(android.content.ClipData) SharelockAPIErrorEvent(com.auth0.sharelock.event.SharelockAPIErrorEvent) Snackbar(com.nispok.snackbar.Snackbar)

Example 57 with Client

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());
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) BufferedWriter(java.io.BufferedWriter) ECPublicKey(java.security.interfaces.ECPublicKey) TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) List(java.util.List) Skin(org.dragonet.common.data.entity.Skin) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 58 with Client

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;
}
Also used : VerificationException(io.hops.hopsworks.jwt.exception.VerificationException) AccessLocalException(javax.ejb.AccessLocalException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashSet(java.util.HashSet)

Example 59 with Client

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);
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) Claim(com.auth0.jwt.interfaces.Claim) IOException(java.io.IOException) SigningKeyNotFoundException(io.hops.hopsworks.jwt.exception.SigningKeyNotFoundException)

Example 60 with Client

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);
        });
    });
}
Also used : JWT(com.auth0.jwt.JWT) Arrays(java.util.Arrays) Context(jakarta.ws.rs.core.Context) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) MCRUser(org.mycore.user2.MCRUser) MCRRestAPIAuthentication(org.mycore.restapi.v1.MCRRestAPIAuthentication) LinkedHashMap(java.util.LinkedHashMap) Response(jakarta.ws.rs.core.Response) SecurityContext(jakarta.ws.rs.core.SecurityContext) MCRJWTUtil(org.mycore.frontend.jersey.MCRJWTUtil) ContainerRequestFilter(jakarta.ws.rs.container.ContainerRequestFilter) Map(java.util.Map) ContainerResponseContext(jakarta.ws.rs.container.ContainerResponseContext) ContainerResponseFilter(jakarta.ws.rs.container.ContainerResponseFilter) Priority(jakarta.annotation.Priority) MCRTransactionHelper(org.mycore.common.MCRTransactionHelper) Claim(com.auth0.jwt.interfaces.Claim) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) MCRUserInformation(org.mycore.common.MCRUserInformation) CacheControl(jakarta.ws.rs.core.CacheControl) NotAuthorizedException(jakarta.ws.rs.NotAuthorizedException) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) IOException(java.io.IOException) MCRUserManager(org.mycore.user2.MCRUserManager) MCRFrontendUtil(org.mycore.frontend.MCRFrontendUtil) Provider(jakarta.ws.rs.ext.Provider) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) ProxyOutputStream(org.apache.commons.io.output.ProxyOutputStream) StandardCharsets(java.nio.charset.StandardCharsets) Priorities(jakarta.ws.rs.Priorities) RuntimeDelegate(jakarta.ws.rs.ext.RuntimeDelegate) MCRJWTResource(org.mycore.frontend.jersey.resources.MCRJWTResource) Base64(java.util.Base64) List(java.util.List) Principal(java.security.Principal) Logger(org.apache.logging.log4j.Logger) MCRSystemUserInformation(org.mycore.common.MCRSystemUserInformation) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) MCRSession(org.mycore.common.MCRSession) MCRRestAPIUtil(org.mycore.restapi.v1.utils.MCRRestAPIUtil) HttpHeaders(jakarta.ws.rs.core.HttpHeaders) MCRSessionMgr(org.mycore.common.MCRSessionMgr) Optional(java.util.Optional) Application(jakarta.ws.rs.core.Application) LogManager(org.apache.logging.log4j.LogManager) MCRSession(org.mycore.common.MCRSession) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException)

Aggregations

IOException (java.io.IOException)36 APIException (com.auth0.exception.APIException)27 Auth0Exception (com.auth0.exception.Auth0Exception)27 RateLimitException (com.auth0.exception.RateLimitException)27 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 List (java.util.List)25 Test (org.junit.Test)25 VoidRequest (com.auth0.net.VoidRequest)24 TokenHolder (com.auth0.json.auth.TokenHolder)22 JsonParseException (com.fasterxml.jackson.core.JsonParseException)19 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)19 ExpectedException (org.junit.rules.ExpectedException)19 RecordedMultipartRequest (com.auth0.net.multipart.RecordedMultipartRequest)16 Test (org.junit.jupiter.api.Test)14 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)14 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)13 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 AuthAPI (com.auth0.client.auth.AuthAPI)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 OkHttpClient (okhttp3.OkHttpClient)7