Identityserver 4基于角色的登录

时间:2019-12-24 14:02:03

标签: c# asp.net-core identityserver4

我正在为Identityserver进行辅助项目,我能够进行身份验证并调用api。 现在我想赋予不同的API函数不同的权限角色, 当我将某些api函数标记为[Authorize(Roles =“ RegularUsers”)]时,无论我尝试了什么,我都会不断收到403-forbidden。 我在这里附加代码:

IdentityServer4-Startup.cs:

  public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = _configuration["ConnectionString"];
            services.AddTransient<ISmsService, SmsService>();
            services.AddTransient<IProfileService, CustomProfileService>();

            services.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer(connectionString); });

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();
            services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents = true;
                    options.Events.RaiseFailureEvents = true;
                    options.Events.RaiseInformationEvents = true;
                    options.Events.RaiseSuccessEvents = true;

                })

                .AddExtensionGrantValidator<PhoneNumberTokenGrantValidator>()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>()
                                .AddProfileService<CustomProfileService>();






        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseIdentityServer();
            app.UseMvc();
            app.UseMvcWithDefaultRoute();
        }

IdentityServer4配置类:

public class Config
    {
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Phone(),
                new IdentityResources.Email(),
             //   new IdentityResource("roles", new[] { "role" })


            };
        }




        public static IEnumerable<ApiResource> GetApiResources()
        {

           return new List<ApiResource>
           {
               new ApiResource("myapi", "My Api"){ UserClaims = { JwtClaimTypes.Role, JwtClaimTypes.PhoneNumber, JwtClaimTypes.Email, JwtClaimTypes.ClientId } },
                new ApiResource("roles", new[] { "role" })

           };
            /*
           return new List<ApiResource>
           {


               new ApiResource ("myapi", "My Api"),
           };*/
        }

        public static IEnumerable<Client> GetClients()
        {
            var x = "secret".Sha256();
            return new List<Client>
            {

                 new Client
                {
                    ClientId = "MyTestUser",
                    AllowedGrantTypes =  GrantTypes.ClientCredentials,
                    ClientSecrets = {new Secret("secret".Sha256()) },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.OfflineAccess,
                        "myapi",
                        "Role",
                        "role",
                        "RegularUsers",
                         "roles"
                    },
                   Claims= new List<Claim> {new Claim ("role", "role") },
                    AllowOfflineAccess = true,
                    AlwaysSendClientClaims = true,
                    AlwaysIncludeUserClaimsInIdToken = true
                }
            };
        }
    }

我的API startup.cs:


 public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddAuthorization(options => options.AddPolicy("role", policy => policy.RequireClaim("Role", "role")))
                .AddJsonFormatters();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:62537";
                    options.RequireHttpsMetadata = false;
                    //options.SupportedTokens = IdentityServer4.AccessTokenValidation.SupportedTokens.Reference;
                    options.ApiName = "myapi";
                });
        }

我的API函数类:

[Route("api/Test1")]
    public class Test1Controller : Controller
    {
        [HttpGet]
        [Authorize(Roles = "role")]
        public IActionResult GetRegular()
        {
            return Ok("Regular__"+DateTime.Now.Ticks.ToString());
        }
}
}



0 个答案:

没有答案