Home > front end >  How to get the id_token outside a controller in Asp.net Core MVC?
How to get the id_token outside a controller in Asp.net Core MVC?

Time:02-18

How can I get the id_token returned by OpenIdConnect provider outside of a controller.

Inside the controller, this gives me the token:

string idToken = await HttpContext.GetTokenAsync("id_token");

I need to get the token inside a service in a similar fashion. How can I do this?

P.S: I have already tried to use HttpContextAccessor but it does not return anything.

CodePudding user response:

Using Session to store data/value, which can be used in different place within your project.

//store vaule
Session["idToken"] = await HttpContext.GetTokenAsync("id_token");

//Call session 
var x = Session["idToken"];

//empty or clean Session value
Session["idToken"] = null;

CodePudding user response:

It seems GetTokenAsync() is an extension method to the httpContext. If this is true, then you could add the HttpContextAccessor in your startup / top level program.cs (depending if you are on .net 5 or 6)

builder.Services.AddHttpContextAccessor();
//or
services.AddHttpContext();

Then in your class, you can go the well known DI route:

public class MyService : IMyService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyService(IHttpContextAccessor httpContextAccessor) =>
        _httpContextAccessor = httpContextAccessor;

    public async Task DoSomething() {
       var idtoken = await _httpContextAccessor.HttpContext.GetTokenAsync("id_token");
    }
}

Documentation: https://docs.microsoft.com/de-de/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0

  • Related