0

I have mvc client application which uses identity server 4 using cookie authentication.

Below is my Config:

 services.AddAuthentication(options =>
      {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })

Http Client Method:

public async Task<IList<MenuModel>> GetMenusNavAsync()
                    {
                        var response = await _httpClient.GetAsync("api/Menu/GetMenusNavBar");
                         response.EnsureSuccessStatusCode();
                        using var responseContent = await response.Content.ReadAsStreamAsync();
                       return await JsonSerializer.DeserializeAsync<List<MenuModel>>(responseContent);
                   }

Now i need to send access token to api controller inside http client. How to get the access token from Identity server or Coockie. Pls suggest..Thanks in advance

Ajt
  • 1,719
  • 1
  • 20
  • 42

1 Answers1

1

Once you are logged-in, on MVC app, you can use HttpContext.GetTokenAsync extension to get the authentication tokens in the session. This is a standard ASP.NET Core extension method on Microsoft.AspNetCore.Authentication namespace.

the code would look like:

public async Task<IList<MenuModel>> GetMenusNavAsync()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            var response = await _httpClient.GetAsync("api/Menu/GetMenusNavBar");
            response.EnsureSuccessStatusCode();
            using var responseContent = await response.Content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<List<MenuModel>>(responseContent);
        }

Find a complete sample here

nahidf
  • 2,260
  • 1
  • 15
  • 22
  • Thank you ..Actually i already gt the ansewer.. Pls let me know how to authorization works in mvc controller? if i put just [Authorize(Roles = "Administrator")] is enough? – Ajt May 20 '20 at 02:43
  • 2
    For authorization you can just simply add [Authorize] attribute on the action. But if you are looking for role based authorization, need to add role claim to the access token first, [here](https://stackoverflow.com/questions/40844310/role-based-authorization-with-identityserver4) is a good post about it. – nahidf May 20 '20 at 03:17
  • Is it possible to add this as part of a delegating handler? – Narshe Aug 11 '22 at 11:15