Custom Authorize in Asp.Net Core Web Api - api

I need help to the follow issue:
Each endpoint of my API is decorated with the "Authorize" attribute, where I indicate the claim or the necessary claims to access the endpoint. However, the same user can have a considerable amount of claims and these claims will be stored in the database. So with every request in my API, I need to intercept this request, identify the user, query the database to see if it has the required claims, and return, providing or denying access to the requested endpoint. Most of the implementations that I saw on the internet, pass the claims in the code itself, in a static way, and that does not meet me.
I tried to implement some custom filters, but I was not successful either.
Could someone help me solve this?
Thanks!

I recomended you to use JWT Authorization.
It's easy to implement and also secure.
In this article you have an example with how to do it. I hope that's help you.
https://code-maze.com/aspnetcore-webapi-best-practices/#jwt

Related

Is it better to get ID from URL or JWT in an authenticated API

So I am creating some api's on Laravel using Passport (JWT).
I am having issues deciding what is the preferred method for the following:
PUT: api/users/{user_id}
PUT: api/users/me
I need the api so that the user can change his own information, but I would also like it for the api to be accessible for the Admin to change said information.
At the moment I am only using the first API and checking if the ID is the same as the one in the JWT auth or if the one requesting the api is the Admin.
But I was also thinking that maybe it was better to have them separate. The first api should only be accessible to the Admin, and I should be taking the ID from the JWT auth for the second api.
What would be the correct choice? Or is there a better choice?
I would say using this approach is better:
PUT: api/users/{user_id}
That allows anyone to consistently link to your own profile or to some other user profile in the same way. Then depending on your authentication and authorization, you can be allowed to do different operations on that resource.
There is no correct or better choice. You seem to understand the implications of using any of them so it's really up to you to choose. With the /{user_id} version you have to be extra careful not to remove proper validation rules from your code. If you used /users/me for a GET operation you would have to be careful with setting cache headers. If a browser would cache a response to users/me and then another user would request this endpoint, then you could get some other user's data. For PUT operations, though, this is not a concern.

Handling authorization with IdentityServer4

I'm extremely confused on how to use a centralized IDP with both authentication and authorization. The architecture for my project was to be a single web API and one React client. I wanted to keep things structured out into microservices just to try something more modern, but I'm having major issues with the centralized identity, as many others have.
My goal is fairly simple. User logs in, selects a tenant from a list of tenants that they have access to, and then they are redirected to the client with roles and a "tid" or tenant id claim which is just the GUID of the selected company.
The Microsoft prescribed way to add identity in my scenario is IdentityServer, so I started with that. Everything was smooth sailing until I discovered the inner workings of the tokens. While some others have issues adding permissions, the authorization logic in my application is very simple and roles would suffice. While I would initially be fine with roles refreshing naturally via expiration, they must immediately update whenever my users select a different tenant to "log in" to. However, the problem is that I cannot refresh these claims when the user changes tenants without logging out. Essentially, I tried mixing authorization with authentication and hit a wall.
It seems like I have two options:
Obtain the authorization information from a separate provider, or even an endpoint on the identity server itself, like /user-info but for authorization information. This ends up adding a huge overhead, but the actual boilerplate for the server and for the client is minimal. This is similar to how the OSS version of PolicyServer does it, although I do not know how their paid implementation is. My main problem here is that both the client and resource (API) will need this information. How could I avoid N requests per interaction (where N is the number of resources/clients)?
Implement some sort of custom state and keep a store of users who need their JWTs refreshed. Check these and return some custom response to the caller, which then uses custom js client code to refresh the token on this response. This is a huge theory and, even if it is plausible, still introduces state and kind of invalidates the point of JWTs while requiring a large amount of custom code.
So, I apologize for the long post but this is really irking me. I do not NEED to use IdentityServer or JWTs, but I would like to at least have a React front-end. What options do I have for up-to-date tenancy selection and roles? Right when I was willing to give in and implement an authorization endpoint that returns fresh data, I realized I'd be calling it both at the API and client every request. Even with cached data, that's a lot of overhead just in pure http calls. Is there some alternative solution that would work here? Could I honestly just use a cookie with authorization information that is secure and updated only when necessary?
It becomes confusing when you want to use IdentityServer as-is for user authorization. Keep concerns seperated.
As commented by Dominick Baier:
Yes – we recommend to use IdentityServer for end-user authentication,
federation and API access control.
PolicyServer is our recommendation for user authorization.
Option 1 seems the recommended option. So if you decide to go for option 1:
The OSS version of the PolicyServer will suffice for handling the requests. But instead of using a json config file:
// this sets up the PolicyServer client library and policy provider
// - configuration is loaded from appsettings.json
services.AddPolicyServerClient(Configuration.GetSection("Policy"))
.AddAuthorizationPermissionPolicies();
get the information from an endpoint. Add caching to improve performance.
In order to allow centralized access, you can either create a seperate policy server or extend IdentityServer with user authorization endpoints. Use extension grants to access the user authorization endpoints, because you may want to distinguish between client and api.
The json configuration is local. The new endpoint will need it's own data store where it can read the user claims. In order to allow centralized information, add information about where the permissions can be used. Personally I use the scope to model the permissions, because both client and api know the scope.
Final step is to add admin UI or endpoints to maintain the user authorization.
I ended up using remote gRPC calls for the authorization. You can see more at https://github.com/Perustaja/PermissionServerDemo
I don't like to accept my own answer here but I think my solution and thoughts on it in the repository will be good for anyone thinking about possible solutions to handing stale JWT authorization information.

