簡體   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