REST authentication, Best approach - codeigniter

Background:
We are building system that required login information for all pages. the application is designed to be Restful application using codeigniter as Phil Sturgeon library.
Scenario:
- username & password is required when a user called any page [Client]
- Authentication is needed where any Api call is fired
I a bit confused how to migrate or do the above scenario, And what are approach to authenticate the application.

A simple way to authenticate users in a RESTful API is using HTTP Basic or Digest Auth. In this setting the user credentials are sent via the Authorization header in a form of username:password as Base64 encoded hash to the server.
As the principles of REST state that the communication between client and server should be stateless, the client has to sent the authorization on every request. In practice this means that you often store the credentials in a session on the client side (as you don't want to the user to enter his credentials on every request). Please note that you should only do this via an secured connection using HTTPS!
To authenticate the application you could use a token based system, such as an API-Key. This means any request would be signed using additional request parameters. If the number of applications is finite and known, you could alternatively simply identify them by their IP.
You could also take a look at OAuth.

Request the login and password for every page is more suitable and more secure(that what I do in my projects), using 'virtual' and stored session in the database may be a second solution but not a good because it will be an additional charge for the DB.

Related

Acceptable OAuth Flow for a decoupled frontend/Backend Architecture?

I have a NextJS frontend and Golang backend architecture with an authentication system using JWTs and an internal user/password database. I'm adding OAuth sign-in in addition to the JWT system, but all API calls will still be maintained using JWTs. I have a working prototype that uses the following OAuth flow:
User is directed to a NextJS page that displays various login options as buttons.
When a provider is chosen, the user is redirected to the backend at /auth/provider where they are then redirected to the provider with all required keys and callback links.
User logs in at the provider and the redirect is triggered to /auth/provider/callback.
The backend server retrieves the user data from the callback and connects the user email to the internal user data for generating a JWT.
The backend returns a page that stores the JWT in local storage and redirects to a NextJS page.
The NextJS page can then use the stored JWT to make API calls.
An additional step could be to exchange the JWT for a new, non-stored JWT or session cookie if the JWT is used twice (potential XSS attempt) and the new JWT is invalidated.
The above method works, but requires a locally stored JWT. Is this a concern, and is it possible to complete the final steps without the need for a locally stored JWT.
Does this flow make sense or am i going about it all wrong? Would swapping to PKCE be overkill?
For the current prototype I'm using the github.com/markbates/goth example code running as the golang backend and a basic NEXTjs server
In effect you have a form of backend for frontend there. It is worth browsing OAuth for browser based apps a little similar to section 6.2 of the above doc.
One option might be to host the backend at a URL like https://api.example.com, then make it write cookies for the Next.js app, hosted at a URL like https://www.example.com.
In this way the backend and frontend parts of the OAuth flow are decoupled, and you also avoid locally stored JWTs. Note the same domain prerequisite, needed for the cookie to be considered first-party, and therefore avoid being dropped by browsers later.

How to access a secured API in the frontend?

There is a lot of good content on the internet that explains how to secure a Spring API with Keycloak: Create a Client that represents the API Service in Keycloak and use a link like the one below to get the access and refresh token:
<Domain>/auth/realms/<realm>/protocol/openid-connect/auth/{some parameters}
This yields both tokens. So far so good.
Now, however, I am not sure how the flow for the frontend accessing the API should look like.
Should the frontend directly access this endpoint and, therefore, obtain the access and refresh token? That would mean that the API can only have the access-type public because there is no way to store the client (the API) secret securely.
Or should there be a third server that somehow stores the refresh token for each user, that the user can call if his access token is no longer valid. This server would then use the client's refresh token (and the client secret that could be stored securely, since it would be in the backend) to get a new access token from Keycloak and would forward it to the user.
I guess the main question that I am asking is, whether the client/user should get the refresh token.
If one needs to implement a logic according to the second option, I would be interested in a link or description of how something like this can be done in Spring.
I think, in either case you need to use the Authorization Code Flow. The implicit flow, which was recommended for SPAs (frontends without a backend server) in former versions of OAuth2 must not be used anymore.
The best option is to have a backend server, so the user retrieves the auth code via redirection and the backend server exchanges this auth code with the access and refresh tokens (and keep them without forwarding them to the frontend).
If there is no backend in place and your frontend needs to retrieve and hold the tokens directly, I would recommend to use the Authorization Code Flow with a public client and the PKCE extension (which - put simply - ensures that the entity asking for the auth code is the same as the entity asking for the tokens and that the auth code was not stolen and used by a foreign entity). There are several sources with more detailed explanations, which might help you, for example: https://auth0.com/docs/flows/authorization-code-flow-with-proof-key-for-code-exchange-pkce
Hope this helps you with your architectural considerations.

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.

.NET WebAPI and http basic authentication

I created a WEBAPI solution and I am creating the HTML pages to access all the functions of that web service. I am using http basic authentication.
I got these options
Save the username and password in a Javascript vars and send them every time I call any of the WEBAPI functions.
Send the username and password the first time, create a token on the server and send it back to the client, then save it as a cookie and use it every time I call any of the WEBAPI functions.
Dont use HTTP basic authentication.
What is the best way to handle this?
Thanks
You don't want to send the username / password on every call for security reasons.Token based authentication would be the way to go and you can use the built in identity authentication for that.
The best tutorial I have found for that is http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
There's nothing wrong with using basic authentication as long as it is done over a secure channel. If you send the username and password on every call, your api will need to access the database on every call just to authenticate the user. If you send a token when the user is authenticated, then you remove the need to access the database on subsequent calls.
Using a token also allows you to take advantage of an identity provider such as Thinktecture's IdentityServer to provide single sign on. If you have more than a few systems, it will allow users to log in one time and then access any of the applications and it can greatly simplify security.

API Authentication and use of OAuth2

I’m trying to get my head around how I would introduce token-based (key-based?) authentication to a web API (currently looking at Sinatra, but maybe Rails too) that would be used by a mobile client and how OAuth would fit into the picture.
So, let’s say I want to create a web service that uses Facebook for authentication and grabbing basic user data. Here, my API would be a client to Facebook’s OAuth Server, requesting an access token upon a user’s successful login to Facebook. This would then grant me access to the user’s data which I would use to create an entry in my database, storing this user-specific token with any other application information I would like linked to them.
I think I got that part right so far, but here’s where I’m a bit confused.
I think that my API would also need some form of API key to grant access to a mobile user, since I wouldn’t want to transmit and store the Facebook key on their device. Would I have to have a separate store of keys which I provide to the client to access my service? Are there any ‘best practice’ ways of doing this?
Would I have to have a separate store of keys which I provide to the client to access my service?
yes.
Are there any ‘best practice’ ways of doing this?
The simplest way would be to generate a separate authentication token on every User creation and expose that to the mobile client. Then send it with every subsequent request header.
Devise provides a simple example how to achieve that. You don't need devise for that, just provide some token generation mechanism.
#Devise.friendly_token
def self.friendly_token
SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
end
This mechanism can be extended to provide more security in following ways
Being an oauth2 provider itself.
On successfull login with facebook, you would generate an :authorization_code which the client can exchange for your own Oauth2 Bearer or MAC token within a next step. Then you can send your own Oauth2 token with every request for user authentication.
See rack-oauth2
Implement HMAC token encryption.
Generate and expose a secret_key to every client after singning in. Use this secret to sign messages along with a unique client id. The server can then lookup the secret_key for the specific client_id and verify the message.
See api-auth

Resources