How to check token for already defined policy? - asp.net-core

This is how I handle authorization with policies for controller:
At "Startup.cs", in "ConfigureServices" method I add following code:
services.AddAuthorization(options =>
{
options.AddPolicy("can_work", policy => policy
.RequireClaim("my_app", "user", "admin")
);
});
And then all it takes is to decorate given controller or specific method with attribute:
[Authorize(Policy = "can_work")]
As the effect only users with matching policy are granted the usage of controller/method.
Now, I have situation when I cannot rely on just attributes -- I have user token at hand and I have to decide whether to grant access or not. I could manually replicate the above policies rules, but it means I would repeat myself in two places. So I would like to somehow retrieve those policies I set already and check for which the token matches. How to do it?
Maybe I rephrase -- I know I can manually iterate over token claims:
foreach (var claim in token.Claims)
// manually check the value and type, and basically repeat policy again
this would be (a) repeating (b) prone to errors when something change. Instead I would like to have single call
policy_service.GetPoliciesForToken(token);
which will hit the authorization service I defined with policies (see top of the question). And currently I don't know how to write such line.
Background I describe what I need this is for, because maybe there is even simpler way -- SignalR broadcasting. When client calls SignalR method I could use attribute as well, but when the service initiates flow, say every 1 second it sends to all its clients a tick, then I would like to know to which client I can send it. So my idea would be to check user tokens when connecting to SignalR hub, retrieve matching policies (this part I don't know how to do it reusing already set policy options), and then when broadcasting anything simply filter out the clients based on cached info.
For the time being for security concerns it is sufficient for me.

Following King King tips, to some degree now I have one definition and shared check.
I changed how policies are built. I build them manually and keep their instances also for my purposes (see later):
AuthorizationPolicy work_policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireClaim("my_app", "user", "admin")
.Build();
then having policy instances I call services.AddAuthorization(options... which works as before for controllers.
As for SignalR hub I request in constructor IAuthorizationService, and when user connects thanks to attribute Authorize I have this.Context.User provided on one hand, and I have my policies instances, thus I can make such call:
AuthorizationResult auth_result = await authService.AuthorizeAsync(this.Context.User, work_policy);
to check if given user matches or not given policy.

Related

ASP.NET Core Custom Authorization

I need to implement role based authorization on a .NET 5 API but the thing is that we don't want to decorate all the controllers with attributes and a list of roles, because all that configuration will come from either a config file (JSON) or an external service (TBD), in a way that roles will be mapped to controllers and actions and we would want to have something that centralizes all this logic, in a similar way we did before with Authentication Filters and Attributes.
I've been reading that now the idea from MS is that everything is handled with policies and requirements, but I don't know how to fit all that into our desired schema. Most of all because I don't see (or can't see) how can I access the Controller and Action's descriptors to know where I'm standing when I perform the authorization process.
Is there any way to achieve this on this new model?
EDIT: I found a way to get controller and action descriptors in order to do part of what I intended. Based on some other questions and articles I read and some tinkering on my own, I got the following:
public class AuthorizationFilter : IAsyncAuthorizationFilter
{
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var descriptor = (ControllerActionDescriptor)context.ActionDescriptor; //<<-- this is the key casting :)
var ctrlName = descriptor.ControllerName;
var actionName = descriptor.ActionName;
var userPrincipal = context.HttpContext.User;
//DO STUFF AND DECIDE RESULT TYPE BASED ON USER CLAIMS AND CURRENT CONTROLLER AND ACTION
context.Result = new ForbidResult();
context.Result = new UnauthorizedResult();
return Task.CompletedTask;
}
}
Then I could add this filter the following way:
services.AddControllers(x => x.Filters.Add<AuthorizationFilter>());
This way I could achieve something similar as before with ASP.NET MVC 4/5, but from what I can read, the .NET Core team tried to go away from this path by implementing the IAuthorizationRequirement and AuthorizationHandler<T> mechanism to replace all that, so my doubt remains: is this the correct way to do it in the new .NET Core 3.x / .NET 5 architecture? Or is there some other way I'm overlooking on how to get and process the controller/action being executed and pass it along to an AuthorizationHandler?
What you are looking for is called externalized authorization also referred to as attribute-based access control. In this model:
authorization logic is decoupled from the application
authorization logic is expressed as policies that build on top of attributes
attributes are key-value pairs that describe the subject, the action, the resource, and the context of what's going on (A user wants to execute an action on an object at a given time and place)
authorization is decided based on those policies in a logical central point (logical because you could very well have multiple instances of that central point colocated with your app for performance reasons). That logical central point in abac is known as the Policy Decision Point (PDP)
authorization is enforced based on the response back from the PDP in the place where you want to enforce it. This could be at a method level or at an API level or even a UI level: you choose. The component in charge of enforcing the decision is called a Policy Enforcement Point (PEP).
There's one main standard out there called xacml and its developer-friendly notation called alfa that will let you implement attribute-based access control. It's worth noting this model and approach is applicable to any app (not .NET-specific at all).

