要创建一个ASP.NET Core混合Razor Pages / React SPA应用程序,并使用Cognito身份验证,可以按照以下步骤进行操作:
创建一个新的ASP.NET Core Web应用程序项目。
安装必要的NuGet包。在项目文件中添加以下包引用:
using Amazon.Extensions.CognitoAuthentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
public void ConfigureServices(IServiceCollection services)
{
// 添加Cognito身份验证服务
services.AddCognitoIdentity(config =>
{
config.UserPoolId = "YOUR_USER_POOL_ID";
config.ClientId = "YOUR_CLIENT_ID";
});
// 配置身份验证中间件
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.ResponseType = "code";
options.MetadataAddress = "https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/openid-configuration";
options.ClientId = "YOUR_CLIENT_ID";
options.ClientSecret = "YOUR_CLIENT_SECRET";
});
// 添加Razor页面服务
services.AddRazorPages();
}
请确保将YOUR_USER_POOL_ID
,YOUR_CLIENT_ID
,YOUR_CLIENT_SECRET
替换为Cognito用户池和应用程序的实际值。
Login.cshtml.cs
的类,并添加以下代码:using Amazon.AspNetCore.Identity.Cognito;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Threading.Tasks;
public class LoginModel : PageModel
{
private readonly SignInManager _signInManager;
public LoginModel(SignInManager signInManager)
{
_signInManager = signInManager;
}
public async Task OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (result?.Succeeded == true)
{
return LocalRedirect(returnUrl);
}
else
{
return Challenge(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = returnUrl });
}
}
public async Task OnGetLogoutAsync()
{
await _signInManager.SignOutAsync();
return RedirectToPage("/Index");
}
}
创建一个React SPA。在ClientApp文件夹中创建一个新的React应用程序。
在React应用程序中实现Cognito身份验证。可以使用AWS Amplify库来简化身份验证流程。在ClientApp文件夹中运行以下命令安装AWS Amplify:
npm install aws-amplify
import Amplify from 'aws-amplify';
import { AmazonCognitoIdentityProvider } from '@aws-amplify/auth';
Amplify.configure({
Auth: {
region: 'YOUR_REGION',
userPoolId: 'YOUR_USER_POOL_ID',
userPoolWebClientId: 'YOUR_CLIENT_ID',
authenticationFlowType: 'USER_PASSWORD_AUTH',
identityProvider: AmazonCognitoIdentityProvider
}
});
确保将YOUR_REGION
,YOUR_USER_POOL_ID
,YOUR_CLIENT_ID
替换为Cognito用户池和应用程序的实际值。
Auth
模块来处理身份验证。以下是一个简单的示例:import { useState } from '