I'm trying to implement Identity Server 4 with AspNet Core using Authorization Code Flow.
The thing is, the IdentityServer4 repository on github have several samples, but none with Authorization Code Flow.
Does anyone have a sample on how to implement Authorization Code Flow with Identity Server 4 and a Client in MVC consuming it?
Here's an implementation of an Authorization Code Flow with Identity Server 4 and an MVC client to consume it.
IdentityServer4 can use a client.cs file to register our MVC client, it's ClientId, ClientSecret, allowed grant types (Authorization Code in this case), and the RedirectUri of our client:
This class is referenced in the ConfigurationServices method of the Startup.cs in the IdentityServer4 project:
For reference, here are the Users and Scopes classes referenced above:
The MVC application requires two controller methods. The first method kicks-off the Service Provider (SP-Initiated) workflow. It creates a State value, saves it in cookie-based authentication middleware, and then redirects the browser to the IdentityProvider (IdP) - our IdentityServer4 project in this case.
For reference, here are the constants and SaveState method utilized above:
The second MVC action method is called by IdenityServer4 after the user enters their credentials and checks any authorization boxes. The action method:
Here's the method:
Checking that the State received is what you expected helps defend against CSRF attacks: http://www.twobotechnologies.com/blog/2014/02/importance-of-state-in-oauth2.html
This ValidateStateAsync method compares the received State to what was saved off in the cookie middleware:
This ValidateToken method uses Microsoft's System.IdentityModel and System.IdentityModel.Tokens.Jwt libraries to check that JWT is properly signed.
A working solution containing these source files resides on GitHub at https://github.com/bayardw/IdentityServer4.Authorization.Code
Here's a sample - it is using hybrid flow instead of code flow. But hybrid flow is more recommended anyways if you client library supports it (and the aspnetcore middleware does).
https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/5_HybridFlowAuthenticationWithApiAccess