Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx

Introduction

 
The practice of creating Custom APIs using ASP.NET core is increasing day by day as ASP.NET core is platform agnostic and is based on the C# language. Securing your API is very important as we do not want everyone to access the data, hence we will explore Azure AD based authentication in ASP.NET Core Web API and consume the API using SharePoint Framework.
 
There are two aspects to this article:
  1. Creating ASP.NET Core web API secured using Azure AD
  2. Consuming the API in SharePoint Framework
Let us first understand how we can create a secure web API.
 

ASP.NET Core Web API 

 
To create ASP.NET Core web API we can use .NET Core CLI or Visual Studio. In this article we will use Visual Studio to create a Web API.

Open Visual Studio and select Create a New Project.
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 
From the available template select ASP.NET Core Web Application as the type of the Project with C# as language
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 
Provide the project name as "SecuredWebAPI" and click on create
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 
In the next Screen Select API and then change the authentication type from No Authentication to Work or School Accounts. Provide the domain name of your tenant and click on OK login with tenant admin user if not already logged in.
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 
Internally when the API gets created there is an Azure AD application which also gets created as displayed in the image below
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx

In this Azure AD Application there is another thing called Expose an API which also has an entry with Scope configured. This is created by Visual Studio itself for our convenience. 
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 
We need to update the code in startup.cs so that it will accept a valid audience and valid Issuers. To do that update the below code in ConfigureServices method, comment the services.AddAuthentication line and replace it with the below code which will include valid audience and valid Issuers. We will also enable CORS as we will be consuming the Web API in SharePoint which would have a different domain.
  1. services.AddCors();  
  2.   
  3.             services.AddAuthentication(sharedoptions =>  
  4.             {  
  5.                 sharedoptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
  6.             }).AddJwtBearer(options =>  
  7.             {  
  8.                 options.Authority = "https://login.microsoftonline.com/52d05dd6-9e21-494f-8502-77658dbe16b8";  
  9.                 options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters  
  10.                 {  
  11.                     ValidAudiences = new List<string> { "https://testinglala.onmicrosoft.com/SecuredWebAPI" },  
  12.                     // set the following issuers if you want to support both V1 and V2 issuers  
  13.                     ValidIssuers = new List<string> { "https://sts.windows.net/52d05dd6-9e21-494f-8502-77658dbe16b8/",  
  14.                        "https://login.microsoftonline.com/52d05dd6-9e21-494f-8502-77658dbe16b8/v2.0" }  
  15.                 };  
  16.             });  
Now let us start the web API and test it in Postman to check whether it is authenticating or not.
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx


As displayed in the image the API provides us 401 Unauthorized as the output code
 

Consume the web API using SPFx


To consume the web API in SPFx let us first create an SPFx solution.
 
Use the below code in Node.js command prompt to create SPFx solution.
  1. md callSecuredAPIGraph  
  2.   
  3. cd callSecuredAPIGraph  
  4. yo @microsoft/sharepoint   
Select the below answers when prompted with questions as displayed in the image below.
 
We will use MSAL.js to fetch the token and use that token to call our web API. This token would be a bearer token so let us add the dependency of MSAL.js using the below command.
  1. npm install msal --save  
Now update the below code in the WebPart.ts file.
 
Import the reference to MSAL.js using the below code:
  1. import * as Msal from 'msal';  
Add the below variable as constants as we will not update those (Please update the clientId, authority and redirectUri as per your tenant and application id in azure ad and tenant Id):
  1. const msalConfig = {  
  2.     auth: {  
  3.         clientId: '914a7422-244b-4684-9e47-6f020d014967',  
  4.         authority: "https://login.microsoftonline.com/52d05dd6-9e21-494f-8502-77658dbe16b8",  
  5.         redirectUri: 'https://testinglala.sharepoint.com/_layouts/15/workbench.aspx'  
  6.     }  
  7. };  
  8. const msalObj = new Msal.UserAgentApplication(msalConfig);   
Now let us add the below code to fetch the token. We will fetch this before our code gets rendered update the render method with the below code:
  1. public render(): void {  
  2.     msalObj.handleRedirectCallback(error1 => {  
  3.         console.log(error1);  
  4.     });  
  5.     if (!msalObj.getAccount()) {  
  6.         msalObj.loginRedirect({  
  7.             scopes: ["https://testinglala.onmicrosoft.com/AzureADCoreAPI/user_impersonation"]  
  8.         });  
  9.     } else {  
  10.         msalObj.acquireTokenPopup({  
  11.             scopes: ["https://testinglala.onmicrosoft.com/AzureADCoreAPI/user_impersonation"]  
  12.         }).then((val) => {  
  13.             console.log(val);  
  14.             const element: React.ReactElement < ICallSecuredApiProps > = React.createElement(CallSecuredApi, {  
  15.                 description: this.properties.description,  
  16.                 context: this.context,  
  17.                 accessToken: val.accessToken  
  18.             });  
  19.             ReactDom.render(element, this.domElement);  
  20.         }).catch((error) => {  
  21.             console.log(error);  
  22.         });  
  23.     }  
  24. }   
To fetch the data from Web API let us update our CallSecuredApi.tsx file. Add a state variable response and initialize it with empty array and add below method which would fetch the API data:
  1. public componentDidMount() {  
  2.     this.props.context.httpClient.get('https://localhost:44364/api/values', HttpClient.configurations.v1, {  
  3.         headers: {  
  4.             'Authorization': `Bearer ${this.props.accessToken}`  
  5.         },  
  6.         method: 'GET'  
  7.     }).then((response: HttpClientResponse) => {  
  8.         response.json().then((val) => {  
  9.             console.log(val);  
  10.             this.setState({  
  11.                 response: val  
  12.             });  
  13.         }).catch((erro) => {  
  14.             console.log(erro);  
  15.         });  
  16.     }).catch((error) => {  
  17.         console.log(error);  
  18.     });  
  19. }   
Update the render method with the below code to display the obtained data from the web API.
  1. public render(): React.ReactElement  
  2. <ICallSecuredApiProps> {    
  3. return (    
  4.   
  5.     <div className={styles.callSecuredApi}>  
  6.         <div className={styles.container}>  
  7.             <div className={styles.row}>  
  8.                 <div className={styles.column}>  
  9.                     <span className={styles.title}>Welcome to SharePoint!</span>    
  10. {this.state.response && this.state.response.map((val) => {    
  11. return (  
  12.                     <div>{val}</div>);    
  13. })}    
  14.   
  15.                 </div>  
  16.             </div>  
  17.         </div>  
  18.     </div>    
  19. );    
  20.     
  21. }     
Now we can start our SPFx solution using the below code
  1. gulp serve  
Outcome
 
Create An ASP.NET Core API With Azure AD Authentication And Consuming It In SPFx
 

Conclusion

 
Securing Web API in ASP.NET core is very easy and consuming it in SPFx using MSAL.js gives us a good opportunity to create an end to end solution for enterprise which is scalable. We can leverage ASP.NET core API which can help us to create robust Web API for our desired application.
 
Happy Codding !!! 


Similar Articles