Using a Variable to get an Access Token

Options
Justin.B.253
Justin.B.253 Posts: 12 🌱
edited February 20 in Social Groups

I have created an application that allows an instructor to create their sandbox courses and then enroll themselves into that sandbox. I'm currently using an access token from Postman and as long as I continue to manually refresh the token, the application works fine. I'm ready to use it production but this is where I'm running into an issue. I don't understand how to dynamically pull get a token and have it refreshed. I"m wondering, while using javascript, can a dynamically request a token from D2L and hold it in a variable? I'm asking if its both possible and if I am on the right track because my console messages when I run it, I get errors. This is part of what I am using as a reference. I'm still new to coding so this has been a learning curve.

const client_id = 'your_client_id';

    const client_secret = 'your_client_secret';
    const redirect_uri = 'https://myschool.brightspace.com/';
    const token_endpoint = 'https://auth.brightspace.com/core/connect/token';
    const create_course_endpoint = 'https://myschool.brightspace.com/d2l/api/lp/1.45/courses/';
    const enrollments_endpoint = 'https://myschool.brightspace.com/d2l/api/lp/1.45/enrollments/';
    const users_endpoint = 'https://myschool.brightspace.com/d2l/api/lp/1.45/users/';
    async function getAccessToken() {
      const formData = new URLSearchParams();
      formData.append('client_id', client_id);
      formData.append('client_secret', client_secret);
      formData.append('grant_type', 'client_credentials');

Tagged:

Comments

  • Per.R.998
    Per.R.998 Posts: 1 🌱
    Options

    I have had the exact same issue: D2L does not allow the grant_type = client_credentials - you will have to use grant_type = authorization_code - and thereby involving a Brightspace user to get this authorization code - that can exchanged to a set of Accesstoken and Refreshtoken

    All the Best

    Per Rosenbeck, Web Developer at CED, Aarhus University

  • Robert.R.757
    Robert.R.757 Posts: 7 🌱
    Options

    I have also ran into this issue. Once you get an access token and refresh token via Postman, you will need to save the refresh token. Once the access token expires, you can call the https://auth.brightspace.com/core/connect/token endpoint and pass the refresh token as a parameter. This endpoint will then return you a new access token as well as a new refresh token.