MI2
MI2

Reputation: 21

ASP.NET Identity - Generating a token

I would like generate a token during registration within WEB APIs. I’m new to ASP.NET Identity, I have grabbed all the out of the box APIs which are published by ASP.NET Identity, but don’t see any API to generate a token. I’m writing a set of WEB APIs and the consumer of these APIs is are going to a mobile app and web based portals. Please Help.

Upvotes: 2

Views: 5587

Answers (1)

Horizon_Net
Horizon_Net

Reputation: 5979

What you are looking for is the token endpoint, which you can add in the configuration of the authentication:

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    AllowInsecureHttp = true
};

When sending a POST request with the username and the password against this endpoint you'll get back a bearer token which you can use in your mobile applications:

static string GetToken(string userName, string password)
{
    var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
    var content = new FormUrlEncodedContent(pairs);
    using (var client = new HttpClient())
    {
        var response = client.PostAsync("http://localhost:62069/Token", content).Result;
        return response.Content.ReadAsStringAsync().Result;
    }
}

John Atten has written a nice tutorial about it. There you will also find the appropriate code snippets.

You can customize it as you want, for example setting custom expiration of the token and the usage of refresh tokens.

Upvotes: 3

Related Questions