Search in sources :

Example 1 with Client

use of com.auth0.json.mgmt.client.Client in project chemvantage by chuckwight.

the class LTIRegistration method createDeployment.

String createDeployment(HttpServletRequest request) throws Exception {
    DecodedJWT jwt = JWT.decode(request.getParameter("Token"));
    String client_name = jwt.getSubject();
    String email = jwt.getClaim("email").asString();
    String organization = jwt.getAudience().get(0);
    String org_url = jwt.getClaim("url").asString();
    String lms = jwt.getClaim("lms").asString();
    String client_id = request.getParameter("ClientId");
    if (client_id == null)
        throw new Exception("Client ID value is required.");
    String deployment_id = request.getParameter("DeploymentId");
    if (deployment_id == null)
        throw new Exception("Deployment ID value is required.");
    String platform_id;
    String oidc_auth_url;
    String oauth_access_token_url;
    String well_known_jwks_url;
    switch(lms) {
        case "blackboard":
            platform_id = "https://blackboard.com";
            oidc_auth_url = "https://developer.blackboard.com/api/v1/gateway/oidcauth";
            well_known_jwks_url = "https://developer.blackboard.com/api/v1/management/applications/" + client_id + "/jwks.json";
            oauth_access_token_url = "https://developer.blackboard.com/api/v1/gateway/oauth2/jwttoken";
            break;
        case "canvas":
            platform_id = "https://canvas.instructure.com";
            oidc_auth_url = "https://canvas.instructure.com/api/lti/authorize_redirect";
            well_known_jwks_url = "https://canvas.instructure.com/api/lti/security/jwks";
            URL account_url = new URL(request.getParameter("AccountUrl"));
            if (account_url.getHost().contains("instructure.com"))
                oauth_access_token_url = "https://" + account_url.getHost() + "/login/oauth2/token";
            else
                oauth_access_token_url = "https://canvas.instructure.com/login/oauth2/token";
            break;
        case "LTI Certification":
        case "IMS Certification":
            platform_id = "https://ltiadvantagevalidator.imsglobal.org";
            oidc_auth_url = "https://ltiadvantagevalidator.imsglobal.org/ltitool/oidcauthurl.html";
            well_known_jwks_url = "https://oauth2server.imsglobal.org/jwks";
            oauth_access_token_url = "https://ltiadvantagevalidator.imsglobal.org/ltitool/authcodejwt.html";
            break;
        default:
            platform_id = request.getParameter("PlatformId");
            if (platform_id == null || platform_id.isEmpty())
                throw new Exception("Platform ID value is required.");
            oidc_auth_url = request.getParameter("OIDCAuthUrl");
            if (oidc_auth_url == null || oidc_auth_url.isEmpty())
                throw new Exception("OIDC Auth URL is required.");
            oauth_access_token_url = request.getParameter("OauthAccessTokenUrl");
            if (oauth_access_token_url == null || oauth_access_token_url.isEmpty())
                throw new Exception("OAuth Access Token URL is required.");
            well_known_jwks_url = request.getParameter("JWKSUrl");
            if (well_known_jwks_url == null || well_known_jwks_url.isEmpty())
                throw new Exception("JSON Web Key Set URL is required.");
    }
    Deployment d = new Deployment(platform_id, deployment_id, client_id, oidc_auth_url, oauth_access_token_url, well_known_jwks_url, client_name, email, organization, org_url, lms);
    d.status = "pending";
    d.price = 20;
    Deployment prior = Deployment.getInstance(d.platform_deployment_id);
    String msg = "<h2>Congratulations. Registration is complete.</h2>" + "<br/><br/>Contact Chuck Wight at admin@chemvantage.org for support with any questions or issues.<br/><br/>Thank you.";
    if (prior != null) {
        // this is a repeat registration
        d.status = prior.status == null ? "pending" : prior.status;
        if (prior.client_id.equals(d.client_id))
            msg += "Note: this platform deployment was registered previously. The registration data have now been updated.<p>";
        else
            msg += "Note: This platform deployment was registered previously. The client_id and registration data have now been updated. If this is not correct, you should contact admin@chemvantage.org immediately.<p>";
    }
    // registration is now complete
    ofy().save().entity(d).now();
    return msg;
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) URL(java.net.URL)

Example 2 with Client

use of com.auth0.json.mgmt.client.Client in project chemvantage by chuckwight.

the class LTIRegistration method sendRegistrationEmail.

