From 9982e7f0805d09adc01887e4898af9364c9e8c79 Mon Sep 17 00:00:00 2001 From: Tan <75737870+Tanyuu@users.noreply.github.com> Date: Sun, 6 Aug 2023 01:30:27 +0800 Subject: [PATCH] feat: Support AddCasdoorWebApi method (#59) Signed-off-by: Tan <2912363476@qq.com> --- .../Casdoor.AspNetCore.csproj | 4 ++++ src/Casdoor.AspNetCore/ServiceExtension.cs | 24 +++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/Casdoor.AspNetCore/Casdoor.AspNetCore.csproj b/src/Casdoor.AspNetCore/Casdoor.AspNetCore.csproj index e40a61b..ce5058c 100644 --- a/src/Casdoor.AspNetCore/Casdoor.AspNetCore.csproj +++ b/src/Casdoor.AspNetCore/Casdoor.AspNetCore.csproj @@ -43,18 +43,22 @@ + + + + diff --git a/src/Casdoor.AspNetCore/ServiceExtension.cs b/src/Casdoor.AspNetCore/ServiceExtension.cs index e05c0ad..fd4f479 100644 --- a/src/Casdoor.AspNetCore/ServiceExtension.cs +++ b/src/Casdoor.AspNetCore/ServiceExtension.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Authentication.JwtBearer; namespace Casdoor.AspNetCore.Authentication { @@ -49,9 +50,10 @@ public static AuthenticationBuilder AddCasdoor(this AuthenticationBuilder builde public static AuthenticationBuilder AddCasdoor(this AuthenticationBuilder builder, string applicationType, Action optionAction) { builder.Services.AddCasdoorClient(optionAction); - return applicationType switch { - CasdoorDefaults.WebAppApplicationType => builder.AddCasdoorWebApp(o => {}), - CasdoorDefaults.WebApiApplicationType => builder.AddCasdoorWebApi(o => {}), + return applicationType switch + { + CasdoorDefaults.WebAppApplicationType => builder.AddCasdoorWebApp(o => { }), + CasdoorDefaults.WebApiApplicationType => builder.AddCasdoorWebApi(o => { }), _ => throw new ArgumentOutOfRangeException(nameof(applicationType)) }; } @@ -85,9 +87,21 @@ public static AuthenticationBuilder AddCasdoorWebApp(this AuthenticationBuilder return builder; } - public static AuthenticationBuilder AddCasdoorWebApi(this AuthenticationBuilder builder, Action openIdOptionAction) + public static AuthenticationBuilder AddCasdoorWebApi(this AuthenticationBuilder builder, Action jwtBearerOptionAction) { - throw new NotImplementedException("WebApi is not supported yet."); + builder.Services.AddAuthentication(options => + { + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }); + builder.Services.AddOptions(JwtBearerDefaults.AuthenticationScheme).Configure( + (options, casdoorOptions) => + { + options.Authority = casdoorOptions.Protocols.Authority; + options.Audience = casdoorOptions.Protocols.Audience; + } + ); + builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, jwtBearerOptionAction); + return builder; } } }