OpenID Connect Hybrid Flow for calling resource API (OIDC Part 4)

Share on facebook
Share on google
Share on twitter
Share on linkedin

In the last post we created an authorization code client, enabling the client to get the user claims from the id token, exchanged for the post-login authorization code. That way we were able to display the user roles on an authorized MVC view. This time, instead of getting the user roles from the userInfo endpoint directly with an access token from AppClient, we are going to get it from the resource API, using an access token.

Note: This could also have been implemented with authentication code client since we are only using an MVC client in this part. Using the hybrid client here is just for learning purpose, enabling you later to use the hybrid client both from a browser and an MVC app simultaneously.

The OpenID connect with IdentityServer4 and Angular series

This series is learning you OpenID connect with Angular with these parts:

AuthorizationServer – Setting up the hybrid client

Compared to part 3 of the OIDC series, the only thing we need to do to the AuthorizationServer is to add a hybrid client:

// OpenID Connect hybrid flow client (MVC) new Client { ClientId = "mvc", ClientName = "MVC
Client", AllowedGrantTypes = GrantTypes.Hybrid,
ClientSecrets =
    new Secret("secret".Sha256())

RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes =
AllowOfflineAccess = true

The only difference between this and the previous authorization code client is that browsers are here allowed to get the id token on first roundtrip. We could also get the access token on the first roundtrip if we enabled that here. With authorization code flow, they needed to exchange their authorization code for an id token.

ClientApp – Calling the resource API with access token

In part 3 we already set the AppClient up for using hybrid flow by adding the ClientSecret in the Startup authentication middleware. The only difference is here we are requesting the id_token as well as the authorization code on first request:

ClientApp/Startup.cs options.ResponseType = "code id_token";

After the user has been authenticated, the HTTPContext is going to contain an access token as well as the id token. We use this in a method for calling the resource API’s authenticated identity endpoint:

 private async Task CallApiUsingUserAccessToken() { 
    var accessToken = await HttpContext.GetTokenAsync("access_token");

var client = new HttpClient();

return await client.GetAsync("http://localhost:5001/api/identity");

This gets the access_token from the HttpContext, which is provided by the authentication cookie that got set on successful user authentication. After that, the access token is set and send as a bearer token. This method is used by the IdentityController.Index action:

[Authorize] public async Task Index() { 
var userClaimsVM = new UserClaimsVM(); var userClaimsWithClientCredentials = await
userClaimsVM.UserClaimsWithClientCredentials =
userClaimsWithClientCredentials.IsSuccessStatusCode ? await
userClaimsWithClientCredentials.Content.ReadAsStringAsync() :

var userClaimsWithAccessToken = await CallApiUsingUserAccessToken();
userClaimsVM.UserClaimsWithAccessToken = userClaimsWithAccessToken.IsSuccessStatusCode ? await userClaimsWithAccessToken.Content.ReadAsStringAsync() : userClaimsWithAccessToken.StatusCode.ToString();

return View(userClaimsVM);

The user claims from the resource are stored in the userClaimsVM and the Identity/Index.cshtml should now look like this:

@model ClientApp.Models.UserClaimsVM;
    ViewData["Title"] = "Index";



User claims:
    @foreach (var claim in User.Claims)

<form asp-controller="Identity" asp-action="Logout" method="post">
    <button type="submit">Logout</button>

Now the view is also showing user claims from the resource API using access token.

No change is needed for the resource api, so we are now ready to run the servers together.

Running the app

When running the three servers all together we should be able to get an access token using the: HttpContext.GetTokenAsync("access_token").

By going to, this JWT can easily be decoded.

OpenId access token

We see that the scope is containing resourceApi as well as the audience property, allowing the user to access the ResourceApi.

When going to http://localhost:5002/identity we should now be prompted for login and consent for which we are gonna use one of the hard coded test users. Here after we are gonna be redirected to our identity view, now containing the user claims, fetched from the ResourceAPI:


That sums up part 4! We accomplished to setup an hybrid flow client in the Authorization Server that can return both a authorization code as well as id token and access token, if requested. Using this we obtained an access token containing the resource api as scope, which enabled our ClientApp to fetch and display authorized identity information by requesting the resource API.

Next time we are gonna make the setup more realistic by enabling user registration using ASP.NET identity.
The code for this part can be found on my Github.

Do you want to become an Angular architect? Check out Angular Architect Accelerator.

Related Posts and Comments

How to Handle Errors in a Reactive Angular App

In this post, we will cover how to handle errors in a reactive Angular app. To provide a good user experience you should always let your users know what state your application is in. That includes showing a loading spinner when it’s loading and showing error messages if there are any errors. It is a

Read More »

How to Set Up Git Hooks in an Nx Repo

Git hooks can be used to automate tasks in your development workflow. The earlier a bug is discovered, the cheaper it is to fix (and the less impact it has). Therefore it can be helpful to run tasks such as linting, formatting, and tests when you are e.g. committing and pushing your code, so any

Read More »

The Stages of an Angular Architecture with Nx

Long gone are the times when the frontend was just a dumb static website. Frontend apps have gotten increasingly complex since the rise of single-page application frameworks like Angular. It comes with the price of increased complexity and the ever-changing frontend landscape requires you to have an architecture that allows you to scale and adapt

Read More »

The Best Way to Use Signals in Angular Apps

Since Angular 16, Angular now has experimental support for signals and there is a lot of confusion in the community about whether this is going to replace RxJS or how it should be used in an app in combination with RxJS. This blog post sheds some light on what I think is the best way

Read More »

High ROI Testing with Cypress Component Testing

Testing is one of the most struggled topics in Angular development and many developers are either giving up testing altogether or applying inefficient testing practices consuming all their precious time while giving few results in return. This blog post will change all this as we will cover how I overcame these struggles the hard way

Read More »