After getting the access token with hybrid or authorization code flow to keep them from the browser it seems stupid to use SaveTokens = true in the (ASP.NET Core) OpenIdConnect middleware so that they end up in the browser again.
What is a better way to store the access token using the middleware?
Using SaveTokens the middleware stores the tokens in the cookie along with a users claims. Whilst this cookie might be stored in a browser it's protected so only that application can read it. The browser or client side code cannot read the cookie. So they're not really ending up in the browser (like they would using the implicit grant type).
Otherwise what you would need to do is create a token store, looking up tokens either by authenticated user or by session.
ASP.NET Core Identity has a table for storing tokens for a user you could look into using, but then this would mean all of your applications have to integrate with the ASP.NET Identity library and a token could be accessed by any app.
There are a couple of key differences compared to the implicit flow which makes this significantly more secure:
They end up in the browser as Secure and HttpOnly cookies, which means they are:
Only sent over encrypted requests over HTTPS.
They are inaccessible to JavaScript.
The cookies are encrypted as well, and can only be read by the ASP.NET Core server app. So even if an attacker does somehow obtain them, to decrypt them they'd need access to the server, or the encryption key used by ASP.NET Core's Data Protection provider.
Related
We are developing an application that uses a React front end website hosted on AWS using Amplify. This communicates with a .NET Core 3.1 Web API running on EC2 / Elastic Beanstalk. Cognito is used for user authentication with the Web API configured to use JWT tokens.
It works OK, but we have noticed that the Cognito provider stores the JWT access token in the browser local storage. This is what we see using F12 in Chrome and inspecting local storage.
From what we have read, storing access tokens in local storage is not advised as it makes the application susceptible to XSS attacks. Strange then, that the Cognito identity provider chooses to store sensitive information here.
If this approach is not considered safe, can the provider be configured to store this information elsewhere, such as cookies?
Alternatively, as we control both front and back ends, is there an alternative method that can be used to secure the API that does not involve tokens? Obviously the API needs to know which user is logged on to the web application in order to perform authorization checks. [Note authorization in the application is record level and defined in database tables, so it goes beyond simple user profile attributes.]
Many thanks in advance for your advice.
Doug
Security is a spectrum not a feature so it really depends on your appetite for risk vs effort. Amplify is not a particularly nice codebase, it has 500+ issues and if you look at the code you might be fairly shocked at the quality of it.
If you are using Hosted-UI then you can write code to manage the tokens yourself rather than using amplify, although you will need to learn a bit about OAuth grants and OIDC.
Be aware that the Hosted UI lacks a huge amount of features, so if you are going to use it make sure you are happy with it. Off the top of my head
no silent refresh capability in the hosted UI, so no safe way to store the refresh token.
no support for custom auth flow in the hosted UI
no passwordless support in the hosted UI
no ability to pre-populate a field in the hosted UI (e.g. username)
no ability to customise the plethora of obscure error messages in the custom UI
fixed now, but for years the email addresses were case sensitive!
An alternative is also to just use the AWS SDK to get tokens directly using cognito-idp but this also has a bunch of issues:
no code/PKCE/nonce capability so insecure in a mobile authsession
no ability to set oauth scopes, so can't use them
consequently not possible to use for OIDC
the SRP implementation is bananas and so far off spec
if you make device registration mandatory, it will deliver a working access tokens before the device is registered! (allows invisible devices for malicious logins)
We were using auth0 which was leagues ahead but we had to move to Cognito because of SMS OTP cost (min $25k per year at auth0).
I have been using AWS for over a decade now, Cognito is by far the worst service I have used, and I have used a lot! If you can avoid it, do so.
To answer the original question, yeah it's insecure. The best you can probably do is keep them in memory. If you wanted to you could probably put the hosted UI behind a cloudfront and use an lambda#edge to transform the token into a cookie instead. This has now opened you up to CSRF attacks though.
answering the original question: no, it is not safe at all.
Storing refreshtoken in any local storage accessable to any local app/script is not secure. So, the best way would be to store the refreshoten (and also the access token) in an httponly cookie or even better to store a one-time session token in httponly secure cookie could be used to get new access and refresh cookies - similarly as it is made by cognito hosted ui with XSRF-TOKEN.
See below how I would solve (and plan to solve) this issue:
Some background:
Due to GDPR regulations I think I can not use the cognito hosted ui - I have to make sure users read and accept the general terms and conditions (giving clear and auditable consent) and can review and accept cookie policies as well before they type in any user data for sign up. Nevertheless the built in hosted ui design is quite outdated and unflexible. I have an SPA website where I want to manage users, secure endpoints, etc.
So I have the following idea which is still not super secure but I think it is more secure one if you want to use js and ampify sdk and which also might answer your question:
I'll use amplify javascript sdk to let users sign up, change psw and log in (get tokenid, access token and refresh token), will make my own "hosted ui". I'll store the access token in memory only (not in local cookies and not in localstorage for sure). Access token will be used in header (bearer) to access apiGW endpoints. Access tokens will have very short expire dates. (I'd also use httponly secure cookies sent back by the apigw, as well as in the body.., then compare at BE side..)
And here comes the trick: I'd cut the refresh token into two. (Don't forget it is just a string.) I'd store the first part of the string in a local cookie (javascript can read it, if browser is closed and opened again it will be still there) and will send the other half of the refresh token to an apiGW endpoint (accessable without authentication) which will store it in a dynamoDB table (with TTL) and will send back an httponly secure cookie to the browser with a randomly generated "storagetoken" in it (which will be a key in dynamodb). There will be another unauthenticated apigw endpoint which will be called by the client whenever the client needs the full refresh token. Calling this endpoint the browser will send in the httponly secure cookie as well (same domain), so the backend will get it. As it is issued by the BE and available only in the given browser it can not be stolen so the backend will send back the stored half refreshtoken. The other half part of refreshtoken is stored in a simple cookie in the browser.
If the browser is closed and opened again client checks if there is any valid accesstoken and if not it checks if there is a half refeshtoken stored as cookie. Then ask the other part of refreshtoken assuming there is a httponlycookie also stored and it will get back the other part of the refreshtoken from the BE. In case of success the client tries to use the full refreshtoken to renew/get access token from cognito, in case of failure it will pop up the login screen.
Whenever refreshtoken is not in use it is deleted from the memory.
I know this is still not supersecure but might be a better solution than storing refresh token in localstorage.
Alternatively, as we control both front and back ends, is there an alternative method that can be used to secure the API that does not involve tokens?
I don't know anything of Amplify but in AWS Cognito what you describe is the Implicit grant OAuth flow. In AWS Cognito it is possible to use Authorization code grant where you instead of the token get a code which you in the backend can exchange for a user pool token.
https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-configuring-app-integration.html
The question still remains where do we have to store the JWT tokens so that our AJAX requests from Javascript can use them in the Authorization headers.
I looked at the following resources. Some suggest to use SessionStorage or LocalStorage and some say that they are unsafe, but don't recommend an alternative either. Also, some (link 3) suggest to store it as httpOnly cookies which obviosuly is not a solution for Single Page Applications. So, if we store them as non httpOnly cookies, its almost same as localStorage.
How do I store JWT and send them with every request using react
Please Stop Using Local Storage (https://dev.to/rdegges/please-stop-using-local-storage-1i04)
https://blog.logrocket.com/jwt-authentication-best-practices/
I know probably there isn't a particular solution to this problem, but strategies used in production settings to work around this problem may help.
As security is your primary concern, then the answer is relatively simple: you can't supply a JWT as an authorization header to your server-side application. To do so would require the use of a Javascript-accessible object, meaning that the JWT is at risk of an XSS attack.
The only secure method available at present is to generate that token via your server application, then supply that token to your client-side SPA via a httpOnly, Secure cookie. Arguably, this cookie is now potentially vulnerable to CSRF, but this may be considered a lesser risk than XSS.
With each subsequent AJAX request, that cookie will then be automatically supplied by the browser. Your server application (or application server) must also be configured to accept the JWT via that specific cookie.
This technique works for any application - Single Page Application or otherwise - that is looking to protect requests to server-side resources.
I'm creating my first SPA using NodeJS stack for development and I came to a point where I should design authentication and secure some parts of the app.
I read a lot about auth techniques including JWT, OAuth, etc. but I still didn't find something like «a real world example».
Let's assume that my task is just to secure some parts of app from public. My app isn't designed to work with 3rd party services so I see no need to use something like Google or Facebook auth. I want to use login/password and store all this data using my own database server.
I don't understand the point of having authentication stateless. I came to a simple conclusion that I can design authentication in this way:
I store users logins and passwords in my database.
User auth means that user enters his credentials, server checks it and creates token. Then server saves this token into database. User saves token using browser local storage or somewhere else if it's not browser environment.
On each request client sends this token, server checks that this token exists and responds appropriately.
User can login from different devices, we just create multiple tokens for him.
We can end specific session or all sessions by just deleting user tokens from database.
We can manage tokens in a way we want, for example server can check expiration time and invalidate (delete) token.
Is it OK? JWT require additional implementation if we need to invalidate token, I saw different examples, all of them were based on storing invalid tokens but what's the point of that if we can just store valid tokens? We already lose statelessness by implementing this storage.
I see that I can just use cookies instead of implementation described above but I don't like an idea to use cookies in RESTful app because it really depends on browser-like client environment.
What are the disadvantages of just storing tokens on server?
I have implemented one project in which user authentication is required and token is stored into database.
You can find that example here.
You are describing the traditional authentication approach using session cookies. The server stores a session for each connected user identified by a sessionid. The sessionid is stored by client in a cookie and sent in each following request to identify user.
You can use this method perfectly, both in browsers or mobile devices (using the device storage instead of a cookie)
The drawback is that it requires many server resources to keep sessions open and requires database queries at each authentication to retrieve user data. This is what JWT solves. The user information goes in the token itself, and is reliable because it is signed with the secret key of the server.
JWT has its own drawbacks, for example it is not useful if you need to have a revocation list, because them will require server storage.
Okay so this might be a very rookie-ish or naive question but I tried searching the internet and have resorted to stack overflow only after not finding anything fruitful. I have been reading about Token based authentication as well as Cookie based authentication. I have come across the opinion that token based authentication is better for Single page web applications but cannot clearly understand why. I will be using nodejs and angularjs to accomplish the same.
I guess that with Token based authentication as well as Cookie based authentication you mean Token authentication vs Session authentication because a token can be stored in a cookie
See this
With session based authentication the server maintains a sessions per each connected user. Client authenticates with its credentials and receives a session_id (which can be stored in a cookie) and attaches this to every subsequent outgoing request. So this could be considered a "token" as it is the equivalent of a set of credentials. This approach requires heavy server resources
Token based authentication is stateless and does not require server storage because the issued token (mainly JWT is used) contains the relevant user info and is signed with the server private key, so it is non-falsifiable. The token is stored in client side (cookie, localStorage, etc), attached to every request and validated by the server. Tokens are also suitable for REST APIs that do not require to maintain the state between each request
Forms based applications use session based authentication, and SPA often use token based authentication by the inherent advantages.
Note also that a SPA with session based authentication only will attach cookies to the outgoing request if the applicacion is located in the same domain that the server
SPAs tend to have many faces: the logged in view, the logged out view, or the restricted view. It’s all about access control. Your users are all getting the same app but they may not have the same levels of access. You’ll find yourself building access control logic for your front end and your back end.
Because tokens contain all this information, they are very portable: they can be used by your UI and your backend to make decisions. You can share them with partner services as a means of building Single Sign On services that delegate users to the correct application.
Hope this link will give you more information..
Token Based Authentication for Single Page Apps (SPAs)
For now I have Asp.Net WebAPI and client application (Angular) on separate hosts. As for authentication, WebAPI uses default external OAuth provider (Google) implementation with middlewares, external bearer token and cookie. Since web application is being hosted separately, for security reasons it is using Implicit grant flow, so access_token is being returned after hash symbol in URI. Also, it means that refresh token can not be implemented.
Here comes the part I am a bit confused about.
As for my WebAPI I am using Local accounts, which have to be created for every new user that comes to my application externaly (from Google) using basic information it provides. So the external bearer token and cookie are only used till I register the user, sign him in and provide LOCAL AUTHORITY bearer token which can be used to access secured API endpoints. It means I still have the LOCAL AUTHORITY provider which lives in my WebAPI and manages access_tokens.
Does it mean that I can implement refresh token?
If I understand correctly refresh token is not valid between Google and my app (because it is using implicit grant flow), but it is viable between my WebAPI and Client application without leaving security holes?
I am a bit confused about the refresh token here. Is it possible?
Thanks for your time.
Kind of Solution
Read this answer for the solution