Giter VIP home page Giter VIP logo

o365-edu.ng's Introduction

page_type products languages extensions
sample
office-365
ms-graph
typescript
contentType technologies services platforms createdDate scenarios
samples
Microsoft Graph
Education
Office 365
AngularJS
1/20/2017 2:19:22 PM
Education

EDUGraphAPI - Office 365 Education Code Sample (TypeScript)

In this sample, we show you how to integrate with school roles/roster data as well as O365 services available via the Graph API.

School data is kept in sync in O365 Education tenants by Microsoft School Data Sync.

Table of Contents

Sample Goals

The sample demonstrates:

EDUGraphAPI is based on NodeJS (the server-side) and Angular 2 (the client-side).

Prerequisites

Deploying and running this sample requires:

  • An Azure subscription with permissions to register a new application, and deploy the web app.

  • An O365 Education tenant with Microsoft School Data Sync enabled.

    • One of the following browsers: Edge, Internet Explorer 9, Safari 5.0.6, Firefox 5, Chrome 13, or a later version of one of these browsers.

    Additionally: Developing/running this sample locally requires the following:

Register the application in Azure Active Directory

  1. Sign into the new Azure Portal: https://portal.azure.com/.

  2. Choose your Azure AD tenant by selecting your account in the top right corner of the page:

  3. Click Azure Active Directory -> App registrations -> +Add.

  4. Input a Name, and select Web app / API as Application Type.

    Input Sign-on URL: https://localhost:44380/

    Click Create.

  5. Once completed, the app will show in the list.

  6. Click it to view its details.

  7. Click All settings, if the setting window did not show.

    • Click Properties, then set Multi-tenanted to Yes.

      Copy aside Application ID, then Click Save.

    • Click Required permissions. Add the following permissions:

      API Application Permissions Delegated Permissions
      Microsoft Graph Read directory data Read all users' full profiles
      Read directory data
      Read directory data
      Access directory as the signed in user
      Sign users in
      Windows Azure Active Directory Sign in and read user profile
      Read and write directory data

    • Click Keys, then add a new key:

      Click Save, then copy aside the VALUE of the key.

    Close the Settings window.

Build and debug locally

This project can be opened with the edition of Visual Studio 2015 you already have, or download and install the Community edition to run, build and/or develop this application locally.

The following tools are also required:

Debug the EDUGraphAPI.Web:

  1. Configure Environment Variables. Right-click the project in Solution Explorer, then click Properties.

    • clientId: use the Client Id of the app registration you created earlier.
    • clientSecret: use the Key value of the app registration you created earlier.
    • SourceCodeRepositoryURL: use the repository URL of your fork.
  2. In the Solution Explorer, right-click npm, then click Install Missing npm Packages:

  3. Press F5.

Deploy the sample to Azure

GitHub Authorization

  1. Generate Token

    • Open https://github.com/settings/tokens in your web browser.
    • Sign into your GitHub account where you forked this repository.
    • Click Generate Token
    • Enter a value in the Token description text box
    • Select the followings (your selections should match the screenshot below):
      • repo (all) -> repo:status, repo_deployment, public_repo
      • admin:repo_hook -> read:repo_hook

    • Click Generate token
    • Copy the token
  2. Add the GitHub Token to Azure in the Azure Resource Explorer

    • Click PUT

Deploy the Azure Components from GitHub

  1. Check to ensure that the build is passing VSTS Build.

  2. Fork this repository to your GitHub account.

  3. Click the Deploy to Azure Button:

    Deploy to Azure

  4. Fill in the values in the deployment page and select the I agree to the terms and conditions stated above checkbox.

    • Resource group: we suggest you create a new group.

    • Site Name: please input a name. Like EDUGraphAPITest003 or EDUGraphAPI993.

      Note: If the name you input is taken, you will get some validation errors:

      Click it you will get more details like storage account is already in other resource group/subscription.

      In this case, please use another name.

    • Source Code Repository URL: replace with the repository name of your fork.

    • Source Code Manual Integration: choose false, since you are deploying from your own fork.

    • Client Id: use the Client Id of the app registration you created earlier.

    • Client Secret: use the Key value of the app registration you created earlier.

    • Check I agree to the terms and conditions stated above.

  5. Click Purchase.

Add REPLY URL to the app registration

  1. After the deployment, open the resource group:

  2. Click the web app.

    Copy the URL aside and change the schema to https. This is the replay URL and will be used in next step.

  3. Navigate to the app registration in the new Azure Portal, then open the setting windows.

    Add the reply URL:

    Note: to debug the sample locally, make sure that https://localhost:44380/ is in the reply URLs.

  4. Click SAVE.

