Search code examples
c#asp.net-web-apiasp.net-identity

how to manually assign a Token to a user context in WebApi


I'm trying to write my own Authorize filter to handle Token-Based authentications. [For some reasons i don't want to implement ASP.Net Identity authentication system]

I want to assign my own Generated token to a user context in WebApi.

something like what the ASP.net Identity does.

how can i do this manually ?

thanks.


Solution

  • you can do this by creating your own custom token provider class.

    public class AccessTokenProvider : Microsoft.Owin.Security.Infrastructure.AuthenticationTokenProvider
    {
        public override void Create(AuthenticationTokenCreateContext context)
        {
            context.SetToken("yourtoken");
            base.Create(context);
        }
    }
    

    and setup your authorization option in owin startup class as below.

    OAuthServerOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/api/token"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        AllowInsecureHttp = true,
        AccessTokenProvider = new AccessTokenProvider()
    };
    
    app.UseOAuthAuthorizationServer(OAuthServerOptions);