Question

I am building a web.api service which uses token for authorization. I've followed the guidelines used by Dominick Baier in his blog here.

Today I've updated all the packages for Owin, Entity Framework and ASP.NET web.api and I've found out that lots of things have changed.

I've found a few articles on the web (apparently there no documentation about these topics) and started to convert my web.api service.

This post about the new ASP.NET Identity 2.0.0 helped me to convert pretty much everything but now I am stuck on a simple stupid matter.

I've managed to create my customer ApplicationUserManager and ApplicationDbContext as suggested in the blog.

In my Startup I've associated my 2 object with the Owin Context:

app.CreatePerOwinContext<ApplicationDatabaseContext>(ApplicationDatabaseContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

I have defined a custom OAuthAuthorizationServerProvider cause I want to use Bearer Authentication:

var OAuthOptions = new OAuthAuthorizationServerOptions
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/oauth/Token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
    Provider = new MyAuthorizationServerProvider(),
    RefreshTokenProvider = new MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8))
};

In my MyAuthorizationServerProvider I have overidden ValidateClientAuthentication cause I want to check client credentials.

Everything seems to work fine and I can get my IAuthenticationManager from OwinContext :

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    string clientId = string.Empty;
    string clientSecret = string.Empty;

    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
    {
        IAuthenticationManager manager = context.OwinContext.Authentication;
        ...
        ...
    }
}

but I don't seem to be able to get my ApplicationDbContext. The only way I can achieve this is using the key which I've found going through the variables registered:

var dbContext = context.OwinContext.Get<ApplicationDbContext>("AspNet.Identity.Owin:OwinWebApiSecurity.Services.ApplicationDatabaseContext, OwinWebApiSecurity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

I was wondering if there a simpler way to achieve the same thing.

Was it helpful?

Solution

Apparently I have to import Microsoft.AspNet.Identity.Owin namespace to have access to those extension methods.

ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top