|
| 1 | +using Microsoft.AspNetCore.Authentication.OpenIdConnect; |
| 2 | +using Microsoft.AspNetCore.HttpOverrides; |
| 3 | +using Microsoft.Identity.Web; |
| 4 | +using Microsoft.Identity.Web.UI; |
| 5 | +using Microsoft.AspNetCore.Authentication.Cookies; |
| 6 | +using Azure.Extensions.AspNetCore.Configuration.Secrets; |
| 7 | +using Azure.Identity; |
| 8 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 9 | +using System.IdentityModel.Tokens.Jwt; |
| 10 | +using Microsoft.IdentityModel.Logging; |
| 11 | +using Constants = Microsoft.Identity.Web.Constants; |
| 12 | + |
| 13 | +var builder = WebApplication.CreateBuilder(args); |
| 14 | + |
| 15 | +var initialScopes = builder.Configuration[ |
| 16 | + $"{nameof(MicrosoftGraphOptions)}:{nameof(MicrosoftGraphOptions.Scopes)}" |
| 17 | +]?.Split(' '); |
| 18 | + |
| 19 | +builder.Services.AddEndpointsApiExplorer(); |
| 20 | +builder.Services.AddOptions(); |
| 21 | + |
| 22 | +// Add services to the container. |
| 23 | +builder.Services |
| 24 | + .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) |
| 25 | + .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(Constants.AzureAdB2C)) |
| 26 | + .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) |
| 27 | + .AddMicrosoftGraph(builder.Configuration.GetSection(nameof(MicrosoftGraphOptions))) |
| 28 | + .AddDistributedTokenCaches(); //we might need to change this to scale the app |
| 29 | + |
| 30 | +// builder.Services |
| 31 | +// .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 32 | +// .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(Constants.AzureAdB2C)) |
| 33 | +// .EnableTokenAcquisitionToCallDownstreamApi() |
| 34 | +// .AddMicrosoftGraph(builder.Configuration.GetSection(nameof(MicrosoftGraphOptions))) |
| 35 | +// .AddInMemoryTokenCaches(); |
| 36 | + |
| 37 | +builder.Services.AddSwaggerGen(c => c.SwaggerDoc("v1", new() { Title = "ADB2C", Version = "v1" })); |
| 38 | + |
| 39 | +// .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) |
| 40 | +// .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection(Constants.AzureAd)) |
| 41 | +// .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) |
| 42 | +// .AddMicrosoftGraph(builder.Configuration.GetSection(nameof(MicrosoftGraphOptions))) |
| 43 | +// .AddDistributedTokenCaches(); //we might need to change this to scale the app |
| 44 | + |
| 45 | +builder.Services.AddMicrosoftGraph(); |
| 46 | +builder.Services.AddProblemDetails(); |
| 47 | +builder.Services.AddHealthChecks(); |
| 48 | +JwtSecurityTokenHandler.DefaultMapInboundClaims = false; |
| 49 | +IdentityModelEventSource.LogCompleteSecurityArtifact = true; |
| 50 | +IdentityModelEventSource.ShowPII = true; |
| 51 | + |
| 52 | +builder.Services.Configure<CookieAuthenticationOptions>( |
| 53 | + CookieAuthenticationDefaults.AuthenticationScheme, |
| 54 | + options => options.AccessDeniedPath = "/AccessDenied" |
| 55 | +); |
| 56 | + |
| 57 | +// builder.Services.Configure<JwtBearerOptions>( |
| 58 | +// JwtBearerDefaults.AuthenticationScheme, |
| 59 | +// options => |
| 60 | +// { |
| 61 | +// options.Events = new JwtBearerEvents { OnAuthenticationFailed = AuthenticationFailed }; |
| 62 | +// } |
| 63 | +// ); |
| 64 | + |
| 65 | +builder.Services.AddAuthorization(options => |
| 66 | +{ |
| 67 | + // By default, all incoming requests will be authorized according to the default policy. |
| 68 | + options.FallbackPolicy = options.DefaultPolicy; |
| 69 | +}); |
| 70 | + |
| 71 | +//if the access to the webapp needs to be limited to a specific role, set the role in the appsettings.json |
| 72 | +//if the role is not set, the webapp will be open to all authenticated users |
| 73 | +//this allows you to show a friendly access denied message with optional instructions for your users |
| 74 | +//how to get access if they want to or if they can |
| 75 | +//this access policy is set on the index.html and on the controller through [Authorize(Policy = "alloweduser")] attribute |
| 76 | +var requiredUserRoleForAccess = builder.Configuration["AzureAdB2C:AllowedUsersRole"]; |
| 77 | +if (!IsNullOrEmpty(requiredUserRoleForAccess)) |
| 78 | +{ |
| 79 | + builder.Services |
| 80 | + .AddAuthorizationBuilder() |
| 81 | + .AddDefaultPolicy( |
| 82 | + "alloweduser", |
| 83 | + policy => |
| 84 | + { |
| 85 | + policy.RequireAuthenticatedUser(); |
| 86 | + policy.RequireRole(requiredUserRoleForAccess); |
| 87 | + } |
| 88 | + ); |
| 89 | +} |
| 90 | +else |
| 91 | +{ |
| 92 | + builder.Services |
| 93 | + .AddAuthorizationBuilder() |
| 94 | + .AddDefaultPolicy("alloweduser", policy => policy.RequireAuthenticatedUser()); |
| 95 | +} |
| 96 | + |
| 97 | +builder.Services.Configure<SessionOptions>( |
| 98 | + builder.Configuration.GetSection(nameof(SessionOptions)) |
| 99 | +); |
| 100 | +builder.Services.AddSession(); |
| 101 | + |
| 102 | +// options => |
| 103 | +// { |
| 104 | +// options.IdleTimeout = TimeSpan.FromMinutes(1); //You can set Time |
| 105 | +// options.Cookie.IsEssential = true; |
| 106 | +// options.Cookie.SameSite = SameSiteMode.None; |
| 107 | +// options.Cookie.SecurePolicy = CookieSecurePolicy.Always; |
| 108 | +// options.Cookie.HttpOnly = true; |
| 109 | +// }); |
| 110 | + |
| 111 | +builder.Services.AddRazorPages().AddMicrosoftIdentityUI(); |
| 112 | + |
| 113 | +builder.Services.AddHttpClient(); // use iHttpFactory as best practice, should be easy to use extra retry and hold off policies in the future |
| 114 | + |
| 115 | +// The following lines code instruct the asp.net core middleware to use the data in the "roles" claim in the Authorize attribute and User.IsInrole() |
| 116 | +// See https://docs.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info. |
| 117 | +builder.Services.Configure<OpenIdConnectOptions>( |
| 118 | + OpenIdConnectDefaults.AuthenticationScheme, |
| 119 | + builder.Configuration.GetSection(nameof(OpenIdConnectOptions)) |
| 120 | +); |
| 121 | + |
| 122 | +var app = builder.Build(); |
| 123 | + |
| 124 | +// this setting is used when you use tools like ngrok or reverse proxies like nginx which connect to http://localhost |
| 125 | +// if you don't set this setting the sign-in redirect will be http instead of https |
| 126 | +app.UseForwardedHeaders( |
| 127 | + new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedProto } |
| 128 | +); |
| 129 | + |
| 130 | +// Configure the HTTP request pipeline. |
| 131 | +if (app.Environment.IsDevelopment()) |
| 132 | +{ |
| 133 | + app.UseDeveloperExceptionPage(); |
| 134 | + app.UseSwagger(); |
| 135 | + app.UseSwaggerUI(); |
| 136 | +} |
| 137 | +else |
| 138 | +{ |
| 139 | + app.UseHsts(); |
| 140 | + app.UseExceptionHandler("/Error"); |
| 141 | +} |
| 142 | + |
| 143 | +app.UseSession(); |
| 144 | +app.UseHttpsRedirection(); |
| 145 | +app.UseStaticFiles(); |
| 146 | + |
| 147 | +app.UseRouting(); |
| 148 | + |
| 149 | +app.UseAuthentication(); |
| 150 | +app.UseAuthorization(); |
| 151 | + |
| 152 | +app.UseCookiePolicy(new CookiePolicyOptions { Secure = CookieSecurePolicy.Always }); |
| 153 | + |
| 154 | +app.MapRazorPages(); |
| 155 | +app.MapControllers(); |
| 156 | + |
| 157 | +// generate an api-key on startup that we can use to validate callbacks |
| 158 | +env.SetEnvironmentVariable("API-KEY", guid.NewGuid().ToString()); |
| 159 | + |
| 160 | +app.Run(); |
0 commit comments