2015-01-15 152 views
2

我想在WEB API中注册期间生成令牌。我是ASP.NET Identity的新手,我抓住了所有由ASP.NET Identity发布的开箱API,但没有看到任何API来生成令牌。我正在编写一组WEB API,这些API的使用者正在转向移动应用程序和基于Web的门户。 请帮助。ASP.NET身份 - 生成令牌

回答

2

你所寻找的是令牌端点,您可以在认证的配置中添加:

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

当发送带有用户名与此终结,你会得到一个POST请求和密码回到你可以在你的移动应用程序使用的承载令牌:

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; 
    } 
} 

约翰安泰信写了nice tutorial了。在那里您还可以找到适当的代码片段。

您可以自定义它,例如设置令牌的自定义过期和刷新令牌的使用。