impersonation via token stored in a cookie - asp.net

I want to know more about win32 LogonUser api function. The last parameter is a token which can be used to impersonate a windows identity to execute code on a person's behalf. Say I have a login page where I enter my username, password and domain. When the user submits the page I validate the user by making a call to LogonUser() and get a token reference.
I am thinking why not store the token in a cookie and use it at a later stage (perhaps in another page). I just don't know what issues I might have to face upfront...
Can the token expire even if we don't close it properly using the CloseHandle() win32 call? Is there any article related with this particular requirement?

Related

Single session using servicestack

I like to implement the functionality
where if two users are trying to login with the same credentials then the first user should log out as soon as the second user login.
consider user one is logged in with his credentials from one machine
and he/ another user is trying to log in from another machine
then the user one session should be removed as soon as user one logged in.
Ps:
I tried to implement that by saving the current session id in the user table and overriding the OnCreated method from the IAuthSession interface and then checking in that if the request sessionId is the same as the saved session Id if same then process the request else call the lout endpoint.
But It will be not good for performance and I am not sure if it is a good way to do that?
PS: I am using a JWT token.
Update :
I am able to clear the session by using ICacheClient to get the session and then remove a session from the server using IRequest.RemoveSession(sessionId), but is it not log out the specific user.
You can't invalidate a user authenticating with stateless authentication like JWT which has the signed authentication embedded in the Token which is valid until the JWT expiry.
i.e. you can't revoke a JWT Token after it's already been issued.
There is a JwtAuthProvider.ValidateToken filter you can use to execute custom logic to prevent a user from authenticating which you may be able to use however that would require that you manage a collection of Token info you want to prevent from authenticating before its Token expiry.

Google OAuth Always Showing Consent Screen

