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

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

ASP Net Core 2.2 僅向需要授權的方法添加儲物柜圖標

ASP Net Core 2.2 僅向需要授權的方法添加儲物柜圖標

C#
慕森卡 2023-08-13 15:36:25
我目前擁有什么?我已經在我的 Web API 項目中實現了 swagger。我正在使用 JWT 授權,并[Authorize]在需要它的方法上使用屬性。所以我想要一種簡單的方法來發送需要授權的請求。在我的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 中添加了一個新按鈕 - 授權。問題是,它還在每個方法旁邊添加了一個“打開”儲物柜圖標。盡管如此,其中一些需要授權。當我使用授權按鈕成功授權時(它基本上為每個請求添加了標頭授權),我在所有請求上收到一個“關閉”的儲物柜。 我知道這可能是所需的功能,表明將通過請求發送授權令牌。我想要一種方法來顯示哪些方法需要授權,哪些不需要。我想要什么?例如,匿名方法的“開放”儲物柜和具有[Authorize]屬性的方法的“關閉”儲物柜。它可能是一個附加圖標,位于該圖標旁邊或用于修改該圖標的行為,沒問題。我怎樣才能實現這個目標?可能的解決方案?我相信一個可能的解決方案是創建一個操作過濾器并遍歷所有方法并將“某些內容”僅附加到那些具有[Authorize]屬性的方法。這是最好的解決方案嗎?如果是這樣,你會如何實施?
查看完整描述

3 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

因為距離我問這個問題已經過去一個多月了。我是這樣做的。


我從 中刪除了以下代碼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>() },

});

我添加了以下一項:


c.OperationFilter<AddAuthHeaderOperationFilter>();

當然還有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[] { } }

                });

            }

        }

    }

很快,這個OperationFilter類只將儲物柜圖標添加到需要授權的方法中。不過儲物柜總是打開的。所以這不是完美的解決方案,但目前還可以。


它看起來是這樣的:

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

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

TA貢獻1860條經驗 獲得超9個贊

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


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 標頭定義為參數,Swagger UI 將拒絕發送該標頭。因此,更好的選擇可能是在 SwaggerGen 服務配置中創建安全定義(通常在 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]

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? );

? ? }

}


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

TA貢獻1886條經驗 獲得超2個贊

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


步驟1


添加一個類并通過接口繼承該類IOperationFilter。之后,實現接口Apply的方法定義IOperationFilter。


要實現Apply方法,您需要兩個類型為OpenApiOperation和的參數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。在此服務中,您需要添加我們在步驟 1 中實現的以下行。


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


構建并運行。

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

查看完整回答
反對 回復 2023-08-13
  • 3 回答
  • 0 關注
  • 182 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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