Authorization Code Flow and PKCE example using OpenIddict - asp.net-core

I stumbled upon OpenIddict and after going through a few example server code, I could not find what I was looking for. I was hoping to see an example of OpenIddict using auth code flow with PKCE, since that seems to be the recommended approach toward security now, but could not find one using both explicitly. My app is a ASP.NET Core WebAPI based app, with a React client. Any help or guidance would be appreciated.

PKCE in OpenIddict works like in any other OIDC server: you just have to send a code_challenge (and optionally a code_challenge_method) when building your authorization request.
If you do that, OpenIddict will store it in the authorization code ticket and will compare it to the code_verifier you send as part of the token request. If you don't send a code verifier, the token request will be automatically rejected.
In 3.0, we'll introduce an option allowing to reject authorization requests that don't use PKCE so that you can force your clients to use PKCE.

Related

Asp.Net Core API OpenId-Connect authentication with JWT token using IdentityModel

I have an ASP.NET Core API as back-end for an Angular SPA front-end. I am using Cognito as an Identity provider and want to create an OpenId-Connect authentication using authorization code flow which would mean that all the secret credentials will be stored in back-end.
The authorization flow should be like this (standard OpenID Connect flow):
FE application calls /authorize endpoint and is redirected to Cognito hosted UI.
After entering credentials FE receives an authorization code.
FE calls BE with authorization code.
BE calls /token endpoint and receives accessToken and refreshToken.
BE Returns accessToken to FE and sets refreshToken as httpOnly cookie(for this not sure, I may store it in Redis cache).
Then, FE with each request will add Bearer AccessToken to authenticate. When AccessToken is close to expiration, it will be updated using refreshToken.
I was experimenting with this example but here application used an Asp.Net Core cookie for authentication and ignored accessToken and refreshToken. I was authenticated even after accessToken was expired. Also, there's not much documentation on how ASP.NET cookie works.
So, now I am thinking about having my custom BE endpoints and use IdentityModel helper methods but not sure if it is a good practice to handle authentication like this.
/Login - gets AccessToken and RefreshToken
/Refresh - updates AccessToken using RefreshToken. FE will call it manually when accessToken will be close to expiration.
So, is there a "recommended" way to handle this scenario nicely with IdentityModel without writing custom implementation?
Also, as far as I know, it is quite common to store refreshToken in httpOnly cookie which will be added to each request sent to BE but then I don't see the point of having an accessToken when I already have refreshToken added with each request.
Isn't it better to store refreshToken inside BE for performance and security reasons?
Authentication is a part of every application so I believe there should be some in-built framework functionality for authorization code flow as well.
You are describing a Backend for Frontend approach, which is a good architecture. Make sure you separate the specialist API that deals with OAuth from general business APIs.
RECOMMENDED WAY
Curity have an approach that provides state-of-the-art security for SPAs, here are some links:
Token Handler Blog Post
Code Example
Code Example Doc
We may add a .Net token handler at some point, but it should not matter what tech is used, since the idea is for the specialist API to be something you plug in rather than code.
STORING REFRESH TOKENS
My personal preference for SPAs is to use AES256 encrypted HTTP only cookies. This fits nicely with goals of avoiding OAuth plumbing in applications and enables the token handler to be stateless and easier to deploy + manage.

Consume JWT token in asp.net core web application

In one of my project need to consume JWT token from asp.net core web application. My trial project is on github https://github.com/SapanPatibandha/JWTAuthentication
This has one server JWTAuthentication which is generating jwt token base on username and password.
Second component is AnyAPI which method is protected by self verification of JWT.
Third important part and where I have problem is Web application.
Need to create login screen in this application, base on this user detail call login api from JWTAuthentication and use that token for all further use of api from that web application.
I am not sure about middleware configuration and how to store this token on web application.
Thanks
IMO, What you asking for is a journey that need some investigating time, that's not what could be answered shortly, so... I'm gonna make this as compact as possible
What you're doing in the repo is hand-generate and validate Jwt Token. If that's required, investigate these stuff:
Generating Jwt on central identity provider server (which you currently have)
Validate Jwt on api resource (which you currently comment that out)
On application(seems like you make use of classic MVC or razor page), create login form that use ajax to get Jwt from identity provider server, store it on client side (browser), then attach it with every request that make use of AnyAPI, by cookie or header or something you saw reasonable. Or if you choose to save the token on Server side, implement your own session-Jwt mapping logic(Actually, some kind of Js SPA would be more suitable for this kind of approach).
Another approach would be implement a more proper Oauth implementation. I consider 2 most widely acknowledged in .net ecosystem would be Identity Server and OpenIdDict. Highly recommend to check them out.

How to manage a JWT login procedure from Micronaut client to a REST API?

I am new to Micronaut and trying to develop a gateway that connects on the client side to a REST API. The API requires an authentication token which is obtained by first sending a POST requests with credentials in the body. The API is then responding with a valid token which needs to be refreshed from time to time. I am able to inject a bearer token in the headers to authenticate my requests but I do not understand whether I have to handle the whole authentification process myself or if the Micronaut framework can manage it on its own?
Thank you very much for your help.
You could create an HttpClientFilter to handle authentication, refresh and the header. You can find an example here which cover basic authentication.
Yours will be more complicated since you need to refresh etc.
Also doing this way, allow you to decouple your authentication code from your API.

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...

JWT authentication in SignalR (.NET Core) without passing token in Query String

I am using JWT authentication tokens in an ASP .NET Core Web API application. The tokens are generated by the API itself, not by a third party.
I added SignalR sucessfully to the stack, but now I need to authenticate the users that are trying to execute server (Hub) methods.
Someone suggested to pass the token in the "qs" property in JavaScript. This will not work for me as our tokens are really large (they contain lots of claims).
I tried writing a custom middleware for reading the token from the payload and auto-authenticating the user. The problem is that, when using WebSockets, the middleware is not executed.
Any ideas will help.
Have a look at article that suggests to use query string Authenticate against a ASP.NET Core 1.0 (vNext) SignalR application using JWT. I know that your token is too long, but author explains how to use middleware to authenticate the request.
Here is the summary from the article:
SignalR does not have any special authentication mechanism built in, it is using the standard ASP.NET authentication.
JWT is typically sent in the Authorization header of a request
The SignalR JavaScript client library does not include the means to send headers in the requests, it does however allow you to pass a query string
If we pass the token in the query string we can write a middleware that adds a authorization header with the token as its value. This must be done before the Jwt middleware in the pipeline
Be aware of the “Bearer ” format
I have highlighted the key point that your custom middleware should be registered before Jwt middleware.
From this answer you can create a WebSocket connection and pass your token as basic auth parameter:
var ws = new WebSocket($"ws://{token}#example.com/service");