60

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?

Lukasz Mk
  • 5,995
  • 2
  • 22
  • 38

2 Answers2

100
services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});
blowdart
  • 52,422
  • 11
  • 102
  • 145
  • Let me ask - in your opinion - is it's good practice? I have to do WebApp for internal use, and I need be sure that is not accessible for public. – Lukasz Mk Apr 05 '16 at 00:51
  • Maybe one more question - did that (global) solution can have any negative impact for example on performance (in compare to using AuthorizeAttribute for every class)? – Lukasz Mk Apr 05 '16 at 00:54
  • 1
    So, is it good practice? Sure, although it depends on your authentication scheme itself. For internal use APIs I'd keep them internal, physically if at all possible. Note that this will accept any identity, be it from forms, or a JWT token. So, in a WebApi scenario generally you'd only want to accept JWT, issued by, say, your AD infrastructure. Performance wise it should be very much the same. – blowdart Apr 05 '16 at 01:02
  • Once again Thank you. You are the boss ;) However your answer raises more questions - I hope you do not mind... You said 'Note that this will accept any identity, be it from forms, or a JWT token'... you mean 'any, any' or only 'any valid' for my Identity Db ? As far I understand - AuthoriseAttribute (without specified policy) allow to access for any authenticated user and prevent access for everyone other ? BTW. it's for Web Application - as for now, I don't intend expose any WebApi. – Lukasz Mk Apr 05 '16 at 01:25
  • 2
    So there are multiple ways in ASP.NET Core to get an identity. There's the built in identity pieces, there is Azure Active Directory, Facebook. Twitter, there are JSON Web Tokens, heck I've even written basic authentication. These can all run in one app. So when I say "any identity", I mean any identity constructed by any identity middleware. A user must still be authenticated though. If all you're using is the ASP.NET Identity stuff you don't need to worry, but if you start to use more you may want to limit by authentication type too ... – blowdart Apr 05 '16 at 01:28
  • Thanks :) It's really helpful. – Lukasz Mk Apr 05 '16 at 01:35
  • it requires `AddAuthorization` method to be called: `services.AddMvc(config => {}).AddAuthorization();` to work for .net core 2 – oleksa Nov 07 '19 at 16:05
3

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

Rohan Shenoy
  • 607
  • 6
  • 17