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

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

ASP Net Core 2.2 僅向需要授權(quán)的方法添加儲(chǔ)物柜圖標(biāo)

ASP Net Core 2.2 僅向需要授權(quán)的方法添加儲(chǔ)物柜圖標(biāo)

C#
慕森卡 2023-08-13 15:36:25
我目前擁有什么?我已經(jīng)在我的 Web API 項(xiàng)目中實(shí)現(xiàn)了 swagger。我正在使用 JWT 授權(quán),并[Authorize]在需要它的方法上使用屬性。所以我想要一種簡單的方法來發(fā)送需要授權(quán)的請求。在我的ConfigureServices課堂上,我添加了以下邏輯。services.AddSwaggerGen(c =>{    // Other swagger options    c.AddSecurityDefinition("Bearer", new ApiKeyScheme    {        In = "header",        Description = "Please enter into field the word 'Bearer' following by space and your JWT token",        Name = "Authorization",        Type = "apiKey"    });    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>    {        { "Bearer", Enumerable.Empty<string>() },    });    // Other swagger options});其作用如下:它在 swagger 中添加了一個(gè)新按鈕 - 授權(quán)。問題是,它還在每個(gè)方法旁邊添加了一個(gè)“打開”儲(chǔ)物柜圖標(biāo)。盡管如此,其中一些需要授權(quán)。當(dāng)我使用授權(quán)按鈕成功授權(quán)時(shí)(它基本上為每個(gè)請求添加了標(biāo)頭授權(quán)),我在所有請求上收到一個(gè)“關(guān)閉”的儲(chǔ)物柜。 我知道這可能是所需的功能,表明將通過請求發(fā)送授權(quán)令牌。我想要一種方法來顯示哪些方法需要授權(quán),哪些不需要。我想要什么?例如,匿名方法的“開放”儲(chǔ)物柜和具有[Authorize]屬性的方法的“關(guān)閉”儲(chǔ)物柜。它可能是一個(gè)附加圖標(biāo),位于該圖標(biāo)旁邊或用于修改該圖標(biāo)的行為,沒問題。我怎樣才能實(shí)現(xiàn)這個(gè)目標(biāo)?可能的解決方案?我相信一個(gè)可能的解決方案是創(chuàng)建一個(gè)操作過濾器并遍歷所有方法并將“某些內(nèi)容”僅附加到那些具有[Authorize]屬性的方法。這是最好的解決方案嗎?如果是這樣,你會(huì)如何實(shí)施?
查看完整描述

3 回答

?
滄海一幻覺

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

因?yàn)榫嚯x我問這個(gè)問題已經(jīng)過去一個(gè)多月了。我是這樣做的。


我從 中刪除了以下代碼Startup.cs:


c.AddSecurityDefinition("Bearer", new ApiKeyScheme

{

    In = "header",

    Description = "Please enter into field the word 'Bearer' following by space and your JWT token",

    Name = "Authorization",

    Type = "apiKey"

});

c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>

{

    { "Bearer", Enumerable.Empty<string>() },

});

我添加了以下一項(xiàng):


c.OperationFilter<AddAuthHeaderOperationFilter>();

當(dāng)然還有AddAuthHeaderOperationFilter.cs:


    public class AddAuthHeaderOperationFilter : IOperationFilter

    {

        private readonly IHttpContextAccessor httpContextAccessor;


        public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)

        {

            this.httpContextAccessor = httpContextAccessor;

        }


        public void Apply(Operation operation, OperationFilterContext context)

        {

            var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;

            var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);

            var allowAnonymous = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);


            if (isAuthorized && !allowAnonymous)

            {

                if (operation.Parameters == null)

                    operation.Parameters = new List<IParameter>();


                operation.Parameters.Add(new NonBodyParameter

                {

                    Name = "Authorization",

                    In = "header",

                    Description = "JWT access token",

                    Required = true,

                    Type = "string",

                    //Default = $"Bearer {token}"

                });


                operation.Responses.Add("401", new Response { Description = "Unauthorized" });

                operation.Responses.Add("403", new Response { Description = "Forbidden" });


                operation.Security = new List<IDictionary<string, IEnumerable<string>>>();


                //Add JWT bearer type

                operation.Security.Add(new Dictionary<string, IEnumerable<string>>

                {

                    { "Bearer", new string[] { } }

                });

            }

        }

    }

