Flask-HttpAuth and Flask-Login - authentication

I am creating a small REST service. I am looking for different authentication methods.
For sites I used the module Flask-Login. It seems the session authentication. The module Flask-HttpAuth provides the http and digest authentication methods. I am little bit confused.
Do they complement each other?
What is better to use for what is a reason?
Thank you.

For a REST service you do not need Flask-Login. Typically in web services you do not store client state (what Flask-Login does), instead you authenticate each and every request. Flask-HTTPAuth does this for you.
You would use both only if you have an application that has a web component and a REST API component. In that case Flask-Login will handle the web app routes, and Flask-HTTPAuth will handle the API routes.
Disclaimer: I'm the author of Flask-HTTPAuth.

You can setup Basic Auth for Flask in a very simple way, without further modules, using decorators.
Take a look at: http://flask.pocoo.org/snippets/8/.
With flask-restful, just add method_decorators = [required_auth] to the Resource class attributes.
You can extend the snippet above, to allow for example user retrieval from a database.
Note that in a REST architecture, requests are stateless: you don't use sessions, but send identification tokens along with every request (see http://broadcast.oreilly.com/2009/12/principles-for-standardized-rest-authentication.html).

Yes they complement each other.
You can also take a look at Flask-security, an all-in-one lib:
https://pythonhosted.org/Flask-Security/
Session based authentication
Role management
Password encryption
Basic HTTP authentication
Token based authentication
Token based account activation (optional)
Token based password recovery / resetting (optional)
User registration (optional)
Login tracking (optional)
JSON/Ajax Support

Related

When to create backend application in keycloak

I see that in most of the keycloak tutorials it is suggested to create two client in keycloak i.e. frontend, backend. But I don't understand the need for this since I can validated the JWT token provided by frontend using public key even without creating separate client.
So my question is, is the approach of not creating the backend app the wrong approach? Also when & why should we create a backend client in keycloak.
Ref - https://medium.com/devops-dudes/secure-front-end-react-js-and-back-end-node-js-express-rest-api-with-keycloak-daf159f0a94e
I see most of the tutorial of keycloak suggest to create two client in
keycloak i.e. frontend, backend. But I don't understand the need of
this as I can validated JWT token provided by frontend using public
key even without creating separate client.
Typically, such tutorials are created to showcase the authentication and authorization capabilities of Keycloak.
The authentication part is showcased by the user authenticating via the browser (using the frontend client), whereas the authorization part is showcased by the application sending an access token to the Keycloak server where the claims on the access token (e.g., roles) can then be used to infer if the user has the permissions to perform the desire action (i.e., authorization).
So my question is, is approach of not creating backend app is not
right approach?
Depends on your specific use case. Alternatively to the approach that I have previously mentioned, one could have had a single client (i.e, the frontend client), and after the user has successfully authenticated, the application would pass the access token to the backend. The backend could then perform the authorization by directly checking, for instance, the roles in the access token, instead of relying on the Keycloak server to do so. There are pros and cons to both approaches.
Also when & why should we create backend client in keycloak.
A typical example would be if the backend would be a separated micro-service that triggers some maintenance task for example. Assuming that task is not related at all to the user authentication process, it would make more sense to then have a separate client (in this case a confidential one) that would rely on the client credentials flow which is typically used for machine-to-machine use-cases.

Integration of frontend and resource server using okta authentication and client credentials API authentication

