我有ASP.NET MVC项目,并且将表单身份验证(Cookie基础)与ASP.NET标识一起使用。我将WEB API控制器添加到该项目中。现在我想要的是对于MVC项目,它应该使用使用Cookie的表单身份验证,但是对于API,它应该使用令牌库,即如何配置它。
此致,伊姆兰·艾哈迈德(Imran Ahmad)
首先安装这些NuGet软件包,
1.安装软件包Microsoft.AspNet.WebApi.Owin
2.安装软件包Microsoft.Owin.Host.SystemWeb
3.安装软件包Microsoft.Owin.Security.OAuth
然后,该项目必须具有StartUp.cs文件。
将此代码添加到您的文件中
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
Provider = new AuthorizationServerProvider()
};
// To Generate token
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
将此代码添加到新的AuthorizationServerProvider.cs文件中
public class AuthorizationServerProvider: OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
context.Validated(identity);
}
}
您可以通过发布到端点来使用Postman API客户端测试代码
yourwebsite/api/token
以及邮递员标签中的grant_type
,用户名和密码
x-www-form-Urlencoded
。
您将获得一个access_token的响应,并在调用Resource
控制器时将此访问令牌放在标头中。
有关更多参考,请参阅http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句