使用授权属性和基于自定义声明的身份验证

时间:2018-02-20 17:41:09

标签: c# asp.net authentication authorization claims-based-identity

我想在我的ASP.net MVC项目中使用基于声明的身份验证构建我自己的身份验证过程。我希望能够使用Authorize属性(包括角色),例如[Authorize(Roles="admin")][Authorize(Roles="Frontenduser")],因为我将拥有多种类型的用户。

我不想使用ASP.net身份,因为它比我需要的要多得多。我还需要为不同类型的用户存储完全不同的数据。

我知道我可以继承AuthorizeAttribute类,但我不确定它是如何与声明一起使用的。首先,任何人都可以推荐使用基于声明的身份验证的良好程序包,其次,如何停止使用ASP.net身份的Authorize属性并使其与我的基于声明的自定义身份验证一起使用? 我已经看过网络上的其他问题和其他解决方案,但我找不到合适的解释或解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用基于策略的授权。身份是身份验证,与授权不同。为此,您可以在启动类中制定策略。这是我在配置服务中的一个例子。如果您不需要身份,则可以使用JWT承载令牌并制定策略。 从nuget获取这些包:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;



      public void ConfigureServices(IServiceCollection services)
        {

  //new policy makes [Authorize (Policy = "Your custom Policy")] availible by claims This is what you put on controllers
            services.AddAuthorization((options) => {
                options.AddPolicy("Your custom Policy", policybuilder =>
                {               
                    policybuilder.RequireAuthenticatedUser();
                    policybuilder.RequireClaim("role", "PayingUserExampleProperty");

                });
            });

在您的配置

添加

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
    app.UseAuthentication();
...

好好读到这个:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies

相关问题