We have an application that has frontend UI(Which is a web application) which communicates with a resource server. Our frontend will be using some APIs from a resource server to get data.
I am planning to add frontend to Okta and provide access to okta registered users.
In the resource server, we have some APIs that we want to expose to our customers to integrate in their system(Programmatically). To use our APIs, we have to provide client credentials(client ID/secret) to them. Using clientId/Secret, they will get access_token and will use that in a subsequent request. We can display this clientId/Secret via frontend UI once the user logs in to it via Okta.
How should I authenticate requests to the resource server from the frontend? And how do I authenticate requests to resource server via customer using clientId/Secret? Should I use one or two different tokens for this purpose?
Does Okta provides per-user client Id/secret that user(customer) can use to get access_token and send it to access resource server and resource server validate token against Okta.
I just did something very similar. You can read about my experience here: How to pass/verify Open ID token between .net core web app and web api?
I don't know what application framework you are using (.net, node, etc), but if you're using .NET the steps are to (a) install the middleware in your web app, (b) install the middleware in your api app, and (c) make sure calls from your web app to the api app pass the id_token.
If you, in addition to that, need to secure it for external users - it should work the same way. The only difference is they will manually call the /authorize endpoint to get their token - but the middleware should take care of the token verification for you in both cases.
Note I did experience one odd thing which is that I needed to pass the id_token and not the access_token. It is also worth mentioning that the claims were interpreted differently in the app and the api (in that the name of the claims for say, userid, were different between them - the data was still the same).
You will have to use 2 different access tokens. There are 2 different flows going on here:
Web UI to API
Business partner system to API
Technically this means:
Authorization Code Flow (PKCE)
Client Credentials Flow
And in terms of tokens it means:
In the first case there is an end user represented in access tokens (the 'sub' claim)
In the second case there is only a Client Id claim in access tokens
I can advise on token validation techniques if needed - let me know.
To me though this feels like an architectural question - in particular around applying authorization after identifying the caller and versioning / upgrades.
Based on my experience I tend to prefer the following architecture these days, based on 2 levels of APIs: eg with these ones exposed to the internet:
User Experience API serves the UI
Partner API deals with B2B
And both entry point APIs call the same core services which are internal. Might be worth discussing with your stakeholders ..

ASP .NET Core Identity default authentication vs JWT authentication

I am developing ASP NET Core Web API and I am confused by choosing the authentication method. I used to apply default Asp Net Identity authentication, but recently I've known about JWT. So I've implemented Authentication almost as it done in this article: https://stormpath.com/blog/token-authentication-asp-net-core.
But I can't understand the benefits of this JWT. With simple Asp Net Identity Authentication, I don't care about token storage etc. I only need to log in with signInManager and use authorized methods until logout. With JWT I need to think about the token store, expiration, and other difficulties. So, what're the benefits of this JWT? How can I store this JWT token after login? Furthermore, should I even use this JWT? In my case, I need simple authentication for simple WebApi which will be used by one or little bit more users. I've also heard about OpenIddict, Auth0, IdentityServer, so what's the difference between all of these authentication mechanisms?
This is the way I understand this, split in to 3 logical parts.
Authentication Server - this will authenticate and issue the JWT token, when the API need's to validate the token it will send the token to this server to validate it.
Client - this is what serves your web pages, or you app perhaps. This is what will need to request and store the the JWT token. The client will need to pass the token to the api every time it requests data.
API - this is what serves the information and needs to validate the token with the Authentication Server.
So, what're the benefits of this JWT?
JWT is issued to the client and stored on the client side. Having JWT allows multiple client's (App's or Websites) use the same authentication server which distributes JWT and states which API's the client's can use and how.
How can I store this JWT token after login?
I only tried to store it in an Ionic 2 app which uses angular 2 which has a storage module. But i'm pretty sure numerous people have done this already and asked this question:
Simple JWT authentication in ASP.NET Core 1.0 Web API
Token Based Authentication in ASP.NET Core (refreshed)
Update
If your front end is made purely html/js/css and doesn't have a back end to accommodate it you would store your token in local storage, there a multiple npm packages that help you with this like this one. You want to look for Implicit flow.
Otherwise if you do have a back end that comes with your front end you want to store the token in a session/database your pick, there are 3rd party providers to do this like IdentityServer4. You want to use Hybrid flow
Furthermore, should I even use this JWT? In my case, I need simple
authentication for simple WebApi which will be used by one or little
bit more users.
The reason for the whole separation of concerns is performance so you don't really need it since it's just one or a little more users. Do it because it's a learning experience, JWT is not easy to setup from the beginning and will require you to do a lot of reading and you will fail and you will be frustrated but at the end you will know how to set it up and how it works
I've also heard about OpenIddict, Auth0, IdentityServer, so what's the difference between all of these authentication mechanisms?
So what you did in the Stormpath tutorial is NOT production ready. That is just a little demo, to help you understand what JWT is and how it works. The above mentioned are complete libraries that tackle all the heavy lifting and do not require you to built the whole thing from scratch. And the main difference between them is the scope that they cover.
I personally used IS4 and it had me crying no more than 2 times (It was simpler than I thought):
http://identityserver4.readthedocs.io/en/release/
https://github.com/openiddict/openiddict-core
https://auth0.com/docs/quickstart/webapp/aspnet-core/00-intro
Use tokens (JWT) if you have multiple applications or services (web, mobile, other services) connection to your API. Benefits: Stateless, Scalability, No cookie, no CORS problems (if you allow it).
If your API will be used by only one web application use the default ASP default authentication system. Its easier to set up.
If you webapi and user interface are hosted in the same web application, token bases security does not buy you anything over the cookie based authentication provided by the built in authentication. That's because the authentication cookie gets sent back to the keep application on every HTTP request. When you make calls to a website other than the one you signed in on those cookies do not get sent. So JSON Web Tokens (JWT) provide a standard format for browser to send identity information to a website when a cookie isn't an option.
If your Web Api is to be accessed by AJAX calls then JWT may be a desired choice, but not mandatory. judging by the description of your app,it seems to me that the default authentication system can serve you well.
Auth2 is the authentication mechanism that enable external login such as Facebook. It is part of the default authentication system, and you need not do much in order to employ it in your app.
OpenIddict sits on top of Auth2. It is part of the default authentication system, and you need not do much in order to employ it in your app. It is the authentication mechanism that enable external login such as Google+
IdentityServer may be used for large Wep Api that is accessed by Ajax calls. As for instance, you can use IdentityServer to authenticate users longing to a front end Angular app.
Once again, the default authentication system can serve you well.
Hope this helps...