I'm building an installed application that will have features requiring the Google Drive REST API using Qt and C++. I understand Qt is now releasing new libraries to support OAuth flows but let's assume I'm a student and learning to use OAuth at this layer is a requirement for this project.
In my application, I have a working OAuth flow for installed applications that ends with an Access Token and Refresh Token being stored using QSettings (I'm open to input on whether this is a disastrously bad idea too). The application requires no authentication/login for its own sake/data, but it does need authentication to Google for calling API's using an Access Token. This application has no associated web backend being hosted; its simple and should be deployable completely locally (I've written and included a simple TCP server that will receive the authorization redirect_uri and will run and close when called from within the application).
As such, I'm curious about the best way to make sure that, when a user opens my application and wants to use the Google Drive features, they are appropriately authenticated on Google's end. Say, if I maintain an access token in the registry, and this access token is granted per-user/per-application basis (right?), then how can I make sure only the user the token belongs to is able to make calls to the API with it?
Here's my understanding and approach; feel free to correct me or educate me if I've got the wrong interpretation.
If an Access Token is found, perform the following:
Open a browser page to a Google login domain and have the user authenticate there (this could prohibit a user from being able to use a cached login session that would have access to a token they otherwise shouldn't have access to)
If user has correctly authenticated with a Google account, return control to the application and make a test call to an API using the stored token.
If the call fails (responds with an invalid_credentials) I should be able to be sure its because the access token has expired and the application will go through the flow to renew an Access Token from a Refresh Token.
If no Access Token is initially found:
Start a normal OAuth installed application flow
Get the tokens and store them so that when the user opens the application next time the former procedure is used
My issue then is the first two steps if the Access Token is found. Nominally this could be done by the typical OAuth flow but it appears that when using a localhost as the redirect uri, Google will always prompt for consent, regardless of settings for prompt and access_type authorization query parameters.
What can be done to accomplish these first two steps in a way that my application can control (i.e. not a solution that relies on a backend server being hosted somewhere)?
If this question is too open-ended for SO requirements I can make some more restrictions/assumptions to limit the problem domain but I'd rather not do that yet in case I unknowingly rope off a good viable solution.
Thanks for reading! Sorry if its a verbose; I wanted to ensure my problem domain was fully fleshed out!
If you are using an installed application, I wouldn't recommend using or storing refresh tokens. Storing refresh tokens on the client side means that if an intruder gains access to the client's application, they have infinite access to the user's application without ever having to enter the user's credentials. If you do insist on having a refresh token, ensure you follow the Google's installed app flow, with the code_verifier parameter included in your requests.
If the access token is found, you should try to verify it, and if verified then use it at the google api, otherwise force the user to login again (or refresh it if you chose to still use refresh tokens).
If no access token is found, your flow sounds fine.
A few notes on loggin in with Google:
Google will only return a refresh token if you specify access_type=offline in your auth request.
Google will only return a refresh token on the user's first authorization request, unless you always specify prompt=consent in your query params.
In my experience, when leaving out the prompt query param, the user is not prompted for their consent again. If they are logged in to google, you will get a new access token, but no refresh token, unless you have prompt=consent.
I think the idea is you use prompt=consent if you have no record of the user ever using your application. Otherwise if they have used it before, you may prefer to use prompt=select_account to allow the user to select which account he wants to use in case he has more then one, or you can just use prompt=none.
This is just my understanding of it all.
My approach I ended up using was just to deploy with an SQLite db that will be stored in the AppData roaming directory. The db schema includes a field for the user's Name (from the OpenID IDToken field if it exists), the user's picture URL (again from IDToken if it exists), the refresh and access token strings (will be stored as encrypted strings when I get around to it), the user's UID/sub string, and a field for a user name and password.
These latter two fields are authentication fields for within my own application, which, again, I wanted to avoid but it seems impossible to do so. So the user will be prompted to enter a username and password into a form, and these credentials will be checked against the existing SQLite db file mentioned previously.
If they exist and are correct, the user gets logged in and will have access to their respective access and refresh token.
If the user has forgotten their password, they'll be asked for reconsent (going through the installed app flow again), and whatever password they provided during initial login will be used as the reset password. It is considered, for my purposes, that logging into Google for the installed app flow is proof enough that the user account belongs to them and they should have authorization to reset the password.
If the user is a new user and doesn't have a record in the local SQLite db file, then they can also click a button to "Create New Account" - which effectively goes through the authorization flow as well but this time a whole new record is posted to the SQLite db with the appropriate fields filled.
There's still more optimization that could be done but at least I am getting closer to the level of security and control of access to Google user accounts that I want.
I'm not marking this as an answer because I feel like this solution is still not desired and that there should be an easier way. So if someone has evidence or experience of providing an equivalent level of authentication control without needing to maintain a local user account database then I would be more than happy to mark such a method as the solution!
Thanks again!

How ASP.NET form authentication works: recognising cookies from request

I am reading on form authentication in ASP.NET and cannot understand some moment:
James enters a username-password, they are saved in the db. A cookie from username is created, encrypted and attached to a response. As I understand then, when we get a request we need to recognise that cookie received are from James and so we can show his customised page.
What I would like to understand is how system will retrieve username form cookie and then load his info from db?
Forms Auth is storage agnostic. It doesn't have to use a database, indeed you can use it with usernames and passwords in web.config.
So what happens is
A user logs in.
The user is authenticated against the membership provider (which can use SQL, Active DIrectory, web.config, Oracle, MySQL, whatever)
A forms authentication token is created for the user, and is placed on the user machine via a cookie.
Each subsequent request reads the forms authentication token, and queries the provider to get the user details.
The user details are used to populate the user identity in the HttpContext and current thread for the request which is then available to your code to use.
In your code you can check the User property in the Page class (WebForms) or the User property in the controller class (MVC).
While you can get at it via the current thread, or the current context it's not advised, especially once you start using background tasks, where the identity may not propagate to the thread, or the context may change.
You'll note that nothing is stored in a database when the user logs in. It's all in the forms authentication token, and the work of retrieving the user from it's store on each request is done for you.
Afaik Forms Authentication does not store or load anything in any database. You can use a database to store the username and password, or you can put them in the web.config. How you store user credentials and validate them is up to you, and can happen separately from Forms Authentication.
Once you have validated a user (against database or some other logical storage), you use FormsAuthentication to write the authentication cookie. You do not need to worry about decrypting the cookie.
You can get the username from System.Threading.Thread.CurrentPrincipal.Identity.Name. To retrieve user's info from the database, you would query the database using the value if the principal identity name.
Response to comments
Right, you can use forms authentication with the membership provider, active directory, or your own custom user database. FormsAuth doesn't care about the password at all, unless it is stored in web.config (as noted in blowdart's more complete answer). It just writes the cookie, which is decrypted and used to create the thread identity automatically.
Additional Info
Even though this was marked as the answer, blowdart's response is much more complete. You really should not get the identity from the thread if you need it in an ASPX page or MVC controller, use the properties he referenced.
You get the username in your web form by calling User.Identity.Name, e.g. like this:
protected void Page_Load(object sender, EventArgs e)
{
string userName = User.Identity.Name;
}
ASP.NET interprets the cookie for you, you don't have to read it yourself. Or is your question how to store the user and password in the DB?

ASP.Net and Facebook: Logging-in via ASP.Net

I want to enable Facebook authentication and the FB-Graph in my website, which already has forms authentication. Using http://multitiered.wordpress.com/2010/08/05/getting-started-with-the-facebook-c-sharp-sdk/, I was able to figure out how to login server-side.
However, the problem with this approach is that a secure cookie will not be created, since the call returns the authentication code in the querystring via a callback. This means that the user will have to login every time.
I can see two ways around this:
Store the access token in a secure cookie manually
Instead of the above approach, use the FB JS API to login - this stores a secure cookie with the access token automatically
I would prefer not to use the second approach, as I would like the login code to be server-side.
Which would be the better approach? Am I missing something?
I use the JavaScript method to first authenticate the user, the JS SDK then writes an encrypted cookie (called "fbs_[YourAppID]") when a connected user hits your page; using one of the many Facebook c# SDKs, this cookie can be decoded using your application secret giving you the user ID, oAuth token, expiry date etc.
Then I hook into the AuthenticateRequest event of my .NET application, check the presence of the cookie, decode if it found, and then find a user who has been assigned this facebook ID (your user table must have a extra field for storing the ID of their facebook account).
If a match is found, I write a normal forms authentication cookie for this user, then .NET will recognise them for all future requests. If no user is found, then this is a brand new user who has just connected. Use the SDK again to query the graph API using their oAuth token, get things like their name/email etc and create a new account, then issue a authentication token as normal.
By writing a normal authetication cookie, the user will stay logged into to your site for all requests, just as if they were a normal user.
One side point, when using email address, check for duplicates, and check for the facebook cookie in all requests. For example, an existing registered logged in user may have just connected.

Facebook 'secret' value, or Authenticating an app after facebook login / registration

I have an existing Spring application which I wish to also allow users to register / sign in through facebook.
The facebook sign-in is working fine, and is currently executed from the client using the Actionscript-Facebook API ( which is essentially a wrapper for the Facebook JS API).
However I'm unsure as to what is an appropriate approach for me to take in using the client-side authenticated session to authenticate against my own app server / session (ie., the Spring session).
In my own application, the user registers/authenticates with an email address & password.
My first thoughts in a facebook authenticated solution is to use the facebook email and secret values returned from the login call. These would be stored in my database when the user performs registration via facebook, (or specifically, a hash of secret) and using these to authenticate during login in the same manner as a regular login.
However, I'm unsure of what the secret value actually is, and whether it's a appropriate to use in this scenario. (The Facebook API seems unclear in what the return values of the login call actually mean)
Is this value bound to the user, or the session?
Does this value change, should the user change their password on Facebook?
Is this an appropriate value to store a hash of?
Finally, is there a more appropriate way of achieving this task?

Resources