Skip to content

Commit

Permalink
fix:alter project structure.add oidc support.
Browse files Browse the repository at this point in the history
  • Loading branch information
arthuridea committed Dec 27, 2023
1 parent 6cbb98c commit 84698ed
Show file tree
Hide file tree
Showing 18 changed files with 301 additions and 40 deletions.
10 changes: 9 additions & 1 deletion NetCore.AIGC.sln
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,17 @@ EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMService.Baidu.ErnieVilg", "src\LLMService.Baidu.ErnieVilg\LLMService.Baidu.ErnieVilg.csproj", "{E3AE89E4-31A0-4EDA-9154-2D089E1FD8A4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03.Docs", "03.Docs", "{7E5E6C28-ABB2-4564-AF1B-D9FCC81B8353}"
ProjectSection(SolutionItems) = preProject
docs\build.cmd = docs\build.cmd
docs\docfx.json = docs\docfx.json
docs\index.md = docs\index.md
docs\toc.yml = docs\toc.yml
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LLMService.OpenAI.ChatGPT", "src\LLMService.OpenAI.ChatGPT\LLMService.OpenAI.ChatGPT.csproj", "{09322116-1405-47CE-BBB5-35E02167905D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02.Sample", "02.Sample", "{0B000384-47E8-4013-A1CE-59A465017EF2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -57,7 +65,7 @@ Global
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{3CA26111-12C9-4AF1-966F-45019EA52385} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{3CA26111-12C9-4AF1-966F-45019EA52385} = {0B000384-47E8-4013-A1CE-59A465017EF2}
{DC8A11BE-3268-4F1E-B83F-27958041ABF1} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{E73CB18F-26D3-4A6C-8AA2-E89FF17B65C5} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
{E3AE89E4-31A0-4EDA-9154-2D089E1FD8A4} = {01705FE5-59E6-4B65-B545-5DFD3AFB1F16}
Expand Down
4 changes: 2 additions & 2 deletions src/LLMService.Shared/ChatService/ChatServiceBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ namespace LLMService.Shared.ChatService
/// <summary>
///
/// </summary>
/// <typeparam name="TRequestDto">The type of the request dto.</typeparam>
/// <typeparam name="TResponseDto">The type of the response dto.</typeparam>
/// <typeparam name="TRequestDto">The type of the request dto.<see cref="IChatRequest{TMessageContent}"/></typeparam>
/// <typeparam name="TResponseDto">The type of the response dto.<see cref="IChatResponse{TBackendResponseDto}"/></typeparam>
/// <typeparam name="TBackendRequestDto">The type of the backend request dto.</typeparam>
/// <typeparam name="TBackendResponseDto">The type of the backend response dto.</typeparam>
/// <typeparam name="TChatMessage">The type of the chat message.</typeparam>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authorization;
using LLMServiceHub.Common;

#nullable enable
namespace LLMServiceHub.Areas.GitHubIdentity.Controllers
{
/// <summary>
///
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" />
//[NonController]
[AllowAnonymous]
[Area("GitHubIdentity")]
[Route("[area]/[controller]/[action]")]
public class AccountController : Controller
{
/// <summary>
/// Handles user sign in.
/// </summary>
/// <param name="scheme">Authentication scheme.</param>
/// <param name="redirectUri">Redirect URI.</param>
/// <returns>Challenge generating a redirect to Azure AD to sign in the user.</returns>
[HttpGet("{scheme?}")]

Check warning on line 29 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)

Check warning on line 29 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)
public IActionResult SignIn(
[FromRoute] string scheme,
[FromQuery] string redirectUri)
{
scheme ??= AppConsts.GitHubAuthScheme;
string redirect;
if (!string.IsNullOrEmpty(redirectUri) && Url.IsLocalUrl(redirectUri))
{
redirect = redirectUri;
}
else
{
redirect = Url.Content("~/")!;
}

return Challenge(
new AuthenticationProperties { RedirectUri = redirect },
scheme);
}

/// <summary>
/// Challenges the user.
/// </summary>
/// <param name="redirectUri">Redirect URI.</param>
/// <param name="scope">Scopes to request.</param>
/// <param name="loginHint">Login hint.</param>
/// <param name="domainHint">Domain hint.</param>
/// <param name="claims">Claims.</param>
/// <param name="policy">AAD B2C policy.</param>
/// <param name="scheme">Authentication scheme.</param>
/// <returns>Challenge generating a redirect to Azure AD to sign in the user.</returns>
[HttpGet("{scheme?}")]

Check warning on line 61 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)

Check warning on line 61 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)
public IActionResult Challenge(
string redirectUri,
string scope,
string loginHint,
string domainHint,
string claims,
string policy,
[FromRoute] string scheme)
{
scheme ??= AppConsts.GitHubAuthScheme;
Dictionary<string, string?> items = new Dictionary<string, string?>
{
{ Constants.Claims, claims },
{ Constants.Policy, policy },
};
Dictionary<string, object?> parameters = new Dictionary<string, object?>
{
{ Constants.LoginHint, loginHint },
{ Constants.DomainHint, domainHint },
};

OAuthChallengeProperties oAuthChallengeProperties = new OAuthChallengeProperties(items, parameters);
if (scope != null)
{
oAuthChallengeProperties.Scope = scope.Split(" ");
}
oAuthChallengeProperties.RedirectUri = redirectUri;

return Challenge(
oAuthChallengeProperties,
scheme);
}

/// <summary>
/// Handles the user sign-out.
/// </summary>
/// <param name="scheme">Authentication scheme.</param>
/// <returns>Sign out result.</returns>
[HttpGet("{scheme?}")]

Check warning on line 100 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)

