MVC Core How to force / set global authorization for all actions?

爷,独闯天下 提交于 2019-11-26 09:44:26

问题


How to force / set global authorization for all actions in MVC Core ?

I know how to register global filters - for example I have:

Setup.cs

services.AddMvc(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});

and this works fine, but I can\'t add the same for Authorize:

options.Filters.Add(new AuthorizeAttribute());

I have error:

Cannot convert from \'Microsoft.AspNet.Authorization.AuthorizeAttribute()\' to \'System.Type\'

(Method .Add() needs IFilterMetadata type)


I know - from similar questions - that this works on MVC4-5... So something must changed on MVC Core...

Someone have any idea?


回答1:


services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});



回答2:


Add the following to your ConfigureServices in StartUp.cs. This is for token validation and force all calls to verify with token.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })`

Add this to Configure method in StartUp.cs.

app.UseAuthentication();

Note: Use [AllowAnonymous] for those where you don't need it



来源:https://stackoverflow.com/questions/36413476/mvc-core-how-to-force-set-global-authorization-for-all-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!