很快,這個(gè)OperationFilter類只將儲(chǔ)物柜圖標(biāo)添加到需要授權(quán)的方法中。不過儲(chǔ)物柜總是打開的。所以這不是完美的解決方案,但目前還可以。


它看起來是這樣的:

https://img1.sycdn.imooc.com//64d8886d0001f39906530147.jpg

查看完整回答
反對 回復(fù) 2023-08-13
?
慕碼人2483693

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

更改為以下內(nèi)容(進(jìn)行了一些額外的樣式編輯):


public class AddAuthHeaderOperationFilter : IOperationFilter

{

? ? private readonly IHttpContextAccessor httpContextAccessor;


? ? public AddAuthHeaderOperationFilter(IHttpContextAccessor httpContextAccessor)

? ? {

? ? ? ? this.httpContextAccessor = httpContextAccessor;

? ? }


? ? public void Apply(Operation operation, OperationFilterContext context)

? ? {

? ? ? ? var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;

? ? ? ? var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);

? ? ? ? var allowAnonymous = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);


? ? ? ? if (isAuthorized && !allowAnonymous)

? ? ? ? {

? ? ? ? ? ? if (operation.Parameters == null)

? ? ? ? ? ? ? ? operation.Parameters = new List<IParameter>();


? ? ? ? ? ? operation.Parameters.Add(new NonBodyParameter

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Name = "Authorization",

? ? ? ? ? ? ? ? In = "header",

? ? ? ? ? ? ? ? Description = "JWT access token",

? ? ? ? ? ? ? ? Required = true,

? ? ? ? ? ? ? ? Type = "string"

? ? ? ? ? ? });


? ? ? ? ? ? operation.Responses.Add("401", new Response { Description = "Unauthorized" });

? ? ? ? ? ? operation.Responses.Add("403", new Response { Description = "Forbidden" });


? ? ? ? ? ? operation.Security = new List<IDictionary<string, IEnumerable<string>>>();


? ? ? ? ? ? //Add JWT bearer type

? ? ? ? ? ? operation.Security.Add(new Dictionary<string, IEnumerable<string>>

? ? ? ? ? ? {

? ? ? ? ? ? ? ? { "Bearer", new string[] { } }

? ? ? ? ? ? });

? ? ? ? }

? ? }

}

編輯


如果將 Authorization 標(biāo)頭定義為參數(shù),Swagger UI 將拒絕發(fā)送該標(biāo)頭。因此,更好的選擇可能是在 SwaggerGen 服務(wù)配置中創(chuàng)建安全定義(通常在 Startup.ConfigureServices 中):


public void ConfigureServices(IServiceCollection services)

{

? ? // Service configuration

? ? services.AddSwaggerGen(c =>

? ? {

? ? ? ? // Configure Swagger

? ? ? ? // "Bearer" is the name for this definition. Any other name could be used

? ? ? ? c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Description = "Use bearer token to authorize",

? ? ? ? ? ? ? ? Type = SecuritySchemeType.Http,

? ? ? ? ? ? ? ? Scheme = "bearer",

? ? ? ? ? ? ? ? BearerFormat = "JWT"

? ? ? ? ? ? });

? ? }

}

然后添加安全要求以及對操作定義的引用:


public class AddAuthorizationHeaderOperationHeader : IOperationFilter

{

? ? public void Apply(OpenApiOperation operation, OperationFilterContext context)

? ? {

? ? ? ? var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;

? ? ? ? var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);

? ? ? ? var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);


? ? ? ? if (!isAuthorized || allowAnonymous)

