Best way to setup Routes in ASP.NET Core 2 Web Api - asp.net

I'm looking for the best way to do my routing in my web Api.
Currently my routes are like these:
[Route("api/branch/{branchId}/products")]
[Route("api/branch/{branchId}/clients")]
In order to consume the api, I need to send a token with the authorization header. The token has the user branchId as a claim.
With my current setup I would need to give the user the branchId to the user in order to consume the api, I prefer not.
What would be the best way to implement the solution just by using the token with this route?
[Route("api/branch/products")]
I know that I would be able to extract the token values in every controller using the UserManager, but that would be to much repeating code
What would you suggest?
Thanks
Alberto Lopez

Write middleware to extract the claim value from the token and store it in the current http context.
HttpContext.Items["branchId"] = branchIdFromToken;
Then you can just use it anywhere where the request context is available by calling HttpContext.Items["branchId"].
A sample for writing middleware and extracting claims from the token (different purposes though) can be found here.

Related

Persist user security profile data at custom Claims

My application have to fetch data from external services with the usage of manually provided at profile/management by user api key & api secret.
I'd like to prevent a huge amount of retriving those necessary keys queries to database and persist it somewhere else (assuming that those keys won't be updated too frequently).
From my point of view it could be implemented with next options:
Use MemoryCache provider with SlidingExpiration;
Create a custom Claim and append it into existing Identity claims collection;
Please correct me if I'm wrong, but if I've realized it right - claim's information is a part of data, which is used for serialization/deserialization at frontend<->backend interaction (I'm not quite confident about it, but suppose that it's used within cookies & tokens).
Actually these keys are also required for a several background processes (message queue consumers or scheduled jobs for example).
Would you mind letting me know a proper way for persiting such protected and frequently used fields in an optimized way?
Thank you in advance.
When you login using one of SignInManager's sign-in methods, it sets a cookie on the browser with an access token in it. This cookie contains claims data. So in subsequent authorized requests, you can query the User.Claims field to access the required fields without making a trip to your datastore.
Now whether you choose to use claims or not totally depends on how often you need the API Key / Secret. Your claims are part of the access token. If sending the API key / Secret on every request is justified, claims is the ideal choice.
UPDATE:
Rather than decrypting the tokens at the frontend, it's better to send them to the frontend client along with the access token.
Incase you're not aware of IdentityServer4 or OpenIddict do check them out. It's probably got all that you need.

symfony web-service with username and password

I will not post any of my code, because this is more just a question to know if it's possible.
I've been googling a lot, but didn't find any concrete solutions. I hope someone can help me here.
The facts:
I have a login form
I need to authenticate the credentials over a web-service
I need to send both username and password, to get back a token if logged in successfully.
The problems:
With a custom provider I'm always stuck with the fact that they only have direct access to the userename, like: loadUserByUsername. I need to access the password there as well, to be able to send this to my web-service.
I have only 1 web-service which sends only back a token if provided username and password are correct.
Question:
How can I access and send both username and password to my web-service?
Thanks!
Generally speaking one would authenticate using an API token to a web service.
That API token is usually issued via an auto-generation script when the user account is created (either by an admin or by a registration form). This token is then passed by the API call to the web-service in a header which then uses it to authenticate the user.
As far as Symfony goes, by far the easiest way of doing this is with Guard. A new component built by Ryan Weaver from KNP.
KNPUniversity has a great tutorial on it (for free).
Note that this is only one option of many, and the 'best' way is probably mainly opinion based and directly related to the use case in question. But it might help you get on the right track.
If the token you want to create should be a JSON Web Token (JWT), a very conventient bundle is LexikJWTAuthenticationBundle, which does almost all of the work automatically. If you just follow the documentation, you will have it quickly up and running. You can combine it with FOSUserBundle, with a custom User entity or whatever.

Stop concurrent multiple client's access to the ASP.NET Web API and ASP.NET Identity 2.1

