第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

實(shí)現(xiàn) AbpIdentity cookies 和 JwtBearer

實(shí)現(xiàn) AbpIdentity cookies 和 JwtBearer

C#
慕桂英3389331 2023-09-24 15:53:33
我繼承了一個(gè)同時(shí)使用 Web API 和 MVC 前端的 ASPnetzero 應(yīng)用程序。API 通過 Bearer 進(jìn)行身份驗(yàn)證,前端通過 AbpIdentity (Cookies) 進(jìn)行身份驗(yàn)證。幾天前,我勇敢地決定更新我的 nuGet 軟件包。該更新伴隨著從 .netCore v1 到 v2 的升級(jí)。但在 JwtBearer 中間件過時(shí)后,我在身份驗(yàn)證方面遇到了一些困難。我可以使用 cookie 進(jìn)行身份驗(yàn)證,但不能使用不記名令牌。我?guī)缀鯂L試了一切。使用多種身份驗(yàn)證方法意味著一次只能使用一種方法。在 Startup.cs 中,我有以下內(nèi)容(片段):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);         }然而,這是一個(gè)自我回答的問題,我希望我能幫助任何有類似或相同情況的人,因?yàn)槲乙呀?jīng)整理了自己的解決方案。這個(gè)想法是讓應(yīng)用程序使用 Bearer 令牌(僅當(dāng)使用 API 時(shí))和 cookie(僅當(dāng)使用 MVC 時(shí))。我還面臨一個(gè)挑戰(zhàn),因?yàn)?MVC 對(duì) API 進(jìn)行 XHR 調(diào)用以獲取要在前端顯示的數(shù)據(jù)。這意味著 API 還需要與 Cookie 配合使用(但僅適用于 MVC 用戶)。
查看完整描述

1 回答

?
紅糖糍粑

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊

所以我終于弄清楚了,這需要相當(dāng)大的轉(zhuǎn)變。結(jié)果是:

  1. API 用戶僅使用 Bearer Token 進(jìn)行身份驗(yàn)證

  2. MVC 用戶使用 Cookie 進(jìn)行身份驗(yàn)證,登錄后應(yīng)用程序中的 API 調(diào)用也使用相同的身份驗(yàn)證。

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

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();

}


查看完整回答
反對(duì) 回復(fù) 2023-09-24
  • 1 回答
  • 0 關(guān)注
  • 150 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)