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

2

63

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?

Agleam answered 4/4, 2016 at 21:45 Comment(0)
N
108
services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});
Newcastle answered 5/4, 2016 at 0:38 Comment(7)
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.Agleam
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)?Agleam
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.Newcastle
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.Agleam
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 ...Newcastle
Thanks :) It's really helpful.Agleam
it requires AddAuthorization method to be called: services.AddMvc(config => {}).AddAuthorization(); to work for .net core 2Transpolar
D
5

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

Dewdrop answered 20/8, 2019 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.