【发布时间】:2020-06-08 12:52:53
【问题描述】:
我有一个使用 MongoDB 作为数据库的 Blazor Server 应用程序,因此我正在尝试使用它来实现身份验证。所以我可以在剃须刀页面中使用<Authenticted>, <AuthorizeView Roles="admin"> 和其他类似的标签。
内置的身份验证模板使用 SQL Server,在这种情况下我不想要它,并且没有一个明确的示例说明如何自己使用另一个数据库进行操作。鉴于微软提供的示例here
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
namespace BlazorSample.Services
{
public class CustomAuthStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "mrfibuli"),
}, "Fake authentication type");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
}
应该如何在应用程序中使用它?您显然不会硬编码单个值和值类型,作为您唯一的身份验证来源。那么应该如何参数化呢?具有本地属性,例如:
Username { get; set; }
UserType { get; set; }
在这种情况下,你会在哪里设置?
然后你将如何使用它来验证用户?我在ConfigurationServices(...)方法下的启动文件中添加了类:
...
services.AddScoped<AuthenticationStateProvider, MongoAuthenticationStateProvider>();
...
我不知道如何验证任何人。我想您可以通过多种方式验证用户名和密码,然后当您知道这很好时,您可以继续更新 .NET 中的身份验证。我正在关注一个教程,他们在后面的代码中提出了类似的建议:
using System;
using System.Linq;
using DocsPlatform.Services;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
namespace DocsPlatform.Pages
{
public class LoginBase : ComponentBase
{
[CascadingParameter]
private Task<AuthenticationState> authStateTask { get; set; }
protected string username { get; set; }
protected string password { get; set; }
protected async Task LoginUser()
{
bool isValid = true;
isValid = dbService.ValidateUser(username, password);
string email = dbService.GetEmail(username);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Email, email),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));
return NavigationManager.NavigateTo("/");
}
}
}
但是,返回中的导航不起作用(他们甚至没有解释他们的代码是如何编译的),并且 SignInAsync() 方法在他们展示的方式中不可用。同样,我不知道他们的代码是如何编译的。那么通常如何做到这一点呢?
除了数百个仅使用内置 SQL Server 模板的示例之外,我找不到任何教程、示例等。在哪里可以找到有关如何使用它的详细信息?除了“使用内置模板”或文档链接here 之外的任何内容都将不胜感激,因为它们都没有解释如何执行此操作。
【问题讨论】:
-
完美的问题说明了这是多么糟糕的记录。我和你在同一个地方。
标签: c# mongodb authentication asp.net-core blazor