繁体   English   中英

Web Api项目中的MVC应用程序Cookie和令牌认证

[英]MVC application Cookie AND Token authentication in Web Api project

我目前正在开展一个有2个客户的项目。 MVC客户端和Android客户端。

我已经实现了ASP .Net Identityauthentication我的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM