Where and how should CSRF token be stored for sending back and fro from server to client and client to server? - csrf-token

I have read a lot of posts/comments saying that CSRF token can be used for improving security for a Web application or an API but I cannot find information how CSRF token is implemented.
I assume on the server side one can store CSRF tokens in a memory cache, SQL server, etc I assume the client sends the token back in a POST request, in the header but how does the server sends a token to a client securely and where does the client store the token (some posts say don't store the token in the session cookie and some say don't store it in a hidden field but do not state the alternative)? Furthermore, does the server generate different tokens during a session (ie. a new token per request)?

Related

How does client send an authentication token back to the user in OpenID connect?

I'm learning about OpenID connect and OAuth2.0 and i think there is something missing, what the client will do after receiving the ID token from the authorization server?
Ok it now has a JWT that contains information about the user, but when the user wants to send a request to the client to do whatever he wants to do, he should attach a token with his request, right? so, when the client will generate this token? as far as i know, if a server uses HTTP as its protocol, it can't send data to the user if the user didn't issue a request, so it shouldn't be able to send that token without a request from the user.
Did i miss something?
I tried to search about this stuff, and I didn't find anything useful.
Ok it now has a JWT that contains information about the user, but when
the user wants to send a request to the client to do whatever he wants
to do, he should attach a token with his request, right?
Should say "but when the client wants to send a request to the server ..."
if a server uses HTTP as its protocol, it can't send data to the user
if the user didn't issue a request, so it shouldn't be able to send
that token without a request from the user.
The token will have been provided to the client during sign-on process.
To summarise the process:
Client enters credentials (e.g. username and password) and sends those to a login endpoint.
The login server will generate a JWT and return to client.
Client receives a JWT and caches it locally at the client end ready to be sent to the server on subsequent requests.
On all subsequent requests to the server the client will attach the cached JWT in the authorization headers of the http request.
The server will validate the token to ensure client is authenticated.

Is Basic Authentication a Session based authentication and why Jwt is more recommended?

I'm learning about Basic Authentication and Jwt Authentication with Java and Spring and I want to ask you if basic authentication is a session based authentication?
I know that in a session based authentication, when the client log in, a sessionId is stored in cookie on the client browser and after that when the client make another request, the server compares the sessionId with the data stored in the memory of the server. And also I want to ask you how is the sessionId sent from client browser to server? Is it sent in the header like a token or how?
And the last question is how the server validate the Jwt token? I know that in case of session authentication, the sessionId sent from client is compared with the data from the memory of the server. But what's happen in case of Jwt authentication? The token is sent with the header and I know that the server validate it and there is no data in the memory of the server. Then how the server compares the token? Any feedback will be apreciated! Thank you!
if basic authentication is a session based authentication?
I know that in a session based authentication
well then why do you ask?
Actually - basic authentication means, that the user credentials(username and password) are sent in the Authorization http header
Authorization: Basic base64(username:password)
The server may or may not use a session cookie. Session cookie may be used with other authentication means or even without any authentication
how is the sessionId sent from client browser to server?
As a session cookie A session cookie is sent as an http header which browser treats as session-persistent
And the last question is how the server validate the Jwt token?
The JWT token should be signed. Note the token has usually 3 parts
header.body.signature
the header specifies a signature type (an asymmetric key or shared secret) and the signature is authenticated (signed or hmac-ed) header and content.
So - the server must validate the issuer, expiration and the signature.
So the server (service provider) doesn't need know the client's identity upfront. The service provider needs to know the issuer's (authentication service which issues the jwt token) public key or shared secret key.
After the jwt validation the service can assume the caller's identity based on the information in the jwt token.
why Jwt is more recommended?
It depends in the use case. (everything has its pros and cons)
I'd recommend using jwt in a distributed and/or microservice architecture. The service doesn't need to access the credentials or to authenticate the user.
In the basic authentication we need to send the username and password for every request.
In the session authentication we will send username and password at initial request. Then from server response we get the session id which stores in browser and gonna use that for requests.
In the token authentication we will send username and password at initial request. Then from server response we get the token and gonna use that for requests.
hope u got it!!

Is the cookie dependent on the browser?

I'm a little confused about the cookie and I want to know can we use cookies somewhere other than the browser, like a mobile app or desktop app. Is the cookie dependent on the browser?
No, cookie is not dependent on browser.
Cookie is dependent on HTTP "User-Agent" -- the software/library client that is acting on behalf of a user, following HTTP protocol. Browser is just one type of it. Other types of "User-Agent" includes:
CLI software that can send HTTP request, such as curl or wget.
Library that can be imported in project and send HTTP request. Take Node.js project for example, they can be request or axios. All major programming language have its own HTTP client libraries.
Self-implemented HTTP client logic code.
more...
In a mobile app or desktop app, if HTTP is used for application, it is highly likely that cookie is used.
Any HTTP client can use cookies. A cookie is just a HTTP header sent by the server, with a value that is sent back to the server by the client in subsequent requests. Consult the documentation of your HTTP client to see if there is built-in support for remembering cookies.
Session Based Authentication
In the session based authentication, the server will create a session for the user after the user logs in. The session id is then stored on a cookie on the user’s browser. While the user stays logged in, the cookie would be sent along with every subsequent request. The server can then compare the session id stored on the cookie against the session information stored in the memory to verify user’s identity and sends response with the corresponding state!
Token Based Authentication
Many web applications use JSON Web Token (JWT) instead of sessions for authentication. In the token based application, the server creates JWT with a secret and sends the JWT to the client. The client stores the JWT (usually in local storage) and includes JWT in the header with every request. The server would then validate the JWT with every request from the client and sends response.
The biggest difference here is that the user’s state is not stored on the server, as the state is stored inside the token on the client side instead. Most of the modern web applications use JWT for authentication for reasons including scalability and mobile device authentication.
Scalability
Session based authentication: Because the sessions are stored in the server’s memory, scaling becomes an issue when there is a huge number of users using the system at once.
Token based authentication: There is no issue with scaling because token is stored on the client side.
Multiple Device
Session based authentication: Cookies normally work on a single domain or subdomains and they are normally disabled by browser if they work cross-domain (3rd party cookies). It poses issues when APIs are served from a different domain to mobile and web devices.
Token based authentication: There is no issue with cookies as the JWT is included in the request header.
Token Based Authentication: using JWT is the more recommended method in modern web apps. One drawback with JWT is that the size of JWT is much bigger comparing with the session id stored in cookie because JWT contains more user information. Care must be taken to ensure only the necessary information is included in JWT and sensitive information should be omitted to prevent XSS security attacks.

basic HTTP authentication on subsequent requests

The image below depicts basic HTTP authentication. The client requests /family resource and it is asked to identify itself. It does and now it can access the /family. The client then also asks for /family/photos/kids resource which is in the family realm.
The client already identified itself for /family resource, but not also for /family/photos/kids. They are in the same realm, but the server doesn't know that the same client issued a request. Or does it? How does the server know that this particular client is also allowed to access /family/photos/kids on subsequent request? Is the password and username send on every request after the user has authenticated? Is the client asked for via pop-up for every request he/she makes? Are cookies set upon first authentication?
Basic authentication requires a header sent by client. No cookies or server session
When the client requests a resource, sends the Authorization header
GET /family
Authorization: Basic token
Where token is base64(username: password). Username followed by ':' and password encoded in base 64
If you are requesting a protected resourced from your browser for example a GET request, and you do not provide the header, the browser shows the autenticathion form and remember it for subsequent requests in the same domain

Create session oriented API's in asp.net Framework 4.0

I am working on a project where mobile apps connects to website through a set of API's. I considered creating API's using "Generic Handlers". This was seems to be working fine until restriction are defined for sensitive data. User has to be authenticated before he makes request for data.
I created a login API where user credentials are validated and a encrypted string which contains the same credentials which he provided at the time of login are returned back to the user after successful validation.
Each time a user makes request after successfull login, an encrypted string was supplied back to server in header. On server side, the encrypted data is decrypted and validated against with the credentials stored in DB. This step is unnecessary as user is recently authenticated. Is there anyway I can avoid authenticating user for each requests. I am planning to go with WCF services where Session can be effectively used to achieve the same (is this is something good idea?)
I did the same steps as you are doing for my API's. Here are some of the changes I made in the authentication part.
Client sends his credentials (username and password) to /api/login
Server validates the credentials and forms an encrypted string with identify of user and some necessary data like expiry date. Call this as token.
var tokenStr = "user_id=1234;expire_date=" + DateTime.Now.AddMinutes(20).ToString();
var encToken = AESCryptoService.Encrypt(salt, tokenStr);
Return this encrypted token to the client
Client sets this token in the HTTP header (X-App-Token) to make future API calls.
Server detects and decrypts this token. Here you can trust this token if decrypts with your salt. Get the user_id and set the current thread principal and proceed with the request.
If the token expires (read expire_date) then return 401 Authentication request, so that the client can request the token again.
You can also use SHA-1 or MD5 or some signing/encryption mechanism to make sure that the token string cannot be altered other than you.

Resources