Pearson
Always Learning


Authentication Libraries

These code samples break down the basic steps to getting a token and can be helpful as you're just getting started or if you want to build your own framework. But we also encourage you to use the new LearningStudio Libraries to make it much easier to manage authentication.

Parameter Descriptions

In the code samples below, we use placeholders for certain parameters that will be specific to your application, campus, and users. Parameters are enclosed in curly brackets, e.g., {applicationId}. A description of each is in the table below.

Important: When replacing the placehodler with your value, also replace the brackets. For example, replace {clientString} with abcd not {abcd}.

Name Description
{applicationId} The API Key for your Application. You can get one of these by creating an app here on the PDN portal. More Info
{clientString} The Client String for the LearningStudio Campus you're connecting to. For Sandbox Campus, this is provided when you request an API key.
{applicationName} The name of your application. This is not validated and can be anything, but don't use spaces or special characters.
{tokenKeyMoniker} The Token Key Moniker for the campus you're connecting to. For Sandbox Campus this is provided when you request an API key.
{sharedSecret} The Shared Secret for the campus you're connecting to. For Sandbox Campus this is provided when you request an API key.
{username} The user's username or login id.
{userPassword} The user's password.

Getting a Token When You Know the User's Password

Also called the Password Grant Type for OAuth 2, this code demonstrates how to get a user token when you know the user's username and password. For more information, read the OAuth 2 overview.

Java  Python  Ruby  PHP  C#

This code sample requires JDK 6 or higher.

// Java Libraries
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.lang.reflect.Type;
import javax.net.ssl.HttpsURLConnection;
 
// Google Gson Libraries used for Json Parsing
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
/**
 * Very basic console app that demonstrates how to make an access token request on
 * behalf of a LearningStudio user via the OAuth 2.0 Password grant type
 */
public class OAuth2Password {
 
    public static void main( final String[] args) throws Exception
    {
        // Setup the variables necessary to make the Request
        String grantType = "password";
        String applicationID = "{applicationId}";
        String clientString = "{clientString}";
        String username = "{username}";
        String password = "{password}";
        String url = "https://api.learningstudio.com/token";
        HttpsURLConnection httpConn = null;
        BufferedReader in = null;
 
        try {
 
            // Create the data to send
            StringBuilder data = new StringBuilder();
            data.append("grant_type=" + URLEncoder.encode(grantType, "UTF-8"));
            data.append("&client_id=" + URLEncoder.encode(applicationID, "UTF-8"));
            data.append("&username=" + URLEncoder.encode(clientString + "\\" + username, "UTF-8"));
            data.append("&password=" + URLEncoder.encode(password, "UTF-8"));
 
            // Create a byte array of the data to be sent
            byte[] byteArray = data.toString().getBytes("UTF-8");
 
            // Setup the Request
            URL request = new URL(url);
            httpConn = (HttpsURLConnection)request.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Length", "" + byteArray.length);
            httpConn.setDoOutput(true);
 
            // Write data
            OutputStream postStream = httpConn.getOutputStream();
            postStream.write(byteArray, 0, byteArray.length);
            postStream.close();
 
            // Send Request & Get Response
            InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
            in = new BufferedReader(reader);
 
            // Get the Json reponse containing the Access Token
            String json = in.readLine();
            System.out.println("Json String = " + json);
 
            // Parse the Json response and retrieve the Access Token
            Gson gson = new Gson();
            Type mapType  = new TypeToken<Map<String,String>>(){}.getType();
            Map<String,String> ser = gson.fromJson(json, mapType);
            String accessToken = ser.get("access_token");
            System.out.println("Access Token = " + accessToken);
 
        } catch (java.io.IOException e) {
 
            // This exception will be raised if the server didn't return 200 - OK
            // Retrieve more information about the error
            System.out.println(e.getMessage());
 
        } finally {
 
            // Be sure to close out any resources or connections
            if (in != null) in.close();
            if (httpConn != null) httpConn.disconnect();
        }
    }
}

Creating and Signing An Assertion

In most cases you don't have a reason to know the user's password. Maybe you're a third party application or the institution handles their own identity management. In these cases you'll create an Assertion for the username and use it to request a token. For more information, read the OAuth 2 overview and the page on building assertions.

Java  Python  Ruby  PHP  C#

This code sample requires JDK 6 or higher. It also has a dependency on the Bouncy Castle crypto library.

// Java Libraries
import java.io.*;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import javax.net.ssl.HttpsURLConnection;
 
// Bouncy Castle Libraries used for CMAC encryption
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;
import org.bouncycastle.util.Strings;
 
// Google Gson Libraries used for Json Parsing
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
/**
 * Very basic console app that demonstrates how to make an access token request on
 * behalf of a LearningStudio user via the OAuth 2.0 Assertion grant type
 */
