![](/img/trans.png)
[英]How to Add token authentication to web api in cookie authentication based asp.net mvc project
[英]MVC application Cookie AND Token authentication in Web Api project
我目前正在开展一个有2个客户的项目。 MVC
客户端和Android
客户端。
我已经实现了ASP .Net Identity
来authentication
我的MVC
控制器。 MVC
项目还包括一些Web API
控制器。 在我的视图中,我调用了控制器,以及对我的Web API
一些ajax调用。
问题:当我从浏览器向Web API(或控制器)发出ajax调用时,是否可以使用cookie based authentication
,但是当我从android应用程序进行ajax调用时,使用token authentication
?
我正在使用.Net Framework 4.6.1
定义两个策略:一个用于API( apipolicy ),另一个用于ConfigureServices中的Startup.cs中的普通MVC调用( defaultpolicy ):
services.AddAuthorization(options =>
{
// define several authorization policies if needed
options.AddPolicy("defaultpolicy", b =>
{
b.RequireAuthenticatedUser();
});
options.AddPolicy("apipolicy", b =>
{
b.RequireAuthenticatedUser();
// define which authentication is used for this policy
b.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
});
应用您需要的每个策略来装饰具有所需[Authorize ("policy")]
属性的控制器,如:
SampleDataApiController.cs - 应用了apipolicy
[Authorize ("apipolicy")]
[Route("api/[controller]")]
public class SampleDataApiController : Controller
{
}
AccountController.cs - 应用了defaultpolicy
[Authorize("defaultpolicy")]
[Route("[controller]/[action]")]
public class AccountController : Controller
{
}
这里的示例是我完整的ConfigureServices方法,可以为您提供一个想法:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("defaultpolicy", b =>
{
b.RequireAuthenticatedUser();
});
options.AddPolicy("apipolicy", b =>
{
b.RequireAuthenticatedUser();
b.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
});
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "CustomScheme";
})
.AddCookie()
.AddJwtBearer(options =>
{
// Bearer Logic
})
.AddOAuth("CustomScheme", options =>
{
// Oauth Logic
});
}
为简单起见,我刚刚添加了以下nuget。 Microsoft.AspNetCore.All
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.