Simple token based authentication/authorization in asp.net core for Mongodb datastore(用于 Mongodb 数据存储的 asp.net 核心中基于简单令牌的身份验证/授权)
问题描述
我需要实现非常简单的身份验证机制,基本上有 2 个角色:Owners
和 Users
.而且我认为拥有 Enum 就足够了.应用程序本身是带有通过 Asp.net 核心实现的 webapi 的 SPA.我看到了文章 - 如何使用 EF Identity 实现它,但他们的模型看起来比我实际需要的要复杂得多,而且 EF 面向 SQL db,我使用的是 mongo.所以我的用户看起来像:
I need to implement pretty simple auth mechanizm with basically 2 roles: Owners
and Users
. And I think that having Enum for that will be enough. App itself is SPA with webapi implemented via Asp.net core. I saw article - how to implement it using EF Identity, but their models looks much more complex than I actually need and EF oriented to SQL db, and I using mongo. So my user will looks something like:
class UserModel{
Id,
Token,
Roles: ["Owners", "Users"],
...
}
那么我需要实现哪些接口并将其添加到 DI 才能使用[Authorize]
和 [Authorize(Roles="Users")]
属性并且它们根据我在标头中发送的令牌正常工作?
So what interfaces I need to implement and add to DI to be able use
[Authorize]
and [Authorize(Roles="Users")]
attribute and they worked correctly based on token I send in header?
推荐答案
让我澄清一点@Adem 的答案.您需要以特定方式实现自定义中间件.实现这一点需要实现 3 个抽象类(答案对于 asp.net core rc2
btw 是正确的):
Let me clarify a little @Adem's answer. You need to to implement custom middleware in specific way. There is 3 abstract classes that need to be implemented to implementing this (answer is correct for asp.net core rc2
btw):
Microsoft.AspNetCore.Builder.AuthenticationOptions
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware
Microsoft.AspNetCore.Authentication.AuthenticationHandler
然后将此中间件添加到您的启动类中.
and then add this middleware to your startup class.
代码示例:
public class TokenOptions : AuthenticationOptions
{
public TokenOptions() : base()
{
AuthenticationScheme = "Bearer";
AutomaticAuthenticate = true;
}
}
public class AuthMiddleware : AuthenticationMiddleware<TokenOptions>
{
protected override AuthenticationHandler<TokenOptions> CreateHandler()
{
return new AuthHandler(new TokenService());
}
public AuthMiddleware(RequestDelegate next, IOptions<TokenOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder) : base(next, options, loggerFactory, encoder)
{
}
}
public class AuthHandler : AuthenticationHandler<TokenOptions>
{
private ITokenService _tokenService;
public AuthHandler(ITokenService tokenService)
{
_tokenService = tokenService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string token = null;
AuthenticateResult result = null;
string token = Helper.GetTokenFromHEader(Request.Headers["Authorization"]);
// If no token found, no further work possible
if (string.IsNullOrEmpty(token))
{
result = AuthenticateResult.Skip();
}
else
{
bool isValid = await _tokenService.IsValidAsync(token);
if (isValid)
{
//assigning fake identity, just for illustration
ClaimsIdentity claimsIdentity = new ClaimsIdentity("Custom");
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "admin"));
claims.Add(new Claim(ClaimTypes.NameIdentifier, "admin"));
claims.Add(new Claim(ClaimTypes.Role, "admin"));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
result =
AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal,
new AuthenticationProperties(), Options.AuthenticationScheme));
}
else
{
result = AuthenticateResult.Skip();
}
}
return result;
}
}`
附言该代码仅用于说明想法.当然,您需要实现自己的处理程序.
这篇关于用于 Mongodb 数据存储的 asp.net 核心中基于简单令牌的身份验证/授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于 Mongodb 数据存储的 asp.net 核心中基于简单令牌的身份验证/授权
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01