Search code examples
asp.net-identityasp.net-identity-2

Trade external access token for local one - ASP.Net Identity


When using ASP.Net Identity and retrieving an external access token from an external provider, how do I then trade-in/issue a local access token using the external access token?

I've seen [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] but have not been able to get it working on my action method. If I send with headers

 Authentication: Bearer external_access_token   

It does not populate the User.Identity

Startup.Auth.cs:

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(),
        AuthorizeEndpointPath = new PathString("/AccountApi/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    });
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

Solution

  • The workflow of OWIN Middleware External Authentication involves

    • Redirecting / querying External OAuth Provider
    • Registering new user with ASP.NET Identity using the External Cookie and all claims information
    • Returning a Bearer Token to the Presentation Layer.

    The [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] is not used to allow External Bearer Tokens to be used in-place of local authority Bearer Tokens. External Bearer Tokens are only used to Authenticate the user's Identity.

    OWIN Middleware Authentication should always conclude with an OWIN Middleware Bearer Token returned to the user. Whether the User Authenticates with a local Login/Password or with External Authentication Cookie / Token, the user must get a local authority Token to make use of Secure Methods.

    If the user does not exist in your Identity Database after External Authentication, Register the user and return a new Bearer Token.