Check warning on line 100 in src/LLMServiceHub/Areas/GitHubIdentity/Controllers/AccountController.cs

View workflow job for this annotation

GitHub Actions / build

Route '{scheme?}' conflicts with another action route. An HTTP request that matches multiple routes results in an ambiguous match error. Fix the conflict by changing the route's pattern, HTTP method, or route constraints. (https://aka.ms/aspnet/analyzers)
public IActionResult SignOut(
[FromRoute] string scheme)
{
if (AppServicesAuthenticationInformation.IsAppServicesAadAuthenticationEnabled)
{
if (AppServicesAuthenticationInformation.LogoutUrl != null)
{
return LocalRedirect(AppServicesAuthenticationInformation.LogoutUrl);
}
return Ok();
}
else
{
scheme ??= AppConsts.GitHubAuthScheme;
var callbackUrl = Url.Page("/Account/SignedOut", pageHandler: null, values: null, protocol: Request.Scheme);
return SignOut(
new AuthenticationProperties
{
RedirectUri = callbackUrl,
},
CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
}
#nullable disable
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@page
@model LLMServiceHub.Areas.GitHubIdentity.Pages.Account.SignedOutModel
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LLMServiceHub.Areas.GitHubIdentity.Pages.Account
{
/// <summary>
/// Model for the SignOut page.
/// </summary>
[AllowAnonymous]
public class SignedOutModel : PageModel
{
/// <summary>
/// Method handling the HTTP GET method.
/// </summary>
/// <returns>A Sign Out page or Home page.</returns>
public IActionResult OnGet()
{
if (User?.Identity?.IsAuthenticated ?? false)
{
//return LocalRedirect("~/");
}

//return Page();
var returnUrl = HttpContext.Request.Query["returnUrl"];
if(string.IsNullOrEmpty(returnUrl))
{
returnUrl = "~/";
}
return LocalRedirect(returnUrl);
}
}
}
12 changes: 12 additions & 0 deletions src/LLMServiceHub/Common/AppConsts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,17 @@ public static class AppConsts
/// The authentication cookie name
/// </summary>
public const string AuthCookieName = "LLMService.Auth";
/// <summary>
/// The antiforgery cookie name
/// </summary>
public const string AntiforgeryCookieName = "LLMService.Antiforgery";
/// <summary>
/// The microsoft authentication scheme
/// </summary>
public const string MicrosoftAuthScheme = "Microsoft";
/// <summary>
/// The git hub authentication scheme
/// </summary>
public const string GitHubAuthScheme = "GitHub";
}
}
27 changes: 27 additions & 0 deletions src/LLMServiceHub/Common/AppRuntimeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Authentication;