Understand the code

Introduction

Solution Component Diagram

The top layer of the solution contains the two parts of the EDUGraphAPI.Web project:

  • The server-side Node.js app.
  • The client side Angular 2 app.

The bottom layers contain the three data sources.

  • The EDUGraphAPI database.
  • Education data exposed by REST APIs.
  • Azure AD data exposed by Graph APIs.

EDUGraphAPI.Web - Server

The server-side app is based on Node.js and implemented with Typescript.

Authentication Mechanisms

Passport and its 2 plugins are used to enable local and O365 authentications:

  • passport-azure-ad: a collection of Passport Strategies to help you integrate with Azure Active Directory. It includes OpenID Connect, WS-Federation, and SAML-P authentication and authorization. These providers let you integrate your Node app with Microsoft Azure AD so you can use its many features, including web single sign-on (WebSSO), Endpoint Protection with OAuth, and JWT token issuance and validation.
  • passport-local: this module lets you authenticate using a username and password in your Node.js applications. By plugging into Passport, local authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

The 2 kinds of authentication are implemented in the /auth/appAuth.ts file.

Web APIs

The server app exposes several Web APIs:

Path Method Description
/api/me GET Return the current user and the user's organization and roles
/api/me/favoriteColor POST Update current user's favorite color
/api/me/accesstoken GET Get current user's access token
/api/tenant POST Update information (isAdminConsented) of current user's tenant
/api/tenant/unlinkAllUsers POST Unlink all users in current user's tenant
/api/users/linked GET Get all linked users
/api/users/:userId/unlink POST Unlink the specified user
/api/admin/consent GET Redirect the user to login page to perform admin consent
/api/admin/consented POST Will be invoked after admin consented
/api/schools/seatingArrangements/:classId GET/POST Get or set the seating arrangement of the specified class

These APIs are defined in the /routes folder.

Data Access

Sequelize is used in this sample to access data from a SQL Database.

The DbContext exposes the models and methods that are used to access data.

The tables used in this demo:

Table Description
Users Contains the user's information: name, email, hashed password...
O365UserId and O365Email are used to connect the local user with an O365 user.
UserRoles Contains users' role. Three roles are used in this sample: admin, teacher, and student.
Organizations A row in this table represents a tenant in AAD.
IsAdminConsented column records than if the tenant consented by an administrator.
TokenCache Contains the users' access/refresh tokens.
ClassroomSeatingArrangements Contains the classroom seating arrangements.

You will find the DbContext class and related model interfaces in the /data/dbContext.ts file.

Services

The services used by the server-side app:

Service Description
MSGraphClient Contains methods used to access MS Graph APIs
SchoolService Contains two methods: get/update seating arrangements
TenantService Contains methods that operate tenants in the database
TokenCacheService Contains method used to get and update cache from the database
UserService Contains method used to manipulate users in the database

The services are in the /services folder.

Multi-tenant app

This web application is a multi-tenant app. In the AAD, we enabled the option:

Users from any Azure Active Directory tenant can access this app. Some permissions used by this app require an administrator of the tenant to consent before users can use the app. Otherwise, users will see this error:

For more information, see Build a multi-tenant SaaS web application using Azure AD & OpenID Connect.

EDUGraphAPI.Web - Client

The client-side app which resides in the /app folder is based on Angular 2 and is also implemented with Typescript 2.

Note: Getting and using declaration files in TypeScript 2.0 is much easier than in TypeScript 1. To get declarations for a library like lodash for example, all you need is npm:

npm install --save @types/lodash

Components

These components are used in the client app.

Folder Component
/ App
/aboutme AboutMe
/admin Admin
LinkedAccounts
Consent
/demoHeoper DemoHelper
/header Header
/link Link
LinkCreateLocal
LinkLoginLocal
LinkLoginO365Requried
/login Login
/O365login O365login
/register Register
/schools Schools
Classes
MyClasses
ClassDetails

Services

Folder Name
/aboutme AboutMeService
/admin AdminService
/demoHelper DemoHelperService
/link LinkService
/services MeService
UserService
UserPhotoService
DataService

Office 365 Education API

The Office 365 Education APIs return data from any Office 365 tenant which has been synced to the cloud by Microsoft School Data Sync. The APIs provide information about schools, sections, teachers, students, and rosters. The Schools REST API provides access to school entities in Office 365 for Education tenants.

In this sample, the Microsoft.Education Class Library project encapsulates the Office 365 Education API.

The EducationServiceClient is the core class of the library. It is used to easily get education data.

Get schools