? ? ? ? {

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? if (operation.Parameters == null)

? ? ? ? ? ? operation.Parameters = new List<OpenApiParameter>();


? ? ? ? operation.Security = new List<OpenApiSecurityRequirement>();


? ? ? ? //Add JWT bearer type

? ? ? ? operation.Security.Add(new OpenApiSecurityRequirement

? ? ? ? ? ? {

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? new OpenApiSecurityScheme

? ? ? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? ? ? ? ??

? ? ? ? ? ? ? ? ? ? ? ? Reference = new OpenApiReference

? ? ? ? ? ? ? ? ? ? ? ? {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

? ? ? ? ? ? ? ? ? ? ? ? ? ? Type = ReferenceType.SecurityScheme,

? ? ? ? ? ? ? ? ? ? ? ? ? ? // Definition name.?

? ? ? ? ? ? ? ? ? ? ? ? ? ? // Should exactly match the one given in the service configuration

? ? ? ? ? ? ? ? ? ? ? ? ? ? Id = "Bearer"

? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? }, new string[0]

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? );

? ? }

}


查看完整回答
反對 回復(fù) 2023-08-13
?
MM們

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

請按照以下步驟使用正確的掛鎖來實(shí)施 Swagger -


步驟1


添加一個(gè)類并通過接口繼承該類IOperationFilter。之后,實(shí)現(xiàn)接口Apply的方法定義IOperationFilter。


要實(shí)現(xiàn)Apply方法,您需要兩個(gè)類型為OpenApiOperation和的參數(shù)OpenApiOperation。


public class AddSwaggerService : IOperationFilter

    {     


        public void Apply(OpenApiOperation operation, OperationFilterContext context)

        {

            var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;

            var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);

            var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);


            if (!isAuthorized || allowAnonymous)

            {

                return;

            }

            if (operation.Parameters == null)

                operation.Parameters = new List<OpenApiParameter>();


            operation.Security = new List<OpenApiSecurityRequirement>();


            

            var security = new OpenApiSecurityRequirement

            {

                {

                    new OpenApiSecurityScheme

                    {

                        Reference = new OpenApiReference

                        {

                            Type = ReferenceType.SecurityScheme,                            

                            Id = "Bearer"

                        }

                    }, new List<string>()

                }

            };

            //add security in here

            operation.Security.Add(security);

        }

第2步


添加swagger Generation Service在ConfigureServices方法中Startup.cs。在此服務(wù)中,您需要添加我們在步驟 1 中實(shí)現(xiàn)的以下行。


c.OperationFilter<AddSwaggerService>();


 public void ConfigureServices(IServiceCollection services)

        {


//.........other Services.........

//.........other Services.........

//.........other Services.........


services.AddSwaggerGen(c =>

                c.SwaggerDoc(AppConstantKeys.APIName, new OpenApiInfo { Title = "title", Version = "APIVersion" });


                c.OperationFilter<AddSwaggerService>();

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme

                {

                    Description ="SwaggerShortDescription",

                    Name = "HeaderName",

                    In = ParameterLocation.Header,

                    Type = SecuritySchemeType.ApiKey,


                });

            });


//.........other Services.........

//.........other Services.........

//.........other Services.........


}

Step-3 在中間件管道中添加 swagger。


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

//.........other middlewares.........

//.........other middlewares.........

//.........other middlewares.........

//.........other middlewares.........



            app.UseSwagger();

            app.UseSwaggerUI(c =>

            {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerUIName");

                c.DocumentTitle = "SwaggerUITitle";

                c.DocExpansion(DocExpansion.None);

                c.RoutePrefix = string.Empty;

            });


//.........other middlewares.........

//.........other middlewares.........

//.........other middlewares.........

//.........other middlewares.........



}



步驟4


構(gòu)建并運(yùn)行。

https://img1.sycdn.imooc.com//64d888930001b67e14490230.jpg

查看完整回答
反對 回復(fù) 2023-08-13
  • 3 回答
  • 0 關(guān)注
  • 178 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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