Using IdentityServer vs creating custom JWT based authentication

Authentication is a bit over the top for me.
My understanding is:
Client performs the login
API or authentication server responds with a token
Client calls API (includes a header which holds the token)
API checks if the token is valid and if valid responds with a resource
I checked several options:
IdentityServer4
Has the advantage to easily implement 3rd party authentication like Facebook. You can easily use the ASP.NET Core identities to authorize your API based on roles.
Custom (simple) JWT authentication
Reference: ASP.NET Core Token Authentication Guide
With this approach, you have to make your own identity user and fetch it from a database.
Cookie authentication
The client holds the token in a cookie when sending a request you have to send it too.
My front-end is written in JS and back-end is ASP.NET Core, so it's CORS.
I don't know what should I use and why? Why do many recommend to use IdentityServer4; isn't the simple custom authentication enough?
(I have problems with the IdentityUser properties and the "hidden" database checks)
The problem with authentication is that it may be simple to write a few lines of code that accomplish the end goal of authenticating your users, but it's really complex to do so in a way that you won't regret it later; aka my application got owned.
One of the steps to take to try to prevent that from happening is don't try to reinvent the wheel and stick to using current standards. However, even with standards, you need to implement them accordingly and that is why you probably see recommendations like the one you mentioned. I would actually make the same type of recommendation my self, delegate as much as you can to third-party libraries like IdentityServer4 or cloud services like Auth0. (you should know I work at Auth0, so you can consider me biased; however, for a non-biased recommendation you can check ThoughtWorks Technology Radar).
Also, if you store tokens in cookies, although the storage and transmission of the token happen differently this is still a token based-authentication system; for more on the possible implications of choosing a client-side token storage approach check where to save a JWT in a browser-based application.
In relation to CORS, you did not make that explicit, so I thought it may be worthwhile to mention it. You only need to actually worry about CORS if you deploy your front-end and back-end in separate domains because even if development happens in isolation if they share a domain CORS is one less thing you need to worry about.
Conclusion
For a front-end browser-based application talking with a REST API, the most common approach is to go with token-based authentication that relies on OAuth 2.0 protocol to perform the actual issuance of the tokens. Additionally, you should aim to delegate token issuance to a third-party (IdentityServer4 or other) so that you don't need to implement or maintain that part of the system and only need to consume/validate the generated tokens.

