Look up the user with bearer token with Openiddict Core - asp.net-core

I am currently using Openiddict, Identity and Entity Framework to manage my users and assign Bearer tokens to users to protect my API.
My infrastructure is currently using ASP.NET Core Web API in the back end and a separate React application in the front end. The React application makes HTTP calls to my API to retrieve it's data. There is no server side HTML rendering at all in the back end.
Everything works as I need it to for the most part. I can register users and retrieve tokens from the API. These tokens are included in my HTTP call in the Authorization header. My AuthorizationController uses this: https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/AuthorizationController.cs with a few minor tweaks. My Startup.cs also uses almost exactly this https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Startup.cs
In some instances, I need to make API calls to the endpoints that are specific to the user. For instance, if I need to know if a user has voted on a comment or not. Instead of passing along the users ID in a query string to get the user details, I would like to use the Bearer token I received that they use to make the API call for that endpoint. I am not sure how to do this though.
In some research I have done it looks like some samples use ASP.NET Core MVC as opposed to the API to retrieve the user with the User variable as seen here https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/ResourceController.cs#L20-L31 however this seems not to apply to my infrastructure.
My question is how do I look up a user based on the Bearer token passed to the API to look up a users details from my database? I am assuming that all of the tokens passed out by the API are assigned to that specific user, right? If that's the case it should be easy to look them up based on the Bearer token.

The question is: How with Openiddict can you look up a user based on the token that was assigned to them for API calls? I need to get the user details before anything else can be done with the application first. Is there something baked internally or do I have to write my own support for this?
When you create an AuthenticationTicket in your authorization controller (which is later used by OpenIddict to generate an access token), you have to add a sub claim that corresponds to the subject/entity represented by the access token.
Assuming you use the user identifier as the sub claim, you can easily extract it from your API endpoints using User.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value and use it to make your DB lookup.

Related

How to authenticate an app instead of an user with django rest framework?

By default, TokenAuthentication creates one token for each user (User access tokens), what makes sense for an API accessed only by end users.
But to integrate with other applications, would be more suitable to authenticate the application itself (App access tokens), instead of to make the application access the API on behalf of a given user.
My question is how to achieve that with Django rest framework. Should I extend the tokens model to add a FK to the applications table or there is an "easy" way? Any tips?
If i understand your problem problem properly Instead of per user a token you would like to have per device ( app ) an authentication token. There are some well used third party app's like django-rest-knox or jwt provide that. No need to do this manually.
Though i prefer django-rest-knox as it has delete all token facility. Which is very useful in case of lost or compromise device.

Azure Mobile App refreshing tokens on server

