How do I handle ajax authentication after initial Login with Shiro - ajax

I have implemented the usual username/password login process with Shiro for my single page webapp which will submit the username and password over https in production. I use a REST back end rather than a typical MVC framework of any sort to facilitate my SPA. Typically with a REST API a BasicAuth is used to log in, and in response if successful an encrypted token is returned either as a cookie or a response header. Subsequent calls would return the cookie or header to avoid having to resend username and password. Usually the token is an ecnrypted username possibly with some other info that can be derived on the server side either as a session token or something else.
Anyway, as I said I am using Shiro and I understand Shiro can use multiple realms for authentication and authorization. What I am trying to do for my web site is require the initial username/password login, then after a user is logged in, somehow avoid the Shiro UsernamePassword authentication process and instead use the token check process.
I think the right way is to provide my own custom authentication realm and credentials matcher.. and I have a public domain SHA256 salted password bit of code that stores the salt, iterations and password in one string that I'd like to use. What I am not sure of is how to configure the shiro.ini... do I need to provide two custom classes, one for my own username/password for initial login, then another for my token authentication? Or can I utilize the built-in shiro usernamePassword, and will it's rememberMe feature be good enough in jquery $.ajax() calls? Perhaps I can use the Shiro implementation but also need to attach the shiro rememberMe cookie to all my $.ajax() calls?
Just a little confused really on the best approach to provide good username/password initial login and subsequent calls without needing to resent username/password... and to support session invalidation and logout functionality.
Another thought is to not use Shiro, instead use my own servlet filter to check for the initial login, if authenticated, return the response header (or cookie) myself with my own encrypted token that I keep in HttpSession or in a database back end for the duration of the session, and make sure in my jquery ajax that after each response to look for the token, and resend it in the subsequent requests.
Thanks

Related

JWT in Cookies - do I need a refresh token?

I'm implementing security for my React SPA using Spring Security on the backend. After a lot of reading, I opted for the following approach :
HTTPS everywhere
POST /login takes credentials returns JWT_TOKEN & XSRF_TOKEN in cookie form. I build the JWT_TOKEN myself whereas Spring Security handles the XSRF_TOKEN. Both cookies are Secured and SameSite=Strict. The JWT token is HttpOnly.
Subsequent API calls require the X-XSRF-TOKEN header. This is read from the aforementionned cookie. Both are sent and Spring Security compares them. JWT is automatically sent and checked in a Filter.
Every time a XSRF token is used, Spring Security generates a new one to prevent session-fixation attacks
XSS protections are applied by Spring Security
So now I'm wondering about refresh tokens. I'm reading a lot of contradictory info out there. Do I need them with this setup? If so how best to handle this ?
Many Thanks
In general, as its name says, the refresh token changes from one token to another. Typically they are used in OAuth protocol-based authentication. They are useful when an access token has expired, but the user's session is still valid.
First, JWTs are a great choice for access tokens. They have claims that match the access tokens requirements, such as: exp, iat, jti, sub, etc. But, when using a cookie-based authentication there is no need for access tokens and possibly no need for JWT.
As you said, your JWT_TOKEN is being set as an HttpOnly cookie, which means that only the server has access to it. JWT is useful for sharing the initial state between the client and server, and vice-versa. If your server is just taking it to look up the database, you don't need a JWT, you are just using a session concept, and keeping session data on a JWT may not be a good practice.
Second, if your authenticated cookie data will live at /login and die at /logout, there is no need for refresh tokens. Refresh tokens are an exchange key for short-life access tokens. Instead, your cookies keep the session live and don't need to be exchanged by something else.
For example, if the user uses the /login route to exchange your username and password for one short life access_token. He may need the refresh_token to get a new access_token without needing to send his username and password again.
If you are using the OAuth protocol or similar, refresh tokens are essential to provide a more seamless experience for your users and avoid the inconvenience of repeatedly having to re-enter their credentials. But even on OAuth, they are not mandatory.

JWT and Session: how JWT should be properly used instead of Session

I am working on a project with PHP and angular. For the user sign in, we're using JWT. Still can't understand why we should use JWT instead of Sessions if each time the user browse a component we need to send the token to server code to check if the user still signed in or not.
Username and password will be sent to server code, where the authentication process will happen, and then generate a token and send it back to angular then save at the local storage.
Any comment on how JWT should be properly used.
EDIT
My question is about the process of checking the JWT when user surf the site and go from component into another.
If you use session for your application... Then while horizontal scaling sharing the session data becomes a burden ....you either need a specialised server .. Jwt are stateless and have no such requirement. It contain following data
Header - information about the signing algorithm, the type of payload (JWT) and so on in JSON format
Signature - well... the signature
Payload - the actual data (or claims if you like) in JSON format
Your JWT already is a proof of your authentication. So you have to send it with each request but you can simplify the authentication logic on server-side.
While on the login you will have to check the credentials you can rely on the JWT's signature and expiryDate. If the signature is still correct the token is valid and you do not have to authenticate anymore.
So regarding your horizontal authentication.
If the called service needs to be authenticated you have to check the JWT for validity on each request (normally works reasonably fast). If there are open api calls you can of course ignore the JWT on server side.
At the end of the day there is no difference to your "session" which will also send some "secret" key which maps your session context. Therefore, it will also be validated.
For some backends you can also use the JWT as your session key to get both worlds involved.
Example:
lets say you have two api roots:
api/secured/*
api/open/*
(Note that the secured and open are only here for demonstrative purposes)
The secured part will contain all the services you want to be authenticated.
The open part can contain insensitive data as well as your login services:
api/open/login -> returns your token
api/open/token/* -> refresh, check re-issue whatever you might need
So now lets say the user accesses your site. You will want to provde an authentication error if he tries to access any api/secured/* URL without a proper JWT.
In this case you can then redirect him to your login and create a token after authenticating him.
Now when he calls an api/secured/* URL your client implementation has to provide the JWT (Cookie, Request header, etc...).
Depending on your framework, language etc. you can now provide an interceptor/filter/handler on server side which will check:
If the JWT is present
if the signature is valid (otherwise the token was faked)
if the JWT is still valid (expiryDate)
Then you can act accordingly.
So to sum up:
There is no need to "authenticate" unless you want to create a new token.
In all other cases it is enough to check the validity of your JWT

Asp Web API. JWT Authentication vs username / password Authentication

Sorry for such novice question.
I am fairly new to web security.
Can someone please explain to me, why do we need JWT token authentication for web api (REST) when I could include { username | email } / password for every single API request?
Mostly, it's a separation of concerns thing. JWTs are a way to authorize a request, whereas username/password is a way to authenticate. The key difference is that authentication is something you should ideally only have to do once, and it should be done by a dedicated endpoint responsible for that. For every other request, you're simply confirming the authorization you received from that initial authentication.
If you were to send username and password with every request, every endpoint then would have to handle authentication logic, which would be a nightmare. Using a JWT, the endpoint can simply verify that it's valid and move on to what it's actually responsible for.
JWTs are just one method of authorization. In a traditional website-style application, this would be handled by a cookie. This then enables the user to login once, and then proceed to browse protected areas of the site without having to login again. The equivalent of what you're suggesting would be essentially like forcing the user to login again everytime they clicked a link, just to view that next page.

Spring OAuth2 Password Flow , Return JWT inside HTTP Only Cookie?

I am using AuthorizationServerConfigurerAdapter to configure my OAuth2 password flow where I am successfully creating a JWT token. I am using my OAuth2 within my Spring REST backend and pairing it with my Angular 2 fronted.
I have read several articles (eg. https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage) where people are putting the JWT inside a HTTP only cookie returned to the Angular front end to prevent XSS scripting and it is of interest to me. I am confused how to integrate or intercept my jwt being returned and place this inside a http only cookie and return it.
Any Suggestions?
John
I wouldn't recommend using password flow at all, especially in a browser client. OAuth2 was designed so that you can avoid that, and thus avoid giving user credentials to an untrusted agent. If you let go of password grants, you will find that a session cookie is just as secure as your JWT cookie proposal, and it works out of the box with no funny business on client or server.

How does spring basic authentication works for subsequent requests after login via basic authentication

I am implementing REST services using springMVC. Now i have added basic authentication entry point in my spring security file. But i don`t know that, Once user authenticated by passing credentials in Authorization header does he need to pass those credentials for all subsequent requests?
for example,
I have two URLs:
1) localhost/apppName/login
// Here user passes credentials in Authorization header. So, user authenticated successfully.
2) localhost/appName/getUsers/1
//Here, client need to pass those credentials in Authorization header?
if it is needed, then why spring kept prinicpal object in the SecurityContextHoder after authentication done via BasicAuthenitcationEntryPoint?
Clients of this services can be any thing like Android, java, .Net
Any suggestions will be appreciated.
Pure REST is stateless, which means that no client context is being stored on the server between requests. That means you need to send the Authorization header for each request.
You don't need to hit the login URL when using Basic auth, that's the point.
However, you can use sessions in combination with Basic auth, and in that case you should pass session cookie between requests. It may have some performance advantage, but generally I would not recommend it.

Resources