I have added a JWT middleware to my application:
app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )
No the funny thing is that it throws 500 exception (should be changed to 401 in later releases) for ALL actions, even those that are not protected at all (don't have authorize attribute). It seems to me that this is wrong but maybe I am doing something wrong myself.
Ideally what I want to achieve is that all actions are protected by default (there were filters for that in previous ASP.NET), and I will put Anonymous on those that I want public or perhaps Authorize("SomePolicy") if I want additional policies, but I want that without a token the API cannot be accessed at all. How do I do this in the new ASP.NET (I know I can inherit from some controller with this attribute, but I hope there is a better way of doing it)?
AuthenticationScheme by default, though a different name could be provided when calling AddCookie ). In some cases, the call to AddAuthentication is automatically made by other extension methods. For example, when using ASP.NET Core Identity, AddAuthentication is called internally.
Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.
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.
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.
Starting with .Net 6
we can do this (if using minimal hosting model recommended by Microsoft):
app.MapControllers().RequireAuthorization();
Starting with .Net Core 3
we can do this:
app.UseEndpoints(endpoints => { endpoints .MapControllers() .RequireAuthorization(); // This will set a default policy that says a user has to be authenticated });
It is possible to change default policy or add a new policy and use it as well.
P.S. Please note that even though the method name says "Authorization", by default it will only require that the user is Authenticated. It is possible to add more policies to extend the validation though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With