在过去的 1 天里,我正在尝试为基于 api 的项目设置基于令牌的身份验证。
使用以下链接作为起点。
http://www.c-sharpcorner.com/UploadFile/736ca4/token-based-authentication-in-web-api-2/
但我有点困惑并出现错误。
Startup.cs(位于类库项目中)
public class Startup
{
public void Configuration(IAppBuilder app)
{
var oauthProvider = new OAuthAuthorizationServerProvider
{
OnGrantResourceOwnerCredentials = async context =>
{
var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
claimsIdentity.AddClaim(new Claim("user", context.UserName));
context.Validated(claimsIdentity);
return;
//context.Rejected();
},
OnValidateClientAuthentication = async context =>
{
string clientId;
string clientSecret;
if(context.TryGetBasicCredentials(out clientId, out clientSecret))
{
if(clientId == context.ClientId && clientSecret == "secretKey")
{
context.Validated();
}
}
}
};
var oauthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/accesstoken"),
Provider = oauthProvider,
AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3),
SystemClock = new SystemClock()
};
app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
}
API 控制器
[AcceptVerbs("POST")]
[HttpPost]
public string Post([FromBody]User user)
{
if(user.Username == "chetan" && user.Password == "pwd")
{
HttpClient client = new HttpClient();
OAuth.InitOAuth(client, user.Username, user.Password);
return "Success!!User valid for token";
}
else
{
return "Error!! User invalid";
}
}
我的 OAuth 课程
public class OAuth
{
public static void InitOAuth(HttpClient client, string userName, string password)
{
string baseAddress = "http://localhost:9000/";
// GETTING THE ERROR AT THIS LINE
using (WebApp.Start<Startup>(url: baseAddress))
{
var form = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", userName },
{"password", password},
};
var tokenResponse = client.PostAsync(baseAddress + "accesstoken", new FormUrlEncodedContent(form)).Result;
var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
}
}
}
错误:-
无法加载文件或程序集“Microsoft.Owin,Version=2.0.2.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35”或其依赖项之一。找到的程序集的清单定义与程序集引用不匹配。(来自 HRESULT 的异常:0x80131040)
在谷歌搜索上,我得到了几个链接并安装了以下软件包:-
Install-package Microsoft.Owin.Host.HttpListener
网络配置
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="Secretkey" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
我在这里缺少什么?
任何帮助或建议都非常感谢。谢谢。