namespace LLMServiceHub.Common
{
/// <summary>
///
/// </summary>
public static class AppRuntimeExtensions
{
/// <summary>
/// Gets the external providers asynchronous.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public static async Task<AuthenticationScheme[]> GetExternalProvidersAsync(this HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);

var schemes = context.RequestServices.GetRequiredService<IAuthenticationSchemeProvider>();

return (from scheme in await schemes.GetAllSchemesAsync()
where !string.IsNullOrEmpty(scheme.DisplayName)
select scheme).ToArray();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace LLMServiceHub.Controller.v1_0
namespace LLMServiceHub.Controllers.v1_0
{
/// <summary>
/// 集成百度AI类api
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using LLMServiceHub.Common;
using Microsoft.AspNetCore.Mvc;

namespace LLMServiceHub.Controller.v1_0
namespace LLMServiceHub.Controllers.v1_0
{
/// <summary>
///
Expand Down
5 changes: 5 additions & 0 deletions src/LLMServiceHub/LLMServiceHub.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="8.0.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.0.0" />
<PackageReference Include="AspNet.Security.OAuth.GitHub" Version="8.0.0" />
<PackageReference Include="IdentityModel" Version="6.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.QuickGrid.EntityFrameworkAdapter" Version="8.0.0" />
Expand All @@ -51,6 +52,7 @@
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.0" />
<PackageReference Include="Polly.Extensions" Version="8.2.0" />
<PackageReference Include="Polly.Extensions.Http" Version="3.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<!--<PackageReference Include="NSwag.AspNetCore" Version="13.20.0" />-->
<PackageReference Include="SwaggerDoc" Version="1.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
Expand All @@ -71,6 +73,9 @@
</ItemGroup>

<ItemGroup>
<Folder Include="Areas\GitHubIdentity\Data\" />
<Folder Include="Areas\GitHubIdentity\Models\" />
<Folder Include="Areas\GitHubIdentity\Views\" />
<Folder Include="Areas\MicrosoftIdentity\Controllers\" />
<Folder Include="Areas\MicrosoftIdentity\Data\" />
<Folder Include="Areas\MicrosoftIdentity\Models\" />
Expand Down
32 changes: 13 additions & 19 deletions src/LLMServiceHub/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -360,34 +360,28 @@
</form>
</div>
<div class="hr-text">or</div>
<div class="card-body">
<div class="card-body p-3">
<div class="row">
<div class="col">
<p>
<div>
<environment exclude="Development">
暂不支持第三方登录
</environment>
<environment exclude="Production">
<a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">MS Sign in</a>
<a class="btn btn-small" asp-area="MicrosoftIdentity" asp-controller="Account" asp-route-scheme="Microsoft" asp-action="SignIn">
<img src="~/images/Microsoft_logo.svg" class="brand-logo me-2" width="16" height="16" asp-append-version="true" />
微软账户登录
</a>
<a class="btn btn-small" asp-area="GitHubIdentity" asp-controller="Account" asp-route-scheme="GitHub" asp-action="SignIn">
<img src="~/images/github-mark.svg" class="brand-logo me-2" width="16" height="16" asp-append-version="true" />
GitHub账户登录
</a>

</environment>


</p>
</div>
</div>
@* <div class="col">
<a href="#" class="btn w-100">
<!-- Download SVG icon from http://tabler-icons.io/i/brand-github -->
<svg xmlns="http://www.w3.org/2000/svg" class="icon text-github" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"></path></svg>
Login with Github
</a>
</div>
<div class="col">
<a href="#" class="btn w-100">
<!-- Download SVG icon from http://tabler-icons.io/i/brand-twitter -->
<svg xmlns="http://www.w3.org/2000/svg" class="icon text-twitter" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M22 4.01c-1 .49 -1.98 .689 -3 .99c-1.121 -1.265 -2.783 -1.335 -4.38 -.737s-2.643 2.06 -2.62 3.737v1c-3.245 .083 -6.135 -1.395 -8 -4c0 0 -4.182 7.433 4 11c-1.872 1.247 -3.739 2.088 -6 2c3.308 1.803 6.913 2.423 10.034 1.517c3.58 -1.04 6.522 -3.723 7.651 -7.742a13.84 13.84 0 0 0 .497 -3.753c0 -.249 1.51 -2.772 1.818 -4.013z"></path></svg>
Login with Twitter
</a>
</div> *@

</div>
</div>
</div>
Expand Down
34 changes: 25 additions & 9 deletions src/LLMServiceHub/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ public class IndexModel : PageModel
[TempData]
public string ErrorMessage { get; set; }

/// <summary>
/// Gets or sets the OAuth schemes.
/// </summary>
/// <value>
/// The OAuth schemes.
/// </value>
public AuthenticationScheme[] OAuthSchemes { get; set; }

/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
Expand Down Expand Up @@ -101,17 +109,12 @@ public async Task OnGet(string returnUrl = null)
ModelState.AddModelError(string.Empty, ErrorMessage);
}

OAuthSchemes = await HttpContext.GetExternalProvidersAsync();

returnUrl ??= Url.Content("~/");

if(!User.Identity.IsAuthenticated)
{
var result = await HttpContext.AuthenticateAsync(OpenIdConnectDefaults.AuthenticationScheme);
if (result.Succeeded)
{
await ExecSignIn(AppConsts.DefaultAuthScheme, result.Principal.Identity.Name, true, returnUrl);
Redirect(returnUrl);
}
}
await ChallengeExternal(AppConsts.MicrosoftAuthScheme, returnUrl);
await ChallengeExternal(AppConsts.GitHubAuthScheme, returnUrl);

ReturnUrl = returnUrl;
}
Expand Down Expand Up @@ -148,6 +151,19 @@ public async Task<IActionResult> OnPostAsync(string returnUrl = null)
return Page();
}

private async Task ChallengeExternal(string scheme, string returnUrl)
{
if (!User.Identity.IsAuthenticated)
{
var result = await HttpContext.AuthenticateAsync(scheme);
if (result.Succeeded)
{
await ExecSignIn(AppConsts.DefaultAuthScheme, result.Principal.Identity.Name, true, returnUrl);
Redirect(returnUrl);
}
}
}

private async Task ExecSignIn(string scheme, string identityUserName, bool rememberme, string returnUrl)
{
// set authentication cookie
Expand Down
Loading

0 comments on commit 84698ed

Please sign in to comment.