getSchools(): Observable<any[]> {
    return this.dataService.getArray<any>(this.urlBase + "/administrativeUnits");
}
getSchoolById(id: string): Observable<any> {
    return this.dataService.getObject(this.urlBase + '/administrativeUnits/' + id );
}

Get classes

getClasses(schoolId: string, nextLink: string): Observable<PagedCollection<any>> {
    let url: string = this.urlBase + "/groups?$top=12&$filter=extension_fe2174665583431c953114ff7268b7b3_Education_ObjectType%20eq%20'Section'%20and%20extension_fe2174665583431c953114ff7268b7b3_Education_SyncSource_SchoolId%20eq%20'" + schoolId + "'" + (nextLink ? "&" + GraphHelper.getSkipToken(nextLink) : '');
    return this.dataService.getPagedCollection<any>(url);
}
getClassById(classId: string): Observable<any> {
    return this.dataService.getObject<any>(this.urlBase + "/groups/" + classId + "?$expand=members");
}

Get users

getUsers(schoolId: string, nextLink: string): Observable<PagedCollection<any>> {
    var url = this.urlBase + "/administrativeUnits/" + schoolId + "/members?$top=12" +
  (nextLink ? "&" + GraphHelper.getSkipToken(nextLink) : '');
    return this.dataService.getPagedCollection<any>(url);
}

Below are some screenshots of the sample app that show the education data.

In /app/services/dataService.ts, three generic methods simplify the invoking of REST APIs.

  • getObject: sends an HTTP GET request to the target endpoint, and deserializes the JSON response string to T, and return the result object.
  • getPagedCollection: sends an HTTP GET request to the target endpoint, and deserializes the JSON response string to PagedCollection, and return the result object.
  • getArray: sends an HTTP GET request to the target endpoint, and deserializes the JSON response string to an array, and return the array.

For HTTP GET request sent by the 3 methods above, an access token is included in the bearer authentication header.

Authentication Flows

There are 4 authentication flows in this project.

The first 2 flows (Local Login/O365 Login) enable users to login in with either a local account or an Office 365 account, then link to the other type account. This procedure is implemented in the LinkController.

Local Login Authentication Flow

O365 Login Authentication Flow

Admin Login Authentication Flow

This flow shows how an administrator logs into the system and performs administrative operations.

After logging into the app with an office 365 account, the administrator will be asked to link to a local account. This step is not required and can be skipped.

As mentioned earlier, the web app is a multi-tenant app which uses some application permissions, so tenant administrator must consent the app first.

This flow is implemented in the AdminController.

Two Kinds of Graph APIs

There are two distinct Graph APIs used in this sample:

Azure AD Graph API Microsoft Graph API
Description The Azure Active Directory Graph API provides programmatic access to Azure Active Directory through REST API endpoints. Apps can use the Azure AD Graph API to perform create, read, update, and delete (CRUD) operations on directory data and directory objects, such as users, groups, and organizational contacts A unified API that also includes APIs from other Microsoft services like Outlook, OneDrive, OneNote, Planner, and Office Graph, all accessed through a single endpoint with a single access token.
Client Install-Package Microsoft.Azure.ActiveDirectory.GraphClient Install-Package Microsoft.Graph
End Point https://graph.windows.net https://graph.microsoft.com
API Explorer https://graphexplorer.cloudapp.net/ https://graph.microsoft.io/graph-explorer

IMPORTANT NOTE: Microsoft is investing heavily in the new Microsoft Graph API, and they are not investing in the Azure AD Graph API anymore (except fixing security issues).

Therefore, please use the new Microsoft Graph API as much as possible and minimize how much you use the Azure AD Graph API.

Below is a piece of code shows how to get "me" from the Microsoft Graph API.

public getMe(): Promise<any> {
    return new Promise((resolve, reject) => {
        request
            .get(Constants.MSGraphResource + "/v1.0/me/?$select=id,givenName,surname,userPrincipalName,assignedLicenses")
            .set('Authorization', 'Bearer ' + this.accessToken)
            .end((err, res) => {
                if (err) { return reject(err) }
                resolve(res.body);
            })
    })
}

Note that in the AAD Application settings, permissions for each Graph API are configured separately:

Questions and comments

  • If you have any trouble running this sample, please log an issue.
  • Questions about GraphAPI development in general should be posted to Stack Overflow. Make sure that your questions or comments are tagged with [ms-graph-api].

Contributing

We encourage you to contribute to our samples. For guidelines on how to proceed, see our contribution guide.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Copyright (c) 2017 Microsoft. All rights reserved.

o365-edu.ng's People

Contributors

tylerlu avatar o365devx avatar rick-kirkham avatar nokafor avatar supernova-eng avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.