If you haven’t noticed yet, we are updating the OfficeDev GitHub with Office 365 samples. I wanted to highlight one of the samples I published last week during the GA announcement – Office 365 APIs Multi-Tenant Web Application.
This sample shows how to build an MVC web application that uses Azure Active Directory for sign-in and then calls a Office 365 API under the signed-in user’s identity using tokens obtained via OAuth 2.0.
Project README will help you get started with the app.
If you are looking for the authentication specific code (info is also available in the README), then:
Quick Look at the SSO Authentication Code
The authentication startup class, App_Start/Startup.Auth.cs in the project contains the startup logic for Azure AD authentication.
The project implements a simple ADAL token cache NaiveSessionCache that uses the ASP.Net session to store and retrieve tokens for the current user. As it name suggests, it is very naive and is not recommended for production use.A more persistent cache such as database is recommended for production use.
Sign In and Sign Out Controls
The sign in and sign out controls are already added to the views. You can find them under Views\Shared folder.
1. _LoginPartial.cshtml is the partial view that renders the Sign In and Sign Out actions.
2. _LoginPartial.cshtml is then rendered in _Layout.cshtml
3. The AccountController.cs has the required methods for sign in and sign out.
Requiring authentication to access controllers
Applying Authorize attribute to all controllers in your project will require the user to be authenticated before accessing these controllers.
To allow the controller to be accessed anonymously, remove this attribute from the controller.
If you want to set the permissions at a more granular level, apply the attribute to each method that requires authorization instead of applying it to the controller class.
SingleTenant Web Application Walk-throughs
The code you write for multi-tenant and single-tenant is quite different.
The GitHub project linked in this post focuses on building multi-tenant web application.
Below are some good resources for building Office 365 API single-tenant web applications:
- Starter Project: Office 365 APIs Single-Tenant Web Application
- Scot Hillier‘s Walk-through on building a single-tenant MVC web application from scratch