ASP.net Core 6.0 Basic Authentication different users - asp.net-core

I've implemented the basic authentication (Attribute, Handler) from here:
https://www.roundthecode.com/dotnet/how-to-add-basic-authentication-to-asp-net-core-application
Now I want to authorize different users, using the attribute like this:
[BasicAuthorization("login1")] and [BasicAuthorization("login2")] or
[BasicAuthorization("username", "password")]
"login1" should only be able to access Actions decorated with the according attribute and parameters.
How is that possible?
How to adapt the AuthenticationHandler?

Related

AuthorizeAttribute: How to try with all available Authentication Schemas?

I have a ASP.NET Core 3.1 Web Application which have ASP.NET Identity authentication and Role based authorization for interactive users (Pages)
Now I implemented some API Controller too within the same ASP.NET Core 3.1 application
[ApiController]
public class ConnectController : ControllerBase {...
I realized, that bearer token endpoint is not out of the box, so I successfully implemented it using OpenIddict, and it is working perfectly.
I would like to use Authorize attribute with Roles.
This is working:
[HttpGet]
[Authorize(Roles = "test01",
AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]
//[Authorize(Roles = "test01")] // This is not working, why?
public ActionResult<string> Ping01(string message)
{ ...
The pure [Authorize(Roles = "test01")] is not working, and I do not understand why?
For diagnostic purpose I examined all available Authentication Schemas, there are six, and the explicitly named "OpenIdDict.Validation.AspNetCore" is in the six (the last one, see debugger screenshot below). With other words I would like remain free change API Authentication methods and implementation in the future without touching the Controllers.
Question
How can I achieve that not specifying explicitly the Authentication Schemas in the AuthorizeAttribute constructor the authorization will try to Authorize with all available Authentication schemas?
Why I would like to do that?
...because I would not like to be specific to any Authentication Schema in my controllers. I would like to have a simple Role based authorization, and would not like the controller authorization code depend on anything else than the Role names.
How can I achieve that not specifying explicitly the Authentication
Schemas in the AuthorizeAttribute constructor the authorization will
try to Authorize with all available Authentication schemas?
If you don't want to specify the schemas explicitly, you have to create a Default Policy in the ConfigureServices method, like this:
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)
.Build();
});
So now when you use [Authorize] the default policy will be included automatically.
By using this attribute now, you will have the user authorized by the role:
[Authorize, Authorize(Roles="admin")]
You may ask, why should Authorize attribute be used twice?
The answer to this can be found here: https://github.com/dotnet/aspnetcore/issues/18954

Blazor server side role or claim based authorization when using windows login

I am new to working with Blazor and Authorization. Background is desktop apps in Vb.Net, so I have been reading everything I can on it, but it still is very confusing when I only want a specific subset of the options out there.
I have a very simple intranet Razor Server based app that is getting the windows user name correctly with default authentication. (I use the name in calls to stored procedures for logging, so I know that is working correctly.)
What I need is to implement authorization (role based would be fine) based on information I have already in the database tied to the user name).
Where and how does one add roles to an existing authstatetask or other object instantiated by the default processes?
Everything I have seen deals with the EF version of Identity or wants to override the authorization task.
I have Simple DB calls being made in Dapper which will return an identifier from which I can set roles.
I just need pointers to the proper method and where in the app I should put it. I have just a single .razor page being loaded, Navbar is disabled.
You can either :
Implement Identity stores for Dapper following instruction in this blog : ASP.NET CORE IDENTITY WITHOUT ENTITY FRAMEWORK
Use Policy-based authorization and create authorization handlers meeting your requirements

How can I make a custom authentication or authorize attribute in asp.netcore 2.0

So I want to make an authentication attribute that I can put on my methods. Example
[Attribute]
public void getUsers()
{
}
I want the attribute to have some logic in it, so I can verify the information coming in, to see if the user is allowed to access that method.
I have done a lot of searching and a lot of them use .Net or mvc and I want .netcore. Any help is welcome

How to restrict controller/view access based on domain ad group

I want to restrict certain parts of my web app to certain user groups located in AD groups inside our domain.
I am using .Net Core 1.1. I have also tried decorating my controller with the [Authorize] attribute but with little success.
Does .Net Core currently have a way to do this?
Make sure you pass windows authentication token with in your Services:
services.Configure<IISOptions>(options =>
{
options.ForwardWindowsAuthentication = true;
});
And then use the [Authorize] attribute as follows
[Authorize(Roles = "AD Role")]

Different Authentication Schemes for the Same ASP.NET Web API

The Situation
I have an upcoming project where the web pages will be making AJAX calls. External clients will also be provided a REST API. I will be implementing this project using ASP.NET MVC 4 with Web API.
I have seen various examples online where people use the [Authorize] attribute for security. I presume this is whenever Web API is called via AJAX on a web page.
I have also seen various examples where an API key was passed along with each request (via query string or header). I presume this is whenever Web API is called from an external system.
The Questions
Here are the questions that immediately come to mind:
Should I be creating a separate controller for internal and external clients?
or should I force the web pages to use the same external authentication model?
or is there a way that external clients can use the Authorize attribute?
or should I somehow support both forms or authentication at the same time?
A Side Note
A colleague pointed out that I might want to deploy the API to a totally different URL than where the web app is hosted. Along the same lines, he pointed out that the external API may need to be more coarse grain or evolve separately.
I don't want to reinvent the wheel, here. This makes me wonder whether I should be using Web API as an internal API for my AJAX calls in the first place or if I should stick to old-school MVC actions with [HttpPost] attributes.
[Authorize] attribute is not meant only for Ajax. When you apply the [Authorize] attribute to say an action method, what this does is it ensures the identity is authenticated before the action method runs,irrespective of the clients making the request and irrespective of the type of credentials submitted to your API. All it looks for is Thread.CurrentPrincipal. Here is the copy-paste of the code from the Authorize filter.
protected virtual bool IsAuthorized(HttpActionContext actionContext)
{
...
IPrincipal user = Thread.CurrentPrincipal;
if (user == null || !user.Identity.IsAuthenticated)
{
return false;
}
...
}
As you can see, all it does it gets the Thread.CurrentPrincipal and checks if the identity is authenticated. Of course, when you include the roles, there are additional checks.
So, what this means is that you will be able to use different means of authentication as long as Thread.CurrentPrincipal is set as a result of authentication. If you have two handlers (or HttpModules in case of web hosting) or authentication filters in case of Web API 2, you can establish the identity based on different factors. For example, you can have a BasicAuthnHandler and a ApiKeyHandler added to config.Handlers and hence run in the web API pipeline one after the other. What they can do is to look for the credentials and set Thread.CurrentPrincipal. If Authorize header comes in the basic scheme, BasicAuthnHandler will authenticate and set Thread.CurrentPrincipal and if the API key comes in, it does nothing and ApiKeyHandler sets Thread.CurrentPrincipal. Both handlers can create same type of prinicipal say GenericPrinicpal or even different one. It does not matter because all the principals must implement IPrincipal. So, by the time Authorize filter runs, Thread.CurrentPrincipal will be set and authorization will work regardless of how you authenticate. Note: If you web host, you will also need to set HttpContext.User as well, in addition to Thread.CurrentPrincipal.