Michael Esteves
Michael Esteves

Reputation: 1485

Adding bearer token to dependency injection

I have identity server 4 setup and my mvc client redirects to identity server and I can authenticate the user.

Now if I want to call me API I can do the following. However I have to pass the access token into the method that calls my api.

Controller

public class UserController : Controller
{
    public IActionResult Index()
    {
        var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");

        var user = _userService.Get(accessToken);
        return View();
    }
}

Service

public async Task<User> Get(string accessToken)
{
    var result =  await _baseUrl.AppendPathSegment("/v1/User/Get").WithOAuthBearerToken(accessToken).GetJsonAsync<User>();

    return result;
}

What I would prefer to do is add the access token to the dependency injection pipeline so that I can use it as a global in the class and not have to worry about passing it around with every call.

public class UserService
{
    private readonly string _bearerToken {get;set;}

    public UserService(IOptions<UserSettings> userSettings)
    {
        _bearerToken  = userSettings.Value.BearerToken;
    }

    public async Task<User> Get(string accessToken)
    {
        var result =  await _baseUrl.AppendPathSegment("/v1/User/Get").WithOAuthBearerToken(_bearerToken ).GetJsonAsync<User>();

        return result;
    }
}

I'm not entirely sure if this is the right way of doing it? If it is then I'm not sure how. I thought maybe as part of the OnTokenValidated event.

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    // Other settings here

    Events = new OpenIdConnectEvents
    {
        OnTokenValidated = context =>
        {
            var accessToken = context.SecurityToken as JwtSecurityToken;

            if (accessToken != null)
            {
                // Over here add the accessToken to IOptions<UserSettings>
            }

            return Task.CompletedTask;
         }
   },
}

Is the OnTokenValidated event the right place to do it? Would that maintain the token between page loads or is there some other place I should be doing this? How would I go about adding the accessToken into IOptions or something equivalent?

Thanks

M

Upvotes: 0

Views: 2458

Answers (1)

Michael Esteves
Michael Esteves

Reputation: 1485

After some more investigating I found a way to do it. Using this answer here

using simple injector in mvc6 with cookie auth

and looking how

https://github.com/dotnet-architecture/eShopOnContainers

did it I created an ITokenManager and an TokenManager and then had access to IHttpContextAccessor through DI which allows me to get the token.

Upvotes: 1

Related Questions