使用 OpenID 将 Blazor 与 AWS Cognito 集成



我正在尝试将 aws cognito 集成到 Blazor 服务器应用程序中。我已经在cognito中配置了用户池,并将启动更改为

services.AddAuthentication()
.AddCookie()
.AddOpenIdConnect(options =>
{
options.ResponseType = "code";
options.MetadataAddress = "address here";
options.ClientId = "clientid";
options.ClientSecret = "secret";
});

现在如何在 Blazor 应用程序加载后显示 CogniTo 登录页,然后在登录后,我想重定向到 Blazor 默认页。 请提供任何帮助。

我花了几天时间试图弄清楚这一切。 以下是我想出的。

程序.cs

builder.Services.AddAuthentication(opt =>
{
opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; 
opt.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, opt =>
{
opt.Authority = builder.Configuration["AWS:Authority"]; //"https://cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-XXXXX/";
opt.ClientId = builder.Configuration["Secret_AWS:ClientId"]; 
opt.ClientSecret = builder.Configuration["Secret_AWS:ClientSecret"]; 
opt.ResponseType = OpenIdConnectResponseType.Code;
opt.SaveTokens = true;
opt.GetClaimsFromUserInfoEndpoint = true;
opt.UseTokenLifetime = true;
opt.Scope.Add("openid");
opt.Scope.Add("email");
opt.Scope.Add("profile");
opt.CallbackPath = "/signin-oidc";  //This is where you can change the callback path.  Just remember to change the ReturnUrl in the Cognito console
opt.TokenValidationParameters = new TokenValidationParameters()
{
NameClaimType = "name"
};
opt.Events = new OpenIdConnectEvents //if you want to see what is going on during the authentication handshake, you can hook into these events as follows (only first one shown for brevity) 
{
//order of calling during login.  OnRedirectToIdentityProvider, OnMessageReceived, OnAuthorizationCodeReceived, OnTokenResponseReceived, OnTokenValidated, OnUserInformationReceived, OnTicketReceived, 
OnRedirectToIdentityProvider = async ctx =>
{
AuthEventFlow = $"{AuthEventFlow}OnRedirectToIdentityProvider, ";
}
}
});
string? AuthEventFlow;

我发现研究 Cognito 身份验证终端节点 Amazon Cognito 终端节点链接很有用。 似乎很多魔术都是由于设置opt而发生的。GetClaimsFromUserInfoEndpoint = true。 然后,OpenIdConnect 通过查询用户池 ID/.well-known/openid-configuration https://cognito-idp.Region.amazonaws.com/your 获取所有各种 Cognito 端点

要调用 Cognito 托管的 UI,请在"页面"文件夹中创建以下 Razor 页面

登录.cshtml

@page
@model AmmanControls.Pages.LoginModel
@{
}

登录.cshtml.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace XXXX.Pages
{
public class LoginModel : PageModel
{
public async Task OnGet(string redirectUri)
{
await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = redirectUri });  
//This was a critical point for me - it is the entry point to the OpenIdConnect login events
}
}
}

Logout.cshtml

@page
@model AmmanControls.Pages.LogoutModel
@{
}

Logout.cshtml.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace XXX.Pages
{
public class LogoutModel : PageModel
{
public async Task<IActionResult> OnGetAsync()
{
await HttpContext.SignOutAsync();
return Redirect("/");
}
}
}

然后,按如下方式调用这些页面:

Shared\LoginDisplay.razor

<AuthorizeView>
<Authorized>
<a>Hello, @context.User.Identity.Name </a>
<form method="get" action="logout">
<button type="submit" class="nav-link btn btn-link">Log out</button>
</form>     
</Authorized>
<NotAuthorized>
<a href="login?redirectUri=/">Log in</a>
</NotAuthorized>
</AuthorizeView>

必须承认,当我最终单击"登录"按钮并且所有重定向都正常工作时,我简直不敢相信!

我现在遇到的问题是,即使用户经过身份验证,@context.User.Identity.Name 也是空的,我正在研究如何将经过身份验证的用户的名称从声明中获取到 ClaimPrincipal 中。 当我弄清楚时,会发布更新。

最新更新