Here's the background:
Need to authenticate with google/facebook/msa
Need to add our own claims to MobileServiceAuthenticationToken for use on client
Want to have refresh token capabilities (I know FB doesn't have that)
I have this working by LoginAsync and getting a MobileServiceAuthenticationToken back. Then I call a custom auth controller which has an [Authorize] attribute on it.
The custom auth controller copies some claims from the principal then adds our claims to those and creates a new token which it returns to the client.
Using the LoginAsync for all of this keeps the tokens flowing for all calls and that's great.
So, the token expires and I call RefreshUserAsync on the client. At this point the MobileServiceAuthenticationToken with our custom claims is replaced by the default one from the MobileAppService without our claims. I expect that.
So now I have to call the custom auth controller again to get our claims added back to the identity token.
This works, but it feels clumsy. And it's two round trips.
What I'm looking for is to refresh the identity provider access token on the server side, and in the same method, update the identity token with our stuff.
I'm aware of the /.auth/refresh call from the client side as an alternative to RefreshUserAsync. Is there a similar call I can make from my controller in the backend without setting up the whole System.Net.Http.HttpClient thing?
For example: I use this.User.GetAppServiceIdentityAsync<GoogleCredentials>( this.Request ) in the backend to get identity provider information without making HTTP calls.
Something like that?
Thanks in advance.
Short version - no.
Longer version - you need to call the /.auth/refresh on the backend on behalf of the user, then add your claims. The /.auth endpoints are on a different service that your backend does not have access to except via Http.
The GetAppServiceIdentityAsync() method still does a HttpClient call, so you aren't saving yourself a round trip.

Laravel 5.2 - How to implement register with api token without session?

I'm looking for a way to create a api token after registration without session
And I also have a question:
Regular site have session to identify the current user
But in api How can I identify the current user if we do not create for him a session?
I'm having trouble with these questions
The main concept is that in login request you send e-mail and password and you get the token.
In all next request you send always this token (so you know which user makes the request) and for this you also send other data (if they are necessary).
Of course you need to make sure this token is somehow unique so you can now exactly which user is making the request.
You can implement it on your own or you can take advantage on some ready components.
In fact in Laravel 5.2 you have TokenGuard built in so you can create simple token authentication out of the box. You can watch this movie on Laracasts for further details.
You can also use some other packages for example JWT Auth

ASP .NET WebAPI default OWIN authentication - help clear things up

I have some general/how-does-it-work-inside questions about WebAPI and OWIN (specifically, the default configuration which is set up when you create new WebAPI project in VS2013 and select Individual user account authentication). I did that, then I registered (using jQuery post) and even logged in (received token which I included in Authorization header, receiving access to protected resource. I just have some more questions about it:
Are my data stored inside authentication token? I know my password isn't, but is token containing encrypted data, or is just a random string? These are the only 2 options that I can think of: either token contains encrypted data (userId, expiration date, etc.) and server app deciphers it and grants me access to resources, or token is a random string and all user data are stored on server (token is used as a key to obtain correct user data entry). If the second theory is right, the token <-> userData lookup must be stored somewhere - is it session, cache or database maybe?
If i wanted to make a RESTful API, what about Roles, etc. (in general - data beyond simple who-are-you identification that I need for every request)? Again: first thing that comes to mind is to store them inside token. But if the data grows large isn't that too much overhead to send with each request (plus headers themselves probably are limited in size)? Second thing is using external OAuth service (like Facebook or Twitter) - if the user authenticates using external token, I can't control what information does it contain. Alternative is to get the data I need from the database each time, but isn't it bad practice? Every single request would need an extra database call to collect user's role and check if he even has access to this particular part of application. I could store it in session, but RESTful API is supposed to be stateless.
Thanks for any help as I'm just starting to dig into OAuth and WebAPI authentication. I know that I can customize everything to work as I want (so use session to store user data, etc.), but I wanted to know what the good practices are and which of them are provided out of the box with default WebAPI project in VS2013 and which need to be implemented manually.
(1) the latter is correct. The server verify token by machine key and can decipher and validate its contents.
(2) You got that correct. Its best to keep the token size min. tbh I am looking to see what others are doing about this. (+1 for the question.)

RESTful API for authroization, plan features control

I am working on a web app. Front-end only interacts with back-end through RESTful API(it's called SOA architecture), and back-end only sends data to front-end in JSON.
My question is:
1) is it the best practice to design the authorization through RESTful API? or it is best to check authorization (user-> role -> privilege) at back-end code?
e.g.: do we ask user /checkPrivilege/{...} every time before executing other API?
2) How it is usually to implement 3 plans with different features & UI in RESTful API?
e.g.: do we use api to limits 5 users for this plan? or we do it at back-end code?
This is an old question, but I'll answer this anyway just in case some looks it up.
The short answer is you do it through the backend. The URI you are requesting should not contain any information about the user. Any session/identifying data should be sent in HTTP Headers.
Your RESTful API is always going to be loaded through a front controller like index.php. This is where you will want to bootstrap an authorization tool to check every single page request for credentials before executing the rest of your code.
Those credentials, at a MINIMUM, should contain a unique authorization token for the user who is making the request, and this token needs to be sent in every request (again, I recommend via an HTTP header). Bonus points if you grant a temporary access token that will expire, so as to prevent unauthorized access at a later date.
But for simplicity, let's say you are just using a permanent unique token per user. You would then store this token along with all the other data about the user, that other data should include an account_id for the account that user is a part of.
So for each request you would:
grab the user token from the HTTP Header
Look up the user based on that token.
If the user is found, then use their account_id to look up the master account their personal account is associated with
If it matches, grant them access
But remember, your URL should never contain this information in anyway. RESTful URLs are stateless.