void sendRegistrationEmail(String token, HttpServletRequest request) throws Exception {
    DecodedJWT jwt = JWT.decode(token);
    String name = jwt.getSubject();
    String email = jwt.getClaim("email").asString();
    String org = jwt.getAudience().get(0);
    String url = jwt.getClaim("url").asString();
    String iss = jwt.getIssuer();
    String lms = jwt.getClaim("lms").asString();
    StringBuffer buf = new StringBuffer();
    buf.append("<h2>ChemVantage Registration</h2>");
    buf.append("Name: " + name + " (" + email + ")<br/>");
    buf.append("Organization: " + org + (url.isEmpty() ? "" : " (" + url + ")") + "<br/>");
    buf.append("LMS: " + lms + "<br/><br/>");
    buf.append("Thank you for your ChemVantage registration request.<p>");
    buf.append("<h3>Pricing</h3>" + "When you complete the registration steps below, your account will be activated immediately. ChemVantage " + "will charge each student $20 USD before granting access to the first assignment. Upon " + "successful payment, the student will have unlimited access to ChemVantage assignments through your LMS " + "for a period of 10 months. As a reminder, access to ChemVantage by instructors and LMS account " + "administrators is always free.");
    buf.append("If you have questions or require assistance, please contact us at admin@chemvantage.org.");
    buf.append("<h3>Complete the LTI Advantage Registration Process</h3>");
    buf.append("The next step is to enter the ChemVantage configuration details into your LMS. " + "This will enable your LMS to communicate securely with ChemVantage. Normally, " + "you must have administrator privileges in your LMS in order to do this. " + "If you are NOT the LMS administrator, please stop here and forward this message " + "to an administrator with a request to complete the registration process. The " + "registration link below will be active for 7 days and expires at " + jwt.getExpiresAt() + ".<p>" + "<hr>" + "<br>To the LMS Administrator:<p>" + "ChemVantage is a free Open Education Resource for teaching and learning college-" + "level General Chemistry. Learn more about ChemVantage " + "<a href=https://www.chemvantage.org/about.html>here</a>.<p>");
    switch(lms) {
        case "blackboard":
            buf.append("This request indicates that you are using the cloud-based Blackboard Learn LMS. " + "To configure ChemVantage in Blackboard please perform the following steps:<ol>" + "<li>Go to System Admin | Integrations: LTI Tool Providers | Register LTI 1.3 Tool" + "<li>Enter the Client ID: " + (iss.equals("https://dev-vantage-hrd.appspot.com") ? "ec076e8c-b90f-4ecf-9b5d-a9eff03976be" : "be1004de-6f8e-45b9-aae4-2c1370c24e1e") + "<li>Make a copy of the deployment_id and set Tool status: Approved" + "<li>Institution Policies: Send Role, Name, Email; Allow Grade Service and Membership Service" + "<li>Submit" + "<li>Click the link below to register the deployment_id with ChemVantage<br/>" + "<a href=" + iss + "/lti/registration?UserRequest=final&token=" + token + ">" + iss + "/lti/registration?UserRequest=final&token=" + token + "</a></li>" + "<li>Go back to the LTI Tool Providers page, and from the dropdown menu on the ChemVantage app select Manage Placements" + "<li>Click Create Placement" + "<ul><li>Label: ChemVantage</li>" + " <li>Description: ChemVantage is an Open Educational Resource for teaching and learning college-level General Chemistry" + " <li>Handle: (any unique string)" + " <li>Availability: Yes" + " <li>Course Content Tool (supports deep linking)" + " <li>Tool Provider URL: " + iss + "/lti/deeplinks" + " <li>Custom Parameters (leave blank)" + " <li>Submit</li></ul></ol>");
            buf.append("<hr><br>To the Course Instructor:");
            buf.append("<ol><li>Go to the course | Content | Build Content | ChemVantage</li>" + "<li>Name: as appropriate (e.g., Quiz - Heat & Enthalpy)</li>" + "<li>Grading:" + "<ul><li>Enable Evaluation - Yes</li>" + " <li>Points - 10 for quiz or homework; 5 for video; 100 for practice exam</li>" + " <li>Visible to Students - Yes</li>" + "</ul></li>" + "<li>Submit</li>" + "<li>Click the new assignment link to launch ChemVantage</li>" + "<li>Choose the relevant assignment (e.g., Quiz on Heat & Enthalpy)</li>" + "<li>Customize the assignment, if desired, using the highlighted link</li>" + "</ol>");
            break;
        case "canvas":
            buf.append("This request indicates that you are using the cloud-based Instructure Canvas LMS. " + "To configure ChemVantage in Canvas please perform the following steps:<ol>" + "<li>Configure a new LTI Developer Key for your Canvas Account " + "(<a href=https://community.canvaslms.com/docs/DOC-16729-42141110178>see detailed instuctions here</a>)" + "<br>Use the following Key Settings:<ul>" + "<li>Key Name: ChemVantage" + (iss.contains("dev") ? " Development" : "") + "<li>Owner Email: admin@chemvantage.org" + "<li>Redirect URIs:<br>" + iss + "/lti/launch<br>" + iss + "/lti/deeplinks" + "<li>Configure Method: Enter URL" + "<li>JSON URL: " + iss + "/lti/registration?UserRequest=config&lms=canvas" + "</ul>" + "<li>Click Save." + "<li>Copy or write down the client_id and deployment_id created in step 1. This is the tricky part, " + "because Canvas doesn't make it easy:<ul>" + " <li>Canvas uses the developer key as the client_id, so it can be viewed from the list of " + "developer keys. It is a numeric value that looks something like <b>32570000000000041</b>.</li> " + " <li>The deployment_id can be found in Settings | Apps | App Configurations by opening the " + "settings menu for ChemVantage. It is a compound value that consists of a number and a hex string " + "separated by a colon and looks something like <b>10408:7db438070728c02373713c12c73869b3af470b68</b>.</li></ul>" + "<li>Add ChemVantage as an External App to your account using the client_id created in step 1 " + "(<a href=https://community.canvaslms.com/docs/DOC-16730-42141110273>see detailed instructions here</a>)" + "<li>Click the link below to register the new client_id and deployment_id created in step 1 with ChemVantage</ol>");
            buf.append("<a href=" + iss + "/lti/registration?UserRequest=final&token=" + token + ">" + iss + "/lti/registration?UserRequest=final&token=" + token + "</a><br/><br/>");
            buf.append("<hr><br>To the Course Instructor:<ol>" + "<li>Create a new Canvas assignment with the following recommended parameters:" + "<ul><li>Name: (as appropriate, e.g. Quiz - Heat and Enthalpy)</li>" + " <li>Points: 10 for quiz or homework; 5 for video; 100 for practice exam</li>" + " <li>Submission Type: External Tool</li>" + " <li>External Tool URL: Find ChemVantage or enter " + iss + "/lti/launch</li>" + " <li>Save or Save and Publish</li>" + "</ul></li>" + "<li>When you launch the assignment, you may use the highlighted link to customize it for your class.</li>" + "</ol>");
            break;
        case "moodle":
            buf.append("This request indicates that you are using the open-source Moodle LMS. " + "To configure ChemVantage in Moodle v3.10 please go to Site Administration | Plugins | Manage Tools<br/>" + "Enter the URL: " + iss + "/lti/registration, complete the form and activate the tool (easy).<br/><br/>" + "Otherwise, you can configure the tool manually:<ul>" + "<li>Tool Name: ChemVantage" + (iss.contains("dev-vantage") ? " Development" : "") + "</li>" + "<li>Tool URL: " + iss + "/lti/launch" + "</li>" + "<li>Tool Description: ChemVantage is an Open Education Resource for teaching and learning college-level General Chemistry</li>" + "<li>LTI version: LTI 1.3</li>" + "<li>Public Key Type: Keyset URL</li>" + "<li>Public Keyset: " + iss + "/jwks" + "</li>" + "<li>Initiate Login URL: " + iss + "/auth/token" + "</li>" + "<li>Redirection URIs: " + iss + "/lti/launch " + iss + "/lti/deeplinks" + "</li>" + "<li>Check 'Supports Deep Linking'</li>" + "<li>Content Selection URL: " + iss + "/lti/deeplinks" + "</li>" + "<li>Services | IMS LTI Assignment and Grade Services: select Use for grade sync only</li>" + "<li>Services | IMS LTI Names and Role Provisioning: select Use this service</li>" + "<li>Privacy | check Force SSL</li>" + "<li>Save Changes</li>" + "</ul>");
            buf.append("When you have finished the configuration, Moodle generates a preconfigured tool. You must activate it and " + "then click 'View configuration details'. When you have these details in hand, including the client_id and deployment_id, " + "click the link below to enter them into ChemVantage.<br/><br/>");
            buf.append("<a href=" + iss + "/lti/registration?UserRequest=final&token=" + token + ">" + iss + "/lti/registration?UserRequest=final&token=" + token + "</a><br/><br/>");
            buf.append("<hr><br>To the Course Instructor:<br/>" + "To add ChemVantage assignments to your course:<ol>" + "<li>Click 'Add an activity or resource'</li>" + "<li>Click 'External Tool'</li>" + "<li>Select ChemVantage from preconfigured tools and click 'Select content'</li>" + "<li>Choose one or more ChemVantage assignments, click 'Submit' and then 'Continue'</li>" + "</ol>");
            break;
        case "LTI Certification":
            buf.append("The deployment_id will be recorded automatically. Please click the link below to register the new client_id with ChemVantage:<br>" + "<a href=" + iss + "/lti/registration?UserRequest=final&token=" + token + ">" + iss + "/lti/registration?UserRequest=final&token=" + token + "</a><br/><br/>");
            break;
        default:
            buf.append("This registration request uses the LTI Advantage (version 1.3) specifications. " + "Use the information below to register ChemVantage in your LMS:<br>" + "Tool Domain URL: " + iss + "<br>" + "Tool Redirect URL: " + iss + "/lti/launch<br>" + "Tool Deep Linking URL: " + iss + "/lti/deeplinks<br>" + "OIDC Login Initiation URL: " + iss + "/auth/token<br>" + "JSON Web Key Set URL: " + iss + "/jwks<p>");
            buf.append("If your LMS requires you to enter a specific public RSA key instead of the JSON Web Key Set URL, you can get it here:<br>" + "<a href=" + iss + "/jwks?kid=" + KeyStore.getAKeyId(lms) + "&fmt=x509>PEM key in X509 format</a> or <a href=" + iss + "/jwks?kid=" + KeyStore.getAKeyId(lms) + ">JSON Web Key</a><p>");
            buf.append("When you have finished the configuration, your LMS " + "should generate a client_id value to identify the ChemVantage tool. " + "In addition, your LMS should generate a " + "deployment_id value to identify a specific account in your LMS for this tool. " + "When you have these values in hand, please click the following link to complete the " + "LTI registration.<p>");
            buf.append("<a href=" + iss + "/lti/registration?UserRequest=final&token=" + token + ">" + iss + "/lti/registration?UserRequest=final&token=" + token + "</a><p>");
    }
    buf.append("If you  need additional assistance, please contact me at admin@chemvantage.org. <p>" + "-Chuck Wight");
    sendEmail(name, email, "ChemVantage LTI Registration", buf.toString());
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 3 with Client

use of com.auth0.json.mgmt.client.Client in project myinfo-connector-java by singpass.

the class MyInfoConnector method getMyInfoPersonData.

/**
 * <p>
 * Get MyInfo Person Data
 * </p>
 * <p>
 * This function takes in all the required variables, invoke the
 * getAccessToken API to generate the access token. The access token is then
 * use to invoke the person API to get the Person data.
 * </p>
 *
 * @param authCode
 *            the authorisation code
 * @param txnNo
 *            the transaction no required in person call
 * @param state
 *            the state required in token call
 * @param publicCert
 *            the public cert
 * @param privateKey
 *            the private key
 * @param clientAppId
 *            the client id
 * @param clientAppPwd
 *            the client password
 * @param redirectUri
 *            the redirect url
 * @param attributes
 *            the attributes
 * @param env
 *            the environment
 * @param tokenUrl
 *            the token url
 * @param personUrl
 *            the person url
 * @param proxyTokenURL
 *            user provided proxy url
 * @param proxyPersonURL
 *            user provided proxy url
 * @param useProxy
 *            indicate the use of proxy url
 * @return the person's data in json format.
 * @see <a href=
 *      "https://www.ndi-api.gov.sg/library/trusted-data/myinfo/implementation-myinfo-data"></a>
 * @since 1.0
 * @throws MyInfoException
 */
protected static String getMyInfoPersonData(String authCode, String txnNo, String state, Certificate publicCert, Key privateKey, String clientAppId, String clientAppPwd, String redirectUri, String attributes, String env, String tokenURL, String personURL, String proxyTokenURL, String proxyPersonURL, String useProxy) throws MyInfoException {
    String result = null;
    String jsonResponse = null;
    RSAPublicKey pubKey = CertUtil.getPublicKey(publicCert);
    // Get access token
    String token = MyInfoConnector.getAccessToken(authCode, tokenURL, clientAppId, clientAppPwd, redirectUri, env, privateKey, state, proxyTokenURL, useProxy);
    HashMap<String, String> tokenList = new Gson().fromJson(token, new TypeToken<HashMap<String, String>>() {
    }.getType());
    DecodedJWT tokenJWT = MyInfoSecurityHelper.verifyToken(tokenList.get(ApplicationConstant.ACCESS_TOKEN), pubKey);
    // Get person
    result = MyInfoConnector.getPersonData(tokenJWT.getSubject(), tokenList.get(ApplicationConstant.ACCESS_TOKEN), txnNo, personURL, clientAppId, attributes, env, privateKey, proxyPersonURL, useProxy);
    if (!env.equalsIgnoreCase(ApplicationConstant.SANDBOX)) {
        try {
            String payload = MyInfoSecurityHelper.getPayload(result, privateKey);
            DecodedJWT personJWT = MyInfoSecurityHelper.verifyToken(payload, pubKey);
            // Convert byte[] to String
            byte[] base64Decode = Base64.getDecoder().decode(personJWT.getPayload());
            jsonResponse = new String(base64Decode);
        } catch (Exception e) {
            throw new MyInfoException();
        }
    } else {
        jsonResponse = result;
    }
    return jsonResponse;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) TypeToken(com.google.gson.reflect.TypeToken) Gson(com.google.gson.Gson) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException)

Example 4 with Client

use of com.auth0.json.mgmt.client.Client in project auth0-java by auth0.

the class ManagementAPI method buildNetworkingClient.

/**
 * Given a set of options, it creates a new instance of the {@link OkHttpClient}
 * configuring them according to their availability.
 *
 * @param options the options to set to the client.
 * @return a new networking client instance configured as requested.
 */
private OkHttpClient buildNetworkingClient(HttpOptions options) {
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    final ProxyOptions proxyOptions = options.getProxyOptions();
    if (proxyOptions != null) {
        // Set proxy
        clientBuilder.proxy(proxyOptions.getProxy());
        // Set authentication, if present
        final String proxyAuth = proxyOptions.getBasicAuthentication();
        if (proxyAuth != null) {
            clientBuilder.proxyAuthenticator(new Authenticator() {

                private static final String PROXY_AUTHORIZATION_HEADER = "Proxy-Authorization";

                @Override
                public okhttp3.Request authenticate(Route route, Response response) throws IOException {
                    if (response.request().header(PROXY_AUTHORIZATION_HEADER) != null) {
                        return null;
                    }
                    return response.request().newBuilder().header(PROXY_AUTHORIZATION_HEADER, proxyAuth).build();
                }
            });
        }
    }
    configureLogging(options.getLoggingOptions());
    Dispatcher dispatcher = new Dispatcher();
    dispatcher.setMaxRequestsPerHost(options.getMaxRequestsPerHost());
    dispatcher.setMaxRequests(options.getMaxRequests());
    return clientBuilder.addInterceptor(logging).addInterceptor(telemetry).addInterceptor(new RateLimitInterceptor(options.getManagementAPIMaxRetries())).connectTimeout(options.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(options.getReadTimeout(), TimeUnit.SECONDS).dispatcher(dispatcher).build();
}
Also used : ProxyOptions(com.auth0.client.ProxyOptions) IOException(java.io.IOException) RateLimitInterceptor(com.auth0.net.RateLimitInterceptor)

Example 5 with Client

use of com.auth0.json.mgmt.client.Client in project auth0-java by auth0.

the class OrganizationsEntity method deleteInvitation.

/**
 * Delete an invitation. A token with {@code delete:organization_invitations`} scope is required.
 *
 * @param orgId the ID of the organization
 * @param invitationId the ID of the invitation to delete
 * @return a Request to execute
 *
 * @see <a href="https://auth0.com/docs/api/management/v2#!/Organizations/delete_invitations_by_invitation_id">https://auth0.com/docs/api/management/v2#!/Organizations/delete_invitations_by_invitation_id</a>
 */
public Request<Void> deleteInvitation(String orgId, String invitationId) {
    Asserts.assertNotNull(orgId, "organization ID");
    Asserts.assertNotNull(invitationId, "invitation ID");
    String url = baseUrl.newBuilder().addPathSegments(ORGS_PATH).addPathSegment(orgId).addPathSegment("invitations").addPathSegment(invitationId).build().toString();
    VoidRequest request = new VoidRequest(client, url, "DELETE");
    request.addHeader(AUTHORIZATION_HEADER, "Bearer " + apiToken);
    return request;
}
Also used : VoidRequest(com.auth0.net.VoidRequest)

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