How to silently refresh expired JWT token with OAuth2? - authentication

We have decided to switch from Hazelcast shared session to Stateless JWT authentication/authorization with OAuth2 and found out a problem that doesnt fit our infrastructure described below.
So we have multiple Self-contained systems (scs) that may be accessed by direct link i.e. mysite.com/scs1 and mysite.com/scs2.
Each scs has it's own UI and BackEnd, but "session" (implemented via Stateless JWT Authorization) has to be valid across multiple scs'es.
OAuth2 Authorizaion Server is a dedicated server (UAA).
In the OAuth2 terminology, each scs is a Resource Server.
Let's assume that user has logged into scs1 (via UAA) and got JWT with TTL=10 minutes and RefreshToken with TTL=30 minutes. Then he leaves that tab in browser for 15 minutes. JWT expires, but the tab still contains the previous page from scs1. And user clicks a link on that page that follows to mysite.com/scs3.
scs3 receives a request, checks JWT and finds out that it has expired. But we have a RefreshToken (still alive for 15 minutes) that may refresh JWT.
Is it possible to return a response from scs3 that would ask browser to go to UAA and silently refresh JWT ?
Maybe some kind of REDIRECT to /uaa/authorization with an ability to add RefreshToken Header?

We have finally found out how to deal with token refresh in our case.
JWT has TTL=10min
RefreshToken has TTL=30min
Javascript, embedded in each page of our site refreshes JWT each 8-9 minutes. So when User has an opened tab in his browser, the refresh procedure will happen seamlessly.
A corner case is when User:
Opens tab mysite.com/scs1
Logs in
Closes tab
Waits 15 minutes. JWT expires, RefreshToken is still alive.
Opens new tab and enters mysite.com/scs1 or scs2 etc.
At this point the BackEnd receives only JWT which is expired.
So BackEnd redirects User to a dedicated web-page /try-refresh?uri=mysite.com/scs1
try-refresh page contains ONLY javascript which tries to refresh token and in successful case redirects User back to address from uri parameter

Related

How to use two factor authorization cookie along with single factor authorization cookie

I have a web application with singe factor authorization and now have implemented two-factor authorization. I am using the Microsoft Identity for the log-in. The problem is - so far we have used a cookie to remember the user while providing the username and password. Say that as 'signglefactorcookie'. Now on the authenticator application authorization page(TFA), I have added another cookie for the remember me option. Say that as 'twofactorcookie'. Now how can I make my client request for both cookies when I use the below code?
// Check whether there is a valid session or persistent cookie
if(this.User.Identity.IsAuthenticated){
// Move to a landing page
}
Problem scenario
Now the problem is, if I log in to the single-factor authentication page with the correct user name and password and land at the two-factor authentication page.
Open a new tab and try to access the home page getting success since there is a single factor cookie that is recognized which makes the user authorized.
How can I make it in a standard way?

.net core 2.0 & Identityserver4 : Cookie Not getting expired after logout

I am using identityserver4 for all configured clients with "AccesssTokenType=1" i.e. reference type.
I have one web app hosted for server, and other one for clients.
I used default identityserver settings, which generated two cookie, one for session Id "idsrv.session", and other one for authentication "idsrv".
In logout I do signout
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
await HttpContext.SignOutAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme);
however it gives error when I call with "idsrv.session"
await HttpContext.SignOutAsync(IdentityServerConstants.DefaultCheckSessionCookieName);
Issue / Steps to reproduce the problem
1st Iteration : Login on my client website which redirects to my identityserver application. I now interceprt the request and response using "Burp Suite". I copy the complete response which has redirect URL's and cookie details.
I signout/logout from client website.
2nd Iteration : I tried login again, and intercepted the request and response using Burp Suite, by passing wrong credential. While Intercepting the response I just copied the cookies from previous request (which was successful in my first iteration), and observe that identityserver has successfully validated the user using the cookie value, ignoring the wrong credentials in this iteration.
Even I tried invalidating and deleting cookies in my signout/logout method, but looks like identityserver still recognises it as the valid ones.
Brock Allen directed me to the corrrect solution. According to him :
This is the real issue you're asking about -- when you signout, you want the cookie to no longer be valid, even in the scenario when it's stolen and replayed. This is not something IdentityServer can address, because we use Microsoft's cookie authentication to achieve signin. You would have to fix this by changing the default usage of their component. You can do it by implementing "server-side cookie" (a term that I dislike) by implementing an ITicketStore: https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationOptions.cs#L136
Details Here
https://github.com/IdentityServer/IdentityServer4/issues/2565