How do I use HttpClientFactory with Impersonation? Or find another way to get a JWT token from a service based on a Windows Identity?

I have a regular ASP.Net Core web site that users access using Windows Authentication to determine which users can access which pages.
In order to render a page for the user, the site needs to call in to a series of web services to fetch various bits of data. These web services don't use Windows Authentication. Instead, they require the user's JWT Token.
So, our WebSite needs to exchange the user's Windows token for a JWT token. We have a special ExchangeToken web service that accepts a request using Windows Authentication, and returns the user's JWT Token.
The difficulty comes when I want WebSite to call this ExchangeToken web service. I need to call it using Impersonation, so that I get the user's JWT Token back. However, it doesn't appear to be possible to use HttpClient with Impersonation.
Initially, I had planned to do this in WebSite:
Repeatedly...
Impersonate the user
Instantiate an HttpClient
Call the TokenExchange service to get the JWT Token
Dispose the HttpClient
Stop impersonation
Return the token
However, according to what I've read, re-creating an HTTP client for every call is bad practice, and I should be using HttpClientFactory instead.
However, I don't see how this approach can work with Impersonation.
I tried this:
Use HttpClientFactory to create an HttpClient
Repeatedly...
Impersonate the user
Call the TokenExchange service to get the JWT Token
Stop impersonation
Return the token
However, what happens is that, despite the impersonation, all calls to the TokenExchange service are made with the same windows credentials - the credentials of the user who happens to access the web site first. AFAIK, this stems from the way that Windows Authentication works - it performs a token exchange the first time you use an HttpClient, and from then on, all calls for that client use the same token.
One option would be to create a separate client for each user... but I have about 7,000 users, so that seems a bit excessive!
Another option would be to trust the WebSite to fetch the tokens on behalf of the user, using its own account. The problem with this is that it entails trusting the WebSite. If it is compromised by an attacker, then I can't stop the attacker stealing JWT tokens for arbitrary user. Whereas, with the impersonation, the attacker still can't get a user's JWT token without first obtaining their Windows token.
So, is there a way to do impersonation + IHttpClientFactory together? Or is there a better way to approach all this?
(If it matters, my company has its own Windows servers - we're not in the cloud, yet)
To demonstrate the problem with the second approach, I made a test application. It doesn't actually use HttpClientFactory, but it does demonstrate the problem.
I started with a web site that just returns the user who made a call:
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class WhoController : ControllerBase
{
[HttpGet]
public ActionResult<string> Get()
{
return User.Identity.Name;
}
}
My client code works like this:
private void CallClient(HttpClient httpClient, string username, string password)
{
LogonUser(username, "MYDOMAIN", password, 2, 0, out IntPtr token);
var accessTokenHandle = new SafeAccessTokenHandle(token);
WindowsIdentity.RunImpersonated(
accessTokenHandle,
() =>
{
string result = httpClient.GetStringAsync("http://MyServer/api/who").Result;
Console.WriteLine(result);
});
}
And my test code invokes it like this:
public void Test()
{
var httpClient = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
CallClient(httpClient, "User1", "Password1");
CallClient(httpClient, "User2", "Password2");
}
As described above, I get the following written to the console:
User1
User1
What I want is:
User1
User2
TL;DR: NET Core is doing a lot to fight you on this approach under the hood.
Not entirely an answer on what to do, but hopefully helpful background on the HttpClientFactory approach, based on my understanding of the components.
First, from the ASP NET Core docs in regards to impersonation:
ASP.NET Core doesn't implement impersonation. Apps run with the app's
identity for all requests, using app pool or process identity. If the
app should perform an action on behalf of a user, use
WindowsIdentity.RunImpersonated in a terminal inline middleware in
Startup.Configure. Run a single action in this context and then close
the context.
RunImpersonated doesn't support asynchronous operations and shouldn't
be used for complex scenarios. For example, wrapping entire requests
or middleware chains isn't supported or recommended.
As you call out, there's a lot of progress NET Core has made around how HttpClient instances are handled to resolve socket exhaustion and the expensive operations around the underlying handlers. First, there's HttpClientFactory, which in addition to supporting creating named/typed clients with their own pipelines, also attempts to manage and reuse a pool of primary handlers. Second, there's SocketsHttpHandler, which itself manages a connection pool and replaces the previous unmanaged handler by default and is actually used under the hood when you create a new HttpClientHandler. There's a really good post about this on Steve Gordon's Blog: HttpClient Connection Pooling in NET Core. As you're injecting instances of HttpClient around from the factory, it becomes way safer to treat them as scoped and dispose of them because the handlers are no longer your problem.
Unfortunately, all that pooling and async-friendly reuse makes your particular impersonation case difficult, because you actually need the opposite: synchronous calls that clean up after themselves and don't leave the connection open with the previous credentials. Additionally, what used to be a lower-level capability, HttpWebRequest now actually sits on top of HttpClient instead of the other way around, so you can't even skip it all that well by trying to run the requests as a one off. It might be a better option to look into using OpenID Connect and IdentityServer or something to centralize that identity management and Windows auth and pass around JWT everywhere instead.
If you really need to just "make it work", you might try at least adding some protections around the handler and its connection pooling when it comes to the instance that is getting used to make these requests; event if the new clients per request are working most of the time, deliberately cleaning up after them might be safer. Full disclaimer, I have not tested the below code, so consider it conceptual at best.
(Updated Switched the static/semaphore to a regular instance since the last attempt didn't work)
using (var handler = new SocketsHttpHandler() { Credentials = CredentialCache.DefaultCredentials, PooledConnectionLifetime = TimeSpan.Zero, MaxConnectionsPerServer = 1 })
using (var client = new HttpClient(handler, true))
{
return client.GetStringAsync(uri).Result;
}

Can Policy Based Authorization be more dynamic?

Net Core policy authorization, however it is looking very static to me. Because in the Enterprise Application, there is an often need for new roles which will need new policies (as far as i understand) or if you want to implement new type of policy specific for certain client. For example if we are building an CMS which will be driven by those policies, we will want, each client to be able to define hes own. So can this new policy base mechanism be more dynamic or, it's idea is entire different?
thanks :))
I always recommend that people take a look # the least privilege repo as it has some great examples of all the various approaches one can take with the new ASP.NET Core Authentication and Authorization paradigms.
Can this new policy base mechanism be more dynamic?
Yes, in fact, it is more dynamic than the previous role-based concepts. It allows you to define policies that can be data-driven. Here is another great resource for details pertaining to this. You can specify that an API entry point for example is protected by a policy (for example), and that policy can have a handler and that handler can do anything it needs to, i.e.; examine the current User in context, compare claims to values in the database, compare roles, anything really. Consider the following:
Define an entry point with the Policy
[Authorize(Policy = "DataDrivenExample")]
public IActionResult GetFooBar()
{
// Omitted for brevity...
}
Add the authorization with the options that add the policy.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("DataDrivenExample",
policy =>
policy.Requirements.Add(new DataDrivenRequirement()));
});
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
}
Then define the handler.
public class MinimumAgeHandler : AuthorizationHandler<DataDrivenRequirement>
{
protected override void Handle(
AuthorizationContext context,
DataDrivenRequirement requirement)
{
// Do anything here, interact with DB, User, claims, Roles, etc.
// As long as you set either:
// context.Succeed(requirement);
// context.Fail();
}
}
Is the idea entirely different?
It should feel very similar to the previous concepts that you're accustomed to with auth8 and authz.
The accepted answer is still quite limiting. It doesn't allow for dynamic values at the Controller and Action level. The only place a custom value could be added is in the requirement when the policy is added. Sometimes you need more fine grain control over the authorization process. A very common scenario is permission based security. Each controller and action should be able to specify the permissions required to access them. See my answer here for a more powerful solution that lets you use custom attributes to decorate your controllers and actions with any information you need while doing authorization.

