Friday, February 22, 2019

Once I have adal.js working in my Angular 7 app, how may I communicate my identity to a .NET Core 2.1 MVC application?

My Startup.cs is more or less what you see here save for the changes in green below.

Nasty!

using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Authentication.JwtBearer;

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Trifecta.Core.ExternalDependencies;
using Trifecta.Infrastructure.ExternalDependencies;
using Trifecta.RestApi.Helpers;
namespace Trifecta.RestApi
{
   public class Startup
   {
      public IConfiguration Configuration { get; }
      
      public Startup(IConfiguration configuration)
      {
         Configuration = configuration;
      }
      
      public void ConfigureServices(IServiceCollection services)
      {
         
services.AddAuthentication(sharedOptions =>
         {
            sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
         }).AddJwtBearer(options => Configuration.Bind("Adfs", options));

         services.AddCors();
         services.AddMvc(options =>
         {
            options.Filters.Add(new BubbleUpExceptions(
               Configuration,
               services.BuildServiceProvider().GetRequiredService<ILogWriting>(),
               services.BuildServiceProvider().GetRequiredService<ITimekeeping>()
            ));
         })
.AddJsonOptions(opt => opt.SerializerSettings.ContractResolver
               = new DefaultContractResolver())
               
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
         ConfigureIoC(services);
      }
      
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
         if (env.IsDevelopment())
         {
            app.UseDeveloperExceptionPage();
         }
         app.UseCors(builder =>
               builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
         
app.UseAuthentication();
         app.UseMvc();
      }
      
      public void ConfigureIoC(IServiceCollection services)
      {
         services.AddTransient<ILogWriting, LogWriting>();
         services.AddTransient<ITimekeeping, Timekeeping>();
      }
   }
}

 
 

My appsettings.json looks like this:

{
   "Adfs": {
      "Authority": "https://www.example.com/adfs",
      "Audience": "7c67b6a3-3ce6-4b81-a706-68ca145bb4de"
   },
   "FileFolderForLogs": "C:\\Temp\\Logs"
}

 
 

Herein, https://www.example.com/ corresponds to environment.activeDirectoryServer here while the adfs chunk at its end matches up to environment.activeDirectoryTenant and 7c67b6a3-3ce6-4b81-a706-68ca145bb4de would be kept in environment.activeDirectoryClient furthermore. In any of the actions in any of the controllers in my application, I may now do this:

string whoAmI = User.Identity.Name;

 
 

whoAmI will end up with your active directory username it in led by the domain with a backslash between the domain and the username! On the Angular side you have to communicate over the access token like so in order for whoAmI to not be null:

public GetContracts(token: string):void{
   let headers = new Headers({ 'Content-Type': 'application/json' });
   headers.set('Authorization', `Bearer ${token}`);
   let options = { headers, 'observe': 'response' };
   this.http.get(environment.apiUrl + "contract", options).toPromise().then(
      function(data:any) {
         let contract:any = JSON.parse(data._body);
         console.log(contract);
   }, function(error){
         console.log(error);
   })
}

No comments:

Post a Comment