.Net 7
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security.DataHandler.Encoder;
using PAP.Web.Helpers;
using PAP.Web.Services;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
//builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// configure strongly typed settings object
AppSettings AppSettings = new AppSettings();
builder.Configuration.GetSection("AppSettings").Bind(AppSettings);
// Now start using it
string OauthIssuer = AppSettings.OAuthIssuer;
string OauthClientId = AppSettings.OAuthClientId;
var OauthSecret = TextEncodings.Base64Url.Decode(AppSettings.OAuthSecret);
builder.Services.AddAuthentication(auth =>
{
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(cookie =>
{
cookie.AccessDeniedPath = "logout";
cookie.SlidingExpiration = true;
})
.AddJwtBearer(jwt =>
{
jwt.Audience = OauthClientId;
jwt.Authority = OauthIssuer;
jwt.RequireHttpsMetadata = false;
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = OauthIssuer,
ValidAudience = OauthClientId,
IssuerSigningKey = new SymmetricSecurityKey(OauthSecret),
ValidateIssuer = true,
RequireAudience = true,
RequireExpirationTime = true,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = false,
ValidateTokenReplay = false,
ValidateActor = false,
ValidateAudience = true,
ClockSkew = TimeSpan.Zero
};
jwt.Configuration = new OpenIdConnectConfiguration();
});
builder.Services.AddCon`enter code here`trollers();
// configure strongly typed settings object
//builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// configure DI for application services
//builder.Services.AddScoped<IUserService, UserService>();
var app = builder.Build();
IdentityModelEventSource.ShowPII = true;
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
if (!app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseHsts();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
AppSettings.cs
namespace PAP.Web.Helpers;
public class AppSettings
{
public string OAuthIssuer { get; set; }
public string OAuthClientId { get; set; }
public string OAuthSecret { get; set; }
}