Getting a token for Web API

Once upon a time I used to install Thinktecture.IdentityModel, call it using basic auth to get a token and then pass this in the headers of ajax calls to Web API.
I just tried to do this, and it barfed.
Up periscope!
Method not found: no match for ctor signature (hurrah for Fiddler).
Comparison with a project in which it does work reveals that the required signature exists in version 2.0.0.0 of System.IdentityModel.Tokens.Jwt but is no longer present in version 4.0.20622.1351
Quick, Robin - to the Bingpole!
There's a github support query on this very topic and in the comments we find
leastprivilege commented on Jan 27
The AuthenticationHandler is not the recommended approach anymore for
Web API v2 since everything is now built-in - use middleware instead.
Unask the question, Grasshopper
This is a definitive opinion. He's one of the library's authors. It is also incredibly unhelpful to anyone who needs to ask the question.
Could someone could point me at appropriate introductory and tutorial links so I can join the ranks of those who nod sagely and marvel at the zen-like brevity of this comment?
I was using AuthenticationHandler to validate out of SQL Server table containing a username and password. Purists please don't lecture me, there are countless businesses that don't or won't use third party OAUTH. I need to convert a username/password pair into a session token that I can use on my Web API methods. That's all. I happen to agree about OAUTH but the people paying for this are not interested in grand unified authentication, they like silos.
Supplementary info
I found a publically accessible PluralSight course on the whole authentication thing. It's by the fellow who wrote the ThinkTecture.AuthenticationHandler and it's quite good as a backgrounder on recent change.
In the course of the material he refers to another PluralSight course on MVC, which has more information on OWIN (which is pure API ie an interface) and Katana (which is Microsoft's implementation of OWIN).
At this point it is clear to me that
There has been a fundamental architecture change for assorted good reasons.
A MessageHandler is not the place to do authentication.
There is a NuGet package called Thinktecture.IdentityModel.Owin.BasicAuthentication which is described as OWIN middleware for HTTP Basic Authentication in OWIN/Katana applications.
My still fuzzy understanding of the new landscape suggests that the middleware package is what I need. NuGet did its thing and now I have to provide some code to insert the middleware into the OWIN middleware chain and more code to actually validate the credentials. As near as I can tell I need to do this in Startup.Auth.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseBasicAuthentication("some_realm", (id, secret) =>
{
if (id == secret) //should check database, but never mind right now
{
var claims = new List<Claim> {
new Claim(ClaimTypes.NameIdentifier, id),
new Claim(ClaimTypes.Role, "Foo") //this can come from db also
};
return Task.FromResult<IEnumerable<Claim>>(claims);
}
return Task.FromResult<IEnumerable<Claim>>(null);
});
Assuming I've got this right so far, how do I use it? Do I continue to decorate Web API methods with [Authorize]?
Success! Nearly.
At the moment a request from my test client causes a hit on the breakpoint I've set on the line if (id == secret) and the condition is satisfied because id and secret contain the values sent by my test code. Claims objects are created as per the code above and duly returned, but the test client receives 401 Unauthorized.
This is almost certainly due to a failure to create a principal object. There's some business with a UserManager and an IdentityModel, and it may be possible to customise that to use our own schema.

MVVM on top of claims aware web services

I'm looking for some input for a challenge that I'm currently facing.
I have built a custom WIF STS which I use to identify users who want to call some WCF services that my system offers. The WCF services use a custom authorization manager that determines whether or not the caller has the required claims to invoke a given service.
Now, I'm building a WPF app. on top of those WCF services. I'm using the MVVM pattern, such that the View Model invokes the protected WCF services (which implement the Model). The challenge that I'm facing is that I do not know whether or not the current user can succesfully invoke the web service methods without actually invoking them. Basically, what I want to achieve is to enable/disable certain parts of the UI based on the ability to succesfully invoke a method.
The best solution that I have come up with thus far is to create a service, which based on the same business logic as the custom authorization policy manager will be able to determine whether or not a user can invoke a given method. Now, the method would have to passed to this service as a string, or actually two strings, ServiceAddress and Method (Action), and based on that input, the service would be able to determine if the current user has the required claims to access the method. Obviously, for this to work, this service would itself have to require a issued token from the same STS, and with the same claims, in order to do its job.
Have any of you done something similar in the past, or do you have any good ideas on how to do this?
Thanks in advance,
Klaus
This depends a bit on what claims you're requiring in your services.
If your services require the same set of claims, I would recommend making a service that does nothing but checks the claims, and call that in advance. This would let you "pre-authorize" the user, in turn enabling/disabling the appropriate portions of the UI. When it comes time to call your actual services, the user can just call them at will, and you've already checked that it's safe.
If the services all require different sets of claims, and there is no easy way to verify that they will work in advance, I would just let the user call them, and handle this via normal exception handling. This is going to make life a bit trickier, though, since you'll have to let the user try (and fail) then disable.
Otherwise, you can do something like what you suggested - put in some form of catalog you can query for a specific user. In addition to just passing a address/method, it might be nicer to allow you to just pass an address, and retrieve the entire set of allowed (or disallowed, whichever is smaller) methods. This way you could reduce the round trips just for authentication.
An approach that I have taken is a class that does the inspection of a ClaimSet to guard the methods behind the service. I use attributes to decorate the methods with type, resource and right property values. Then the inspection class has a Demand method that throws an exception if the caller's ClaimSet does not contain a Claim with those property values. So before any method code executes, the claim inspection demand is called first. If the method is still executing after the demand, then the caller is good. There is also a bool function in the inspection class to answer the same question (does the caller have the appropriate claims) without throwing an exception.
I then package the inspection class so that it is deployed with clients and, as long as the client can also get the caller's ClaimSet (which I provide via a GetClaimSet method on the service) then it has everything it needs to make the same evaluations that the domain model is doing. I then use the bool method of the claim inspection class in the CanExecute method of ICommand properties in my view models to enable/disable controls and basically keep the user from getting authorization exceptions by not letting them do things that they don't have the claims for.
As far as how the client knows what claims are required for what methods, I guess I leave that up to the client developer to just know. In general on my projects this isn't a big problem because the methods have been very classic crud. So if the method is to add an Apple, then the claim required is intuitively going to be Type = Apple, Right = Add.
Not sure if this helps your situation but it has worked pretty well on some projects I have done.