我也掙扎尋找如何剛剛生成令牌的部分文章。我從來沒有找到一個,寫我自己的。所以,如果它有助於:
做的事情是:
- 創建一個新的Web應用程序
- 安裝以下的NuGet包:
Microsoft.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.Identity.Owin
- 添加OWIN
startup
類
然後創建一個HTML和JavaScript的(index.js
)與這些文件內容:
var loginData = 'grant_type=password&[email protected]&password=test123';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "/token", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(loginData);
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
的OWIN startup
類應該有這個內容:
using System;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using OAuth20;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace OAuth20
{
public class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
OAuthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/token"),
Provider = new OAuthAuthorizationServerProvider()
{
OnValidateClientAuthentication = async (context) =>
{
context.Validated();
},
OnGrantResourceOwnerCredentials = async (context) =>
{
if (context.UserName == "[email protected]" && context.Password == "test123")
{
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
context.Validated(oAuthIdentity);
}
}
},
AllowInsecureHttp = true,
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)
};
app.UseOAuthBearerTokens(OAuthOptions);
}
}
}
運行您的項目。令牌應顯示在彈出窗口中。
http://leastprivilege.com/2013/11/13/embedding-a-simple-usernamepassword-authorization-server-in-web-api-v2/ – pomber 2015-05-04 02:12:01