Skip to content

Instantly share code, notes, and snippets.

@LauraKokkarinen
Last active May 13, 2024 12:31
Show Gist options
  • Save LauraKokkarinen/51062e87c2d1635c7fb17831293401e9 to your computer and use it in GitHub Desktop.
Save LauraKokkarinen/51062e87c2d1635c7fb17831293401e9 to your computer and use it in GitHub Desktop.
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
// Configure authentication for the web app (and the downstream API)
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(configuration, "WebApp")
// Enable on-behalf-of-flow for calling the downstream API as the logged in user
.EnableTokenAcquisitionToCallDownstreamApi(configuration["WebApi:Scopes"].Split(' '))
.AddDownstreamWebApi("WebApi", configuration.GetSection("WebApi"))
// Enable token caching
.AddDistributedTokenCaches();
// Enforce authentication for the web app views
services.AddControllersWithViews(options =>
{
var authorizationPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(authorizationPolicy));
})
.AddMicrosoftIdentityUI();
// Use Azure Redis Cache for token caching
services.AddStackExchangeRedisCache(options =>
{
options.InstanceName = configuration["RedisCache:InstanceName"];
options.Configuration = string.Format(configuration["RedisCache:Configuration"], configuration["RedisCache:Password"]);
});
var app = builder.Build();
// Enable authentication for the web app
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment