Azure Mobile App refreshing tokens on server - authentication

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.

Related

Look up the user with bearer token with Openiddict 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.

Forms authentication over http in WCF - how do I know which user is calling me

I'm working on a client-server application using WCF. The first client will be a desktop app (WPF) but I plan to add Xamarin (Android and iOS) and web client. I want this to be an internet service, and to potentially support a large number of clients, so I'm using http, a stateless service to conserve server resources.
I am having difficulties implementing authentication logic.
I found this great example that implements forms authentication:
http://www.dotnetspeak.com/wcf/securing-wcf-with-forms-authentication/
It allows me to handle authentication how I want - compare username and password against the database, create an authentication cookie and return it. Subsequent calls using this cookie will be authenticated automatically.
But the problem is, I don't know which user called the service. If GetMyData() is called by user1, I want to make sure he only gets his own data. I obviously don't want to have the client send their ID separately with each request, because that can be easily tampered with - just switch "user1" for "user2" and hey presto, you're getting someone else's data.
I can get to the authentication cookie inside the service method by calling
WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Cookie]
(I can also see there's one other header called "Host")
The cookie is generated from a FormsAuthenticationTicket, which contains the username and password, but it's encrypted. I'm not sure whether it's possible for me to decrypt the cookie in my code, but I'm pretty sure it wouldn't be the correct approach. My method was called AFTER the underlying system authenticated the caller, so presumably the cookie was decrypted and the ticket was found to be valid. So why can't I get to the data?
Sadly, every article I've found only deals with authenticating the user, but nobody seems to care about which user is using the service afterwards, as long as he's authorized.
I suppose I could store the cookies server-side, along with mapping to the specific user, and find the user that way. But I want the service to be as stateless as possible for performance reasons. Also, this would involve doing fulltext matching on a 300 character long string - for every single request! Yikes!
It seems to me that what I need is a very common use case, so there must be a proper way to do it. I just can't seem to find it. Can anyone help me out?
If you have Forms authentication setup correctly then you can get the logged-in username via Thread.CurrentPrincipal.Identity.Name and send it to your service method for data access validation. Get the user id from username and validate ownership.
Thread.CurrentPrincipal.Identity.Name decrypts the cookie ticket and returns the logged-in username.

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

Thinktecture Identity Server claims

I'm using Thinktecture Identity Server V3 for authentication and having a problem getting the information from HttpContext.Current.User.
I'm using an API to handle calls but when I call HttpContext.Current.User the ID is not avilable only the claims set by Identity server.
Also when I make a call through signalR the hubs HttpContext.Current.User is null and I can't get the users ID or even look at the cliams.
I'm currently using a custom user service hooked into AspNetIdentity and overriding PostAuthenticateLocalAsync and trying to use the user manager to CreateIdentityAsync but this fails.
Is there any way to populate the default claims on login and retrieve the details on a signalr connection and Web API call?
Thanks
Did you end up solving this?
I'm still pretty new to Thinktecture Identity Server, but I'm going to take a stab at this.
There is an option IncludeAllClaimsForUser on the Scope which is set to false by default. Based on what I'm reading, this option will remove the filter when calling the GetProfileAsync() endpoint.
Here's some links on where I found this info:
http://identityserver.github.io/Documentation/docs/configuration/scopesAndClaims.html
https://github.com/IdentityServer/IdentityServer3/issues/621
No I had to park it until I had time to figure it out.
I did use the IncludeAllClaimsForUser property on the scope which would populate the claims. The issue I had was that User.Identity.GetUserId() would always return null as this is now set within the claim "sub".
This was not such a big issue but when I passed through a bearer token on a signalR connection, Current.User is always null and I can't even read the "sub" claim.
Its like the bearer token is not being validated on a signalR connection so I can't get the users details.
Thanks for the help, its much appreciated.

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.