public class OAuth2Assertion {
 
    public static void main( final String[] args) throws Exception
    {
        // Setup the variables necessary to make the Request
        String grantType = "assertion";
        String assertionType = "urn:ecollege:names:moauth:1.0:assertion";
        String applicationName = "{applicationName}";
        String keyMoniker = "{tokenKeyMoniker}";
        String applicationID = "{applicationId}";
        String clientString = "{clientString}";
        String username = "{username}";
        String secret = "{sharedSecret}";
        String url = "https://api.learningstudio.com/token";
        HttpsURLConnection httpConn = null;
        BufferedReader in = null;
 
        // Create the Assertion String
        String assertion = buildAssertion(applicationName, keyMoniker, applicationID, clientString,
            username, secret);
 
        try {
 
            // Create the data to send
            StringBuilder data = new StringBuilder();
            data.append("grant_type=" + URLEncoder.encode(grantType, "UTF-8"));
            data.append("&assertion_type=" + URLEncoder.encode(assertionType, "UTF-8"));
            data.append("&assertion=" + URLEncoder.encode(assertion, "UTF-8"));
 
            // Create a byte array of the data to be sent
            byte[] byteArray = data.toString().getBytes("UTF-8");
 
            // Setup the Request
            URL request = new URL(url);
            httpConn = (HttpsURLConnection)request.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Length", "" + byteArray.length);
            httpConn.setDoOutput(true);
 
            // Write data
            OutputStream postStream = httpConn.getOutputStream();
            postStream.write(byteArray, 0, byteArray.length);
            postStream.close();
 
            // Send Request &amp; Get Response
            InputStreamReader reader = new InputStreamReader(httpConn.getInputStream());
            in = new BufferedReader(reader);
 
            // Get the Json reponse containing the Access Token
            String json = in.readLine();
            System.out.println("Json String = " + json);
 
            // Parse the Json response and retrieve the Access Token
            Gson gson = new Gson();
            Type mapType  = new TypeToken<map>&gt;(){}.getType();
            Map<String,String> ser = gson.fromJson(json, mapType);
            String accessToken = ser.get("access_token");
            System.out.println("Access Token = " + accessToken);
 
        } catch (java.io.IOException e) {
 
            // This exception will be raised if the server didn't return 200 - OK
            // Retrieve more information about the error
            System.out.println(e.getMessage());
 
        } finally {
 
            // Be sure to close out any resources or connections
            if (in != null) in.close();
            if (httpConn != null) httpConn.disconnect();
        }
    }
 
 
   /**
       * Builds an OAuth 2.0 assertion string
       *
       * @param   applicationName    The name of the application brokering the token request
       * @param   keyMoniker    The assigned API key moniker
       * @param   applicationID    The assigned API application id
       * @param   clientString  The string value that uniquely identifies the campus/school
       * @param   username    The LearningStudio user's external identifier
       * @param   secret      The secret key used to sign the assertion string
       *
       * @return  A signed, encoded, and fully constructed assertion string
       *
       * @throws  UnsupportedEncodingException
       */
    private static String buildAssertion(
        String applicationName,
        String keyMoniker,
        String applicationID,
        String clientString,
        String username,
        String secret
    ) throws UnsupportedEncodingException
    {
        // Get the UTC Date Timestamp
        DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
        gmtFormat.setTimeZone(gmtTime);
        String timestamp = gmtFormat.format(new Date())+ "Z";
 
        // Setup the Assertion String
        String assertion = applicationName + "|" + keyMoniker + "|" + applicationID + "|" +
        clientString + "|" + username + "|" + timestamp;
 
        // Generate the CMAC used for Assertion Security
        String cmac = generateCmac(secret, assertion);
 
        // Add the CMAC to the Assertion String
        assertion = assertion + "|" + cmac;
        System.out.println("Assertion String = " + assertion);
        return assertion;
    }
 
   /**
       * Generates a HEX-encoded CMAC-AES digest
       *
       * @param   key The secret key used to sign the data
       * @param   msg The data to be signed
       *
       * @return  A CMAC-AES digest
       *
       * @throws  UnsupportedEncodingException
       */
    private static String generateCmac(String key, String msg)
        throws UnsupportedEncodingException
    {
        byte[] keyBytes = key.getBytes("UTF-8");
        byte[] data = msg.getBytes("UTF-8");
 
        CMac macProvider = new CMac(new AESFastEngine());
        macProvider.init(new KeyParameter(keyBytes));
        macProvider.reset();
 
        macProvider.update(data, 0, data.length);
        byte[] output = new byte[macProvider.getMacSize()];
        macProvider.doFinal(output, 0);
 
        return Strings.fromUTF8ByteArray(Hex.encode(output));
    }
}
6041 reads
Always Learning
Pearson