使用Blazor Server搭建基于AWS Cognito Hosted UI的身份认证系统
步骤如下:
首先,需要在AWS中创建Cognito用户池,并在其中配置基于Hosted UI的身份认证系统。在这个过程中,可以自定义UI界面的样式和内容,使其适配Blazor Server应用程序的模板。
在Blazor Server项目中引入AWS SDK for .NET,并在Startup.cs文件中添加以下代码:
services.AddAWSService
这样就能通过HttpContextAccessor在应用程序中访问当前用户的身份信息。
@inject AmazonCognitoIdentityProviderClient cognitoClient @inject AuthenticationStateProvider authenticationStateProvider
async Task Login() { var authState = await authenticationStateProvider.GetAuthenticationStateAsync(); var username = authState.User.Identity.Name; var password = "password"; var clientId = "client_id"; var poolId = "pool_id";
var authReq = new InitiateAuthRequest
{
ClientId = clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
AuthParameters = new Dictionary()
{
{ "USERNAME", username },
{ "PASSWORD", password },
},
};
var authResp = await cognitoClient.InitiateAuthAsync(authReq);
if (authResp.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
{
// handle change password flow
}
}
var authResult = await cognitoClient.AdminInitiateAuthAsync(adminAuthReq); var authState = await authenticationStateProvider.GetAuthenticationStateAsync(); var user = new ClaimsPrincipal(new ClaimsIdentity(ParseClaims(authResult.AuthenticationResult.IdToken), "jwt"));
var authStateProvider = (CustomAuthStateProvider)authenticationStateProvider; authStateProvider.SetAuthenticationState(Task.FromResult(new AuthenticationState(user)));
上一篇:BlazorServerauthwithjwt的中文
下一篇:BlazorServer报错“Nooverloadformethod'CustomerOrderInsert'takes10arguments”