亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

實現 AbpIdentity cookies 和 JwtBearer

實現 AbpIdentity cookies 和 JwtBearer

C#
慕桂英3389331 2023-09-24 15:53:33
我繼承了一個同時使用 Web API 和 MVC 前端的 ASPnetzero 應用程序。API 通過 Bearer 進行身份驗證,前端通過 AbpIdentity (Cookies) 進行身份驗證。幾天前,我勇敢地決定更新我的 nuGet 軟件包。該更新伴隨著從 .netCore v1 到 v2 的升級。但在 JwtBearer 中間件過時后,我在身份驗證方面遇到了一些困難。我可以使用 cookie 進行身份驗證,但不能使用不記名令牌。我幾乎嘗試了一切。使用多種身份驗證方法意味著一次只能使用一種方法。在 Startup.cs 中,我有以下內容(片段):public IServiceProvider ConfigureServices(IServiceCollection services)        {            services.AddAbpIdentity<Tenant, User, Role>()            .AddUserManager<UserManager>()            .AddRoleManager<RoleManager>()            .AddSignInManager<SignInManager>()            .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory>()            .AddDefaultTokenProviders();        }public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {          AuthConfigurer.Configure(app, _appConfiguration);         }然而,這是一個自我回答的問題,我希望我能幫助任何有類似或相同情況的人,因為我已經整理了自己的解決方案。這個想法是讓應用程序使用 Bearer 令牌(僅當使用 API 時)和 cookie(僅當使用 MVC 時)。我還面臨一個挑戰,因為 MVC 對 API 進行 XHR 調用以獲取要在前端顯示的數據。這意味著 API 還需要與 Cookie 配合使用(但僅適用于 MVC 用戶)。
查看完整描述

1 回答

?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

所以我終于弄清楚了,這需要相當大的轉變。結果是:

  1. API 用戶僅使用 Bearer Token 進行身份驗證

  2. MVC 用戶使用 Cookie 進行身份驗證,登錄后應用程序中的 API 調用也使用相同的身份驗證。

所有更改都是在 Startup.cs 中進行的,我還注釋掉了對 AuthConfigure.cs 文件的引用,該文件現已過時。我愿意接受對該解決方案的任何改進或建議。

Startup.cs 文件中的重要部分:

public IServiceProvider ConfigureServices(IServiceCollection services)

        {

          services.AddAuthentication()

                .AddJwtBearer(cfg =>

                {

                    cfg.RequireHttpsMetadata = false;

                    cfg.SaveToken = true;


                    cfg.TokenValidationParameters = new TokenValidationParameters()

                    {

                        // The application URL is used for the Issuer and Audience and is included in the appsettings.json

                        ValidIssuer = _appConfiguration["Authentication:JwtBearer:Issuer"],

                        ValidAudience = _appConfiguration["Authentication:JwtBearer:Audience"],

                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"]))

                    };


                });


             // Activate Cookie Authentication without Identity, since Abp already implements Identity below.

             services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/Login");


             // Add the Authentication Scheme Provider which will set the authentication method based on the kind of request. i.e API or MVC

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton<IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();


             // Some of these extensions changed

             services.AddAbpIdentity<Tenant, User, Role>()

            .AddUserManager<UserManager>()

            .AddRoleManager<RoleManager>()

            .AddSignInManager<SignInManager>()

            .AddClaimsPrincipalFactory<UserClaimsPrincipalFactory>()

            .AddDefaultTokenProviders();

//…

}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

        {

// app.UseAuthentication is critical here

            app.UseAuthentication();

            app.UseAbp(); //Initializes ABP framework.

            app.UseCors("CorsPolicy");

//…

 //AuthConfigurer.Configure(app, _appConfiguration);

//…

         }

}

public class CustomAuthenticationSchemeProvider : AuthenticationSchemeProvider

{

    private readonly IHttpContextAccessor httpContextAccessor;


    public CustomAuthenticationSchemeProvider(

        IHttpContextAccessor httpContextAccessor,

        IOptions<AuthenticationOptions> options)

        : base(options)

    {

        this.httpContextAccessor = httpContextAccessor;

    }


    private async Task<AuthenticationScheme> GetRequestSchemeAsync()

    {

        var request = httpContextAccessor.HttpContext?.Request;

        if (request == null)

        {

            throw new ArgumentNullException("The HTTP request cannot be retrieved.");

        }


        // For API requests, use authentication tokens.


        var authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"].FirstOrDefault();

        if (authHeader?.StartsWith("Bearer ") == true)

        {

            return await GetSchemeAsync(JwtBearerDefaults.AuthenticationScheme);

        }


        // For the other requests, return null to let the base methods

        // decide what's the best scheme based on the default schemes

        // configured in the global authentication options.

        return null;

    }


    public override async Task<AuthenticationScheme> GetDefaultAuthenticateSchemeAsync() =>

        await GetRequestSchemeAsync() ??

        await base.GetDefaultAuthenticateSchemeAsync();


    public override async Task<AuthenticationScheme> GetDefaultChallengeSchemeAsync() =>

        await GetRequestSchemeAsync() ??

        await base.GetDefaultChallengeSchemeAsync();


    public override async Task<AuthenticationScheme> GetDefaultForbidSchemeAsync() =>

        await GetRequestSchemeAsync() ??

        await base.GetDefaultForbidSchemeAsync();


    public override async Task<AuthenticationScheme> GetDefaultSignInSchemeAsync() =>

        await GetRequestSchemeAsync() ??

        await base.GetDefaultSignInSchemeAsync();


    public override async Task<AuthenticationScheme> GetDefaultSignOutSchemeAsync() =>

        await GetRequestSchemeAsync() ??

        await base.GetDefaultSignOutSchemeAsync();

}


查看完整回答
反對 回復 2023-09-24
  • 1 回答
  • 0 關注
  • 157 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號