How to get OAuth 2.0 right for consuming external APIs in my Custom API .net core

I want to create a custom API that behind the scenes, call number of other APIs which use OAuth 2.0 for authentication. I want to manage this internally so that my custom endpoint somewhat abstract this.
Or to begin with I want to do what app like buffer (https://buffer.com) do - where you connect to different social services and than post your status.
How can I achieve this in .NetCore ?? I don't want to login with these (a lot of samples are catering this scenario), user login is different than this. I just want to establish these connections (like API Connections if you look at Azure API Management) and then perform some operations against those endpoints.
I hope i convey my point. please let me know if this isn't clear.
Thanks
Sanjay
OAuth2 systems are all based on the same workflow.
here's an authorization url, you pass some ids in an authorization header, if everything is correct you get a token, you then use the token to do whatever you are allowed to do. What changes are the credentials you use for authentication and the urls you hit for the various parts of this workflow.
You could write your own OAuth2 library which deals with all this, that's pretty much what I did and simply changed the details for every specific system I had to interact with.
This being said you can always use one of the existing implementations to connect to the various systems you care about, they all have an API you could use, all you have to do is make sure you follow the OAuth2 flow correctly.

REST API - How to make logins via an API stateless and secure?

I'm struggling with an issue here. I've searched repeatedly for answers, but have been unable to find the exact answer I'm looking for. I'm attempting to build a secure authentication method for a REST api. My question is, how do we handle a login for a REST api?
Since a REST api is meant to be stateless every time, does that mean we need to store the client's username/password on the client's end (perhaps hashed), and send it in with every request? I'd be much more comfortable using a system like authentication tokens that are created upon logging in the first time, but does that go against the basic rules of REST, since this technically creates a "state" on the server?
What is the best and most practical method to handle this? As I wrote earlier, I'm struggling to come up with an answer to this; maybe that is due to this problem not having a clear answer, but I honestly don't know.
Thanks in advance.
That's also my understanding of REST: clients send login/password to the server along with every request. The server has to authenticate the client based on this information only. With regard to the Hypermedia principle of REST, having a user logged in is not an application state, in my understanding.

How To Disable Per Request (URL Based) Claims Authorization in WCF?

I have a WCF service which uses claims based authorization.
What I want to do is to attribute an operation with a ClaimsPrincipalPermissionAttribute and only have the authorization check trigger once in my custom ClaimsAuthorizationManager. However I am finding that this authorization check is being triggered twice; once for the URL and then a second time on the operation itself.
I can't find much information on this subject, but what I have found indicates that this is by design. Is it possible for me to overwrite this behavior and not perform any authorization on the URL, and only authorization based on the operation?
I have no interest in authorizing based on URLs, and would really rather avoid adding claims for each and every URL as I am likely to have a lot of them and they may change in future.
I have read several articles, and seen videos from Dominick Baier on this subject, and while I have learnt a lot from these I still can't find an answer to this. Is this simply not possible and I just have to deal with having to authorize based on the URL as well?
You can't change this behavior - what I did is to write a custom claims permission attribute that does emit different claim types. This way I could distinguish between the per-request invocation and the explicit attribute.
https://github.com/thinktecture/Thinktecture.IdentityModel.45/tree/master/IdentityModel/Thinktecture.IdentityModel/Authorization
or the Thinktecture.IdentityModel nuget package.