JWT Refresh token and Multi-Page Application

I am going to implement JWT authentication for several independent services.
There will be auth.example.com and service1.example.com, service2.example.com etc.
My assumptions:
JWT can be kept in cookie for ".example.com"
JWT expire time should be small (like 15 mins) because there is no reliable way to logout user with JWT token (revoke token).
Refresh tokens should be used to reissue JWT tokens
Refresh token cookies should be accessible only by auth.example.com for security reasons and because https://www.rfc-editor.org/rfc/rfc6749#section-1.5 says
"Unlike access tokens, refresh tokens are intended for use only with authorization servers and are never sent to resource servers."
Next, if I have a service - multi page application (i.e. not SPA), where some URLs are called "traditional" way, not via Ajax and render HTML
based on some server side logic, which, of course, include checking of user authorization.
then, say, there will be an action service1.example.com/user/showpage
if (user.logged_in) {
render_some_html(get_some_data(user.login))
}
else {
render_anonimous_uses_page()
}
Problem is:
If site user close all site tabs and, then after hour or so, go directly to page /user/showpage (or maybe he
suspend laptop and wake it up in an hour and go to that page).
What if by that time JWT token will expire. Then to refresh it by Refresh token we need to make Ajax call to auth.example.com (because Refresh
token is stored only in auth.example.com cookie) and this is just unaccessible in server side rendering (that pseudocode that I posted above, it's server side, and it's just impossible to make client ajax call in the middle of execution of server code. it's just not applicable here). This way user will be considered logged out
on this stage.
Redirect could be one solution.. but what if site should work for anonymous out users too, and anyway looking for something better.
This problem not exists for SPA application, because before every Ajax call to internal API, it can check JWT and make call to refresh JWT token.
And question is: is this true that JWT in general should not (cannot) be used in Multi-Page (traditional) applications because of this issue? or there is good way to workaround this? or this is not a problem at all (users don't close tabs too often, or they expect site to log them out or redirect etc)?

ExpressJS and Firebase Auth, beginner queries

I am trying to learn ExpressJS, so I creating a simple website with login functionality...
I want to use Firebase for the accounts and database(Firestore)
My problem is that, Firebase Auth seems to be client-side only and the backend has no idea if the client is logged in or not...
I want to limit the HTML rendered to the client if he is not logged in, but I can't figure out how to check if he is logged in
I know that I can use
firebase.auth().onAuthStateChanged(function(user){
if (!user){
window.location.replace("/login");
}});
on the client side, that doesn't look "Secured" enough to me and I would like to do it in ExpressJS
On firebase documentation I found this about Verifying ID Tokens
but I don't understand first of all how would I send the token to ExpressJS and second, how would I send it before the request to a route is made...
You have to pass the ID token to your backend. You then verify the ID token as explained in https://firebase.google.com/docs/auth/admin/verify-id-tokens#retrieve_id_tokens_on_clients.
You pass the ID token in the request header if your application is a single page app everytime a request is sent.
If you are building a more traditional web app, you can set the ID token via a cookie and retrieve it and check in on your backend with each request. You have to do the following:
Proactively refresh the ID token by calling getIdToken(true) before the token expires. The token typically lasts an hour. You would need to refresh it before expiration and update the cookie so a redirect will still consider the user signed in.
If the user visits your website after a while (longer than an hour), the cookie would be expired, you would redirect to a temporary page where you set onAuthStateChanged and if the user is logged in, call getIdToken(), update the cookie and redirect to the intended destination, otherwise consider the user signed out.

Web API 2, OWIN Authentication, SignOut doesn't logout

I'm doing some research for work with a view to using Bearer tokens as an authentication mechanism (i.e. AngularJS UI, authenticates via OWIN in a Web API [2] project).
I have the login working fine, role information and all that is fine, but I cannot get the token to logout.
My startup configuration is this:
OAuthOptions = new OAuthAuthorizationServerOptions() {
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenExpireTimeSpan = SESSION_TIMEOUT,
AllowInsecureHttp = true
};
And my logout action is simply this:
public HttpResponseMessage Logout() {
var authentication = HttpContext.Current.GetOwinContext().Authentication;
authentication.SignOut(DefaultAuthenticationTypes.ExternalBearer);
return new HttpResponseMessage(HttpStatusCode.OK);
}
I've left all the authentication stuff out for brevity, but to confirm I am using ExternalBearer when setting up the token.
In my UI I'm storing the token in local storage (no cookies are involved here, which is a deliberate design decision). So I have a logout button on my UI, the Logout action is hit and the code runs fine.
However if I subsequently hit the an action on the API which requires authorisation, the request still goes through (i.e. the user is still authenticated even though they should have been signed out.
Either I'm missing something really obvious (wouldn't be the first time ;-) or there's something more fundamental going on here - finally I'm pinging #leastprivilege as I know this is their area.
Any help or insight would be gratefully received.
Only thing I can think of is that the token is stateless on the server/API side and hence can't be expired or signed out.
If that is the case I guess I could either:
a) Add a refresh token which creates a new token that expires in the past - would this even work? - actually cancel that, it would issue a new token ... the old one would still be valid
b) Store the bearer token in the database and check each time, removing the token on logout (naturally salted, hashed, etc). However this is just bringing us back to having a stateful server.
c) I can (and will) be removing the token from local storage when someone explicitly logs out, however the token is still technically valid if a baddy can intercept the token. Naturally all the above will be over SSL anyway, which should inhibit the bad guys/girls.
d) Perhaps this is why lots of people are storing the Bearer token in a cookie (as a storage mechanism) so once you logout as least the cookie will be removed on the next refresh.
Sorry the above is a bit of a brain dump, just wanting to pre-empt any questions
Since OAuth is not an authentication protocol, there is no notion of signout. Delete the access token on the client - that's all you can do.
If you want to invalidate the token on the server side, add a unique id to it and keep track in your service - you would need to manually build something like that.
I have a beautiful solution here: http://www.nakov.com/blog/2014/12/22/webapi-owin-identity-custom-login-service/. It is custom user session implementation for Web API OAuth bearer token authorization based on OWIN and the standard ASP.NET Identity (Microsoft.AspNet.Identity.EntityFramework). It works as most people may expect:
Web API sessions die after 30 minutes of inactivity.
Session’s life is extended at each authorized HTTP request with additional 30 minutes.
Logout works correctly: after logout the bearer access_token becomes invalid (its is revoked).
Full working source code is available at GitHub: https://github.com/SoftUni/SPA-with-AngularJS/tree/master/Ads-REST-Services
This question has been here for ages (and answered too), but I only wanted to chime in my thoughts.
I would do similar to your (C) option, but use a shorter expiry on the bearer access token something like 10 or 20 minutes, so that when you have logged out and deleted the token on the client, although technically the token is still valid, the bad man will have only the remainder of the expiry time to play with your valid token.
In practice, I would use this together with a long-lived refresh token, so that I can get a new bearer token if it expires and want to continue interacting with the API resources, without having to authenticate again.
As long as I know the bearer token lives in the client side so I don't think that you need a server side "logout" function. Just remove the token from the client local storage should log you out.