Problem statement:
Hi. I have some secured data which I want to expose through Web API and ASP.NET Identity mechanism. I want to use out of the box classes of ASP.NET Identity. I take a payment manually and change a value in the table. But there are cases where the user will share his username + password with some other guys so that the others can access the same content without paying anything.
Work plan:
So, I have extended the AspNetUsers table with a column named ApplicationToken (varchar). After successful login, I want to generate a token, update the field of the user's row in the table, and add this value as a claim information and send back to the client app. Now, when the user requests for a paid content, my client app will send the token also. So, somewhere in my server side codes, I need to check this ApplicationToken with the Database token value. If both are equal, I allow the request to proceed, otherwise I will send 401 Unauthorized and tell them to login again.
Implementation options:
After studying and searching, I found the below options to implement:
Create Custom Authentication Filter attribute so that I can grab the claims send from the client and do my required validation
Create a base class of the secured API and get the claims there and do my required validation.
Go for different Jwt based implementation where I should have access in both issuing and checking the Json Web Tokens.
If you have any other options, I would be very glad to hear those.
My question is, which approach is better to proceed. I have enough time to implement, so time is not a factor here. Thanks.

Symfony2 and FOSRestBundle - Only Allow Users to Edit Data That They Own

Symphony Version 2.2 (yah, I know).
FOSRestBundle: 1.5.3
Current Scenario
I have a REST Api driving an angular page. Let's say that each user has a token associated w/ their user record. Consider the following Urls.
GET /api/user/{token}/messages
POST /api/user/{token}/messages
GET /api/messages/{messageId}
GET /api/user/{token}/votes
POST /api/user/{token}/votes
So the user can GET and POST messages. The user can make votes and see them.
(I have about 30 diff routes like this - the URLs are all over the place).
Question
How can I verify that the user is allowed to GET/POST data for the token they're providing?
I do realize I could copy/paste some code to check the given user vs the user from the URL. Or I could write a service w/ a checkUser() function on each endpoint.
My hope, though, is that there is some way of doing this that doesn't require me to check the user on each endpoint's entry point.
Don't send the authentication in the Endpoint. An endpoint typically should be Idempotent, and should individually identify a particular resource.
Send your authentication tokens in HTTP headers.
With that said, as a strategy, baking in your security using #wonde is a good idea. I have implemented a custom base controller class in the past, but the filter and event handling built into symphony provides an even sexier solution.
i would create a before filter and add the checkUser() hook in there , that way you don't have to check the user permission on each endpoint
example

Access token implementaion in ASP.NET

How to use access-token concept that is used in facebook.
1)Can we implement same concept in ASP.NET based web application?
2)Can we use this concept in adding security to access in webservice ASMX and WCF ?
After long time I have found the answer I have posted.
If I am wrong please review my answer.
1) In Facebook server flow authentication when user is successfully authenticated Facebook generates authorization code parameter name as code.
2)In second step using all this parameter authorization code with client _ secret ,client _ id , redirect _ uri , state call Webrequest or call service if success then response have two parameter accessToken ,expires _ in.
3) This accessToken is used for getting userinfo like firstname,lastname,birthday etc with specified scope.
And this is general scenario that is used with WCF and ASMX webservice by storing valid accessToken to safe place or further use.
1) Access token is just a hash from some parameters, e.g.:
MD5(userName, userMail, someSalt, someOtherStuff)
So you can implement it for sure the way you like it. But better if it contains some secret information that can be retrived only by current user
2) Yes you can. As social networks like facebook do it:
there's some application secret key that is known on a server side (where your service runs), and some signature that can be retrieved from facebook api for some app and user and some other information.
Your facebook app gets that signature, it can use it to make hashsum with other parameters like userLogin, application scores or w/e else. Sends it to server.
On a server side you generate signature same way as your appliaction do based on parameters. If signatures are same request is valid. If know - someone is trying to do dirty things :)

Resources