Microservice Authentication strategy

I'm having a hard time choosing a decent/secure authentication strategy for a microservice architecture. The only SO post I found on the topic is this one: Single Sign-On in Microservice Architecture
My idea here is to have in each service (eg. authentication, messaging, notification, profile etc.) a unique reference to each user (quite logically then his user_id) and the possibility to get the current user's id if logged in.
From my researches, I see there are two possible strategies:
1. Shared architecture
In this strategy, the authentication app is one service among other. But each service must be able to make the conversion session_id => user_id so it must be dead simple. That's why I thought of Redis, that would store the key:value session_id:user_id.
2. Firewall architecture
In this strategy, session storage doesn't really matter, as it is only handled by the authenticating app. Then the user_id can be forwarded to other services. I thought of Rails + Devise (+ Redis or mem-cached, or cookie storage, etc.) but there are tons of possibilities. The only thing that matter is that Service X will never need to authenticate the user.
How do those two solutions compare in terms of:
security
robustness
scalability
ease of use
Or maybe you would suggest another solution I haven't mentioned in here?
I like the solution #1 better but haven't found much default implementation that would secure me in the fact that I'm going in the right direction.
Based on what I understand, a good way to resolve it is by using the OAuth 2 protocol (you can find a little more information about it on http://oauth.net/2/)
When your user logs into your application they will get a token and with this token they will be able to send to other services to identify them in the request.
Example of Chained Microservice Design
Resources:
http://presos.dsyer.com/decks/microservice-security.html
https://github.com/intridea/oauth2
https://spring.io/guides/tutorials/spring-security-and-angular-js/
Short answer : Use Oauth2.0 kind token based authentication, which can be used in any type of applications like a webapp or mobile app. The sequence of steps involved for a web application would be then to
authenticate against ID provider
keep the access token in cookie
access the pages in webapp
call the services
Diagram below depicts the components which would be needed. Such an architecture separating the web and data apis will give a good scalability, resilience and stability
You can avoid storing session info in the backend by using JWT tokens.
Here's how it could look like using OAuth 2.0 & OpenID Connect. I'm also adding username & password login to the answer as I assume most people add it as a login option too.
Here are the suggested components of the solution:
Account-service: a microservice responsible for user creation & authentication. can have endpoints for Google, Facebook and/or regular username & password authentication endpoints - login, register.
On register - meaning via register endpoint or first google/fb login, we can store info about the user in the DB.
After the user successfully logs in using either of the options, on the server side we create a JWT token with relevant user data, like userID. To avoid tampering, we sign it using a token secret we define(that's a string).
This token should be returned as httpOnly cookie alongside the login response. It is recommended that it's https only too for security. This token would be the ID token, with regards to the OpenID connect specification.
Client side web application: receives the signed JWT as httpOnly cookie, which means this data is not accessible to javascript code, and is recommended from a security standpoint. When sending subsequent requests to the server or to other microservices, we attach the cookie to the request(in axios it would mean to use withCredentials: true).
Microservices that need to authenticate the user by the token:
These services verify the signature of the JWT token, and read it using the same secret provided to sign the token. then they can access the data stored on the token, like the userID, and fetch the DB for additional info about the user, or do whichever other logic. Note - this is not intended for use as authorization, but for authentication. for that, we have refresh token & access token, which are out of scope of the question.
I have recently created a detailed guide specifically about this subject, in case it helps someone: https://www.aspecto.io/blog/microservices-authentication-strategies-theory-to-practice/
One more architecture perspective is to use nuget-package (library) which actually do authentication/token validaton. Nuget-package will be consumed by each microservice.
One more benefit is that there is no code duplication.
you can use idenitty server 4 for authentication and authorisation purpose
you must use Firewall Architecture hence you have more control over secutiry , robustness ,scalability and ease of use