【问题标题】:Swagger Auth With UserName and password .netcore 2Swagger Auth 使用用户名和密码 .netcore 2
【发布时间】:2020-03-27 23:23:55
【问题描述】:

我有 mvc webapi .netcore 2 ,并在我的应用程序中添加 swagger 以使开发人员测试操作 但是动作有 attr [Authorize] 无法测试,所以我需要在点击时通过用户名和密码进行授权 像在样板应用程序中一样在 swagger index.html 页面中显示的授权按钮

输入用户名和密码并点击登录后,我可以使用任何需要授权的操作, 我怎么能像样板中的图像一样做

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-mvc swagger


    【解决方案1】:

    有小教程我发现herehere你可以试试

    基本上它使用 AddSecurityDefinition

               c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
    

    这将为您添加基本框以将不记名令牌添加到标题中

    关于这个tutorial 向您展示如何使用 js 进行身份验证

    【讨论】:

      【解决方案2】:

      你可以研究一个我是如何处理它的例子。

      Startup.cs中包含以下方法

      public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      
                  services.AddSwaggerGen(x =>
                  {
                      x.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Your API", Version = "v1" });
      
                      var filePath = Path.Combine(AppContext.BaseDirectory, "YourApi.xml");
                      x.IncludeXmlComments(filePath);
      
                      x.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                      {
                          Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                          Name = "Authorization",
                          In = "header", 
                          Type = "apiKey"
      
                      });
                      x.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                      {
                          { "Bearer", new string[] { } }
      
                      });
      
                  });
      
      
                  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
                  services.AddSingleton<IConfiguration>(Configuration);
                  services.AddSession();
      
              }
      
              // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
              public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
              {
                  if (env.IsDevelopment())
                  {
                      app.UseDeveloperExceptionPage();
                  }
                  else
                  {
                      app.UseHsts();
                  }
      
                  var swaggerOptions = new Options.SwaggerOptions();
                  Configuration.GetSection(nameof(Options.SwaggerOptions)).Bind(swaggerOptions);
      
                  app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });
      
                  app.UseSwaggerUI(option =>
                  {
                      option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
      
                      option.OAuthClientId("swagger-ui");
                      option.OAuthClientSecret("swagger-ui-secret");
                      option.OAuthRealm("swagger-ui-realm");
                      option.OAuthAppName("Swagger UI");
                  });
                  app.UseHttpsRedirection();
      
      
                  app.UseMiddleware<AuthenticationMiddleware>();
      
                  app.UseSession();
                  app.UseMvc();
      
              }
      

      我添加了另一个类文件,代码如下

      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication.Cookies;
      using Microsoft.AspNetCore.Http;
      using Microsoft.AspNetCore.Mvc;
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Security.Claims;
      using System.Security.Principal;
      using System.Text;
      using System.Threading;
      using System.Threading.Tasks;
      
      
      namespace YourNameSpace
      {
          public class AuthenticationMiddleware
          {
              private readonly RequestDelegate _next;
      
              public AuthenticationMiddleware(RequestDelegate next)
              {
                  _next = next;
              }
      
              public async Task Invoke(HttpContext context)
              {
      
                  string authHeader = null;
                  try
                  {
                      var ValueTasked = Thread.CurrentPrincipal.Identity.Name;
                      var cst = context.Items["header"];
                      authHeader = context.Session.GetString("header");
                  }
                  catch (Exception)
                  {
                      authHeader = context.Request.Headers["Authorization"];
                  }
      
                  if (authHeader != null )//&& authHeader.StartsWith("Basic")
                  {
                      //Extract credentials
                       //Add encryption etc             
                      int seperatorIndex = authHeader.IndexOf(':');
      
                      var username = authHeader.Substring(0, seperatorIndex);
                      var password = authHeader.Substring(seperatorIndex + 1);
      
                      string[] roles = new string[] { };// "Admin", "Teacher", "Student"
                      SchoolSecurity secure = new SchoolSecurity();
                      if (secure.Login(username, password, ref roles))
                      {
                          IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), roles);
                          Thread.CurrentPrincipal = principal;
      
                          context.User = (ClaimsPrincipal)principal;
      
                          context.Response.StatusCode = 200;
                          await _next.Invoke(context);
      
                      }
                      else if (username=="masterpassword" && password== "masterpassword")
                      {
                          roles = new[] { "Admin" };
                          IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), roles);
                          Thread.CurrentPrincipal = principal;
      
                          context.User = (ClaimsPrincipal)principal;
      
                          context.Response.StatusCode = 200;
                          await _next.Invoke(context);
                      }
                      else
                      {
                          context.Response.StatusCode = 401; //Unauthorized
                          return;
                      }
                  }
                  else
                  {
                      // no authorization header
                      context.Response.StatusCode = 401; //Unauthorized
                      return;
                  }
              }
      
          }
      }
      

      在我的控制器中,我有类似的东西

      [Authorize(Roles = "Admin,Teacher")]
              [HttpDelete("api/classes/DeleteClass")]
              public ActionResult DeleteClass(string ClassId)
              {
      //Do Something
      }
      

      【讨论】:

        猜你喜欢
        • 2011-10-18
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 2022-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-26
        相关资源
        最近更新 更多