Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 236
Lukasz Mk Avatar asked Apr 04 '16 21:04

Lukasz Mk


People also ask

How do I override an authorized attribute in .NET Core?

Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.

How do I register a global filter in .NET Core?

In . Net Core, we can add the filters globally by adding it to the MvcOptions. Filters collection in the ConfigureServices method in the Startup class.

Which attribute will ensure that all users can access a specific controller action?

One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.

What is IAuthorizationRequirement?

IAuthorizationRequirement is a marker service with no methods, and the mechanism for tracking whether authorization is successful. Each IAuthorizationHandler is responsible for checking if requirements are met: C# Copy.


1 Answers

services.AddMvc(config => {     var policy = new AuthorizationPolicyBuilder()                      .RequireAuthenticatedUser()                      .Build();     config.Filters.Add(new AuthorizeFilter(policy)); }); 
like image 50
blowdart Avatar answered Sep 30 '22 01:09

blowdart