Search in sources :

Example 26 with Token

use of com.auth0.json.mgmt.Token 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 27 with Token

use of com.auth0.json.mgmt.Token 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 28 with Token

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

the class LTIv1p3Launch method ltiv1p3LaunchRequest.

void ltiv1p3LaunchRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // StringBuffer debug = new StringBuffer();
    // ensures proper OIDC authorization flow completed
    JsonObject state = validateStateToken(request);
    // returns the validated Deployment
    Deployment d = validateIdToken(request);
    // Decode the JWT id_token payload as a JsonObject:
    JsonObject claims = null;
    try {
        DecodedJWT id_token = JWT.decode(request.getParameter("id_token"));
        String json = new String(Base64.getUrlDecoder().decode(id_token.getPayload()));
        claims = JsonParser.parseString(json).getAsJsonObject();
    } catch (Exception e) {
        throw new Exception("id_token was not a valid JWT.");
    }
    // verify that the redirect_uri are consistent with the state token:
    if (!state.get("redirect_uri").getAsString().contains("https://" + request.getServerName() + "/lti/launch"))
        throw new Exception("Invalid redirect_uri.");
    // required
    verifyLtiMessageClaims(claims);
    User user = getUserClaims(claims);
    switch(claims.get("https://purl.imsglobal.org/spec/lti/claim/message_type").getAsString()) {
        case "LtiResourceLinkRequest":
            launchResourceLink(request, response, d, user, claims);
            break;
        case "LtiSubmissionReviewRequest":
            launchSubmissionReview(response, claims, d, user);
            break;
    }
}
Also used : JsonObject(com.google.gson.JsonObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 29 with Token

use of com.auth0.json.mgmt.Token in project jeecg-boot by jeecgboot.

the class JwtUtil method verify.

/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    try {
        // 根据密码生成JWT效验器
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
        // 效验TOKEN
        DecodedJWT jwt = verifier.verify(token);
        return true;
    } catch (Exception exception) {
        return false;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IOException(java.io.IOException) JeecgBootException(org.jeecg.common.exception.JeecgBootException) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Example 30 with Token

use of com.auth0.json.mgmt.Token in project vidflow-backend by CryptoSingh1337.

the class CustomAuthorizationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
    String requestPath = req.getServletPath();
    if (requestPath.equals(env.getProperty("auth.login.path")) || requestPath.equals(env.getProperty("auth.register.path")))
        filterChain.doFilter(req, res);
    else {
        String authToken = req.getHeader(AUTHORIZATION);
        String token = jwtUtils.extractAuthorizationToken(authToken);
        if (token != null) {
            JWTVerifier verifier = jwtUtils.getTokenVerifier();
            DecodedJWT decodedJWT = verifier.verify(token);
            String username = decodedJWT.getSubject();
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(req, res);
        } else {
            res.setStatus(HttpStatus.FORBIDDEN.value());
            res.setContentType("application/json");
            mapper.writeValue(res.getWriter(), new ErrorResponseModel("Missing Authorization Header"));
        }
    }
}
Also used : ErrorResponseModel(com.saransh.vidflow.model.response.ErrorResponseModel) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17