github.com/Azure/aad-pod-identity@v1.8.17/examples/rest-api/service/MyApiSolution/MyApi/Startup.cs (about) 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Authentication.JwtBearer; 6 using Microsoft.AspNetCore.Authorization; 7 using Microsoft.AspNetCore.Builder; 8 using Microsoft.AspNetCore.Hosting; 9 using Microsoft.AspNetCore.Mvc; 10 using Microsoft.Extensions.Configuration; 11 using Microsoft.Extensions.DependencyInjection; 12 using Microsoft.Extensions.Logging; 13 using Microsoft.Extensions.Options; 14 15 namespace MyApi 16 { 17 public class Startup 18 { 19 private static readonly string _tenantId; 20 private static readonly string _applicationId; 21 22 static Startup() 23 { 24 _tenantId = Environment.GetEnvironmentVariable("TENANT_ID"); 25 _applicationId = Environment.GetEnvironmentVariable("APPLICATION_ID"); 26 27 if (string.IsNullOrWhiteSpace(_tenantId)) 28 { 29 throw new ArgumentNullException("Environment variable TENANT_ID needs to be defined"); 30 } 31 if (string.IsNullOrWhiteSpace(_applicationId)) 32 { 33 throw new ArgumentNullException("Environment variable APPLICATION_ID needs to be defined"); 34 } 35 } 36 37 public Startup(IConfiguration configuration) 38 { 39 Configuration = configuration; 40 } 41 42 public IConfiguration Configuration { get; } 43 44 // This method gets called by the runtime. Use this method to add services to the container. 45 public void ConfigureServices(IServiceCollection services) 46 { 47 services 48 .AddAuthentication() 49 .AddJwtBearer(options => 50 { 51 options.Audience = _applicationId; 52 options.Authority = $"https://sts.windows.net/{_tenantId}/"; 53 }); 54 services.AddAuthorization(options => 55 { 56 var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( 57 JwtBearerDefaults.AuthenticationScheme); 58 59 defaultAuthorizationPolicyBuilder = 60 defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); 61 options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); 62 }); 63 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 64 } 65 66 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 67 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 68 { 69 if (env.IsDevelopment()) 70 { 71 app.UseDeveloperExceptionPage(); 72 } 73 74 app.UseMvc(); 75 } 76 } 77 }