How to convert Azure OpenIdConnect OWIN Cookie Auth Middleware to JavaScript JWT for the SPA application?

Advertisement

My ASP.NET MVC Core application uses the OWIN middleware with the following modules to perform OpenIdConnect authentication on Azure AD:

 using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Azure.ActiveDirectory.GraphClient; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions; 

The OWIN middleware performs a lot of tasks, including

Recovering Azure AD Groups and Roles Using the Azure Graph API
Retrieving user profile data from the database
Creating Claims from Steps 1 and 2
Issue of cookie
The middleware automatically manages Refresh tokens
The middleware caches the token in the database and can recover through an AcquireTokenSilentAsync mechanism for the graphical client.

The MVC application serves only one Razor view and from this point I use the Aurelia JavasScript framework (which can easily be angular, Knockout, React, not important) that only makes API requests to my Api controller via AJAX .

So, my question is how to convert all these authentication and authorization steps processed on the server to JWT-based authentication on the client versus Azure AD?

Granted, my question is pretty naive because there is substantial work being done by the OWIN middleware components in the code below. I am therefore looking for a starting point, auxiliary libraries and feasibility. I do not feel confident removing all the middleware code and server-side authentication until I'm confident this feed can be replicated using AJAX and JWT authentication.

I did some research and the answer may involve the following

adal.js
JWT middleware in ASP.NET Core
HTML Web Storage
Azure AD Graph REST API (instead of the C # graphical client)

Here is the current OWIN Middleware code that performs OpenIdConnect authentication on Azure AD on the server:

  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }   app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }   app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }   app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }   app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; }  app.UseCookieAuthentication(); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], ResponseType = OpenIdConnectResponseType.CodeIdToken, Events = new OpenIdConnectEvents() { OnAuthorizationCodeReceived = async (context) => { var code = context.TokenEndpointRequest.Code; var identity = context.Ticket.Principal.Identity as ClaimsIdentity; userObjectID = identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; signedInUserID = identity.FindFirst(ClaimTypes.NameIdentifier).Value; ClientCredential credential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); var authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"]; AuthenticationContext authContext = new AuthenticationContext(authority, new ADALTokenCacheService(signedInUserID, Configuration)); await authContext.AcquireTokenByAuthorizationCodeAsync( context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, Configuration["Authentication:AzureAd:GraphResource"]); context.HandleCodeRedemption(); ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClient(); // Get currently logged in User from Graph IPagedCollection users = await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(userObjectID)).ExecuteAsync(); IUser user = users.CurrentPage.ToList().First(); // Get User's AD Groups IEnumerable userGroupIds = await user.GetMemberGroupsAsync(false); List userGroupIdList = userGroupIds.ToList(); // Transform User's AD Groups into Claims foreach (var groupObjectId in userGroupIdList) { var group = await activeDirectoryClient.Groups.GetByObjectId(groupObjectId).ExecuteAsync(); Claim newClaim = new Claim( CustomClaimValueTypes.ADGroup, group.DisplayName, ClaimValueTypes.String, "AAD GRAPH"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } // Get User's Application permissions from Database upn = identity.FindFirst(ClaimTypes.Upn).Value; DbContext db = new DbContext(Configuration["ConnectionStrings:DefaultConnection"]); if (db.PortalUsers.FirstOrDefault(b => (b.UPN == upn)) == null) { throw new System.IdentityModel.Tokens.SecurityTokenValidationException("You are not registered to use this application."); } var applications = from permissions in db.PortalPermissions where permissions.PortalUser.UPN == upn //orderby permissions.Application.SortOrder ascending select permissions.PortalApplication; // Transform User's Application permissions into Claims foreach (var application in applications) { Claim newClaim = new Claim( CustomClaimValueTypes.Application, application.Name, ClaimValueTypes.String, "DATABASE"); ((ClaimsIdentity)(context.Ticket.Principal.Identity)).AddClaim(newClaim); } }, OnRemoteFailure = (context) => { if (context.Failure.Message == "You are not registered to use this application.") { context.Response.Redirect("/AuthenticationError"); } else { context.Response.Redirect("/Error"); } context.HandleResponse(); return Task.FromResult(0); } } }); app.UseFileServer(new FileServerOptions { EnableDefaultFiles = true, EnableDirectoryBrowsing = false }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Start}/{id?}"); }); } private ActiveDirectoryClient GetActiveDirectoryClient() { Uri servicePointUri = new Uri(Configuration["Authentication:AzureAd:GraphResource"]); Uri serviceRoot = new Uri(servicePointUri, Configuration["Authentication:AzureAd:TenantId"]); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient( serviceRoot, async () => await GetTokenForApplicationAsync()); return activeDirectoryClient; } private async Task GetTokenForApplicationAsync() { ClientCredential clientCredential = new ClientCredential( Configuration["Authentication:AzureAd:ClientId"], Configuration["Authentication:AzureAd:ClientSecret"]); AuthenticationContext authenticationContext = new AuthenticationContext( Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], new ADALTokenCacheService(signedInUserID, Configuration)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync( Configuration["Authentication:AzureAd:GraphResource"], clientCredential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; } 

The answer

The MVC application serves only one Razor view and from this point I use the Aurelia JavasScript framework (which can easily be angular, Knockout, React, not important) that only makes API requests to my Api controller via AJAX .

Do you mean that the ASP.NET MVC Core application will protect the API controller both by cookies and by the support token? And the Aurelia JavasScript framework will make the AJAX request to the API control using the support token?

If I understood correctly, you need to register another native application on the Azure portal for the authentication of the application that uses the Aurelia JavaScript framework (identical to the SPA call Web API that is protected by Azure AD here) ).

And for the existing ASP.NET MVC Core application to support token authentication, we need to add the JWT token token utility.

And if the Web API that publishes for your SPA application wants to call other resources, we must also check for authentication by method.

For example, if we call the Web API with a token (the token audience must be the application ID of your main ASP.Net MVC application), and the Web API must retrieve that token for the resource target using the stream described. Identity of the user with OAuth 2.0 on behalf of the draft specification to call the other Web API.

Update

 app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = ClientId, Authority = Authority, PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"], ResponseType = OpenIdConnectResponseType.CodeIdToken, GetClaimsFromUserInfoEndpoint = false, Events = new OpenIdConnectEvents { OnRemoteFailure = OnAuthenticationFailed, OnAuthorizationCodeReceived = OnAuthorizationCodeReceived, OnTokenValidated= context => { (context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(new Claim("AddByMyWebApp", "ClaimValue")); return Task.FromResult(0); } } });