【发布时间】:2017-06-27 07:48:56
【问题描述】:
过去 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
Web.Config
<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>
我在这里缺少什么?
非常感谢任何帮助或建议。 谢谢。
【问题讨论】:
-
与您的问题无关,但您应该首先解决这个可怕的实现。您的
OAuth.InitOAuth从控制器调用并启动新的 WebApp?我认为您的申请流程至少存在缺陷。 -
@PeterBons,感谢您的关注。我是新手,请您详细说明如何更正它
-
按照这个实现一步一步来bitoftech.net/2014/06/01/…
-
你如何托管你的 web api。如果您查看已链接的教程,您会看到 Web 应用程序在控制台应用程序启动时启动。然后客户端使用 url + 令牌端点请求令牌,例如 localhost/api/accesstoken。然后,您在控制器上放置了一个
01.[Authorize]属性,现在客户端只有在拥有令牌时才能访问该方法。我建议首先按照教程进行操作,然后尝试使其适应您的需求。
标签: c# asp.net asp.net-web-api owin http-token-authentication