久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

  • <tfoot id='nmPYK'></tfoot>

      <small id='nmPYK'></small><noframes id='nmPYK'>

      <i id='nmPYK'><tr id='nmPYK'><dt id='nmPYK'><q id='nmPYK'><span id='nmPYK'><b id='nmPYK'><form id='nmPYK'><ins id='nmPYK'></ins><ul id='nmPYK'></ul><sub id='nmPYK'></sub></form><legend id='nmPYK'></legend><bdo id='nmPYK'><pre id='nmPYK'><center id='nmPYK'></center></pre></bdo></b><th id='nmPYK'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='nmPYK'><tfoot id='nmPYK'></tfoot><dl id='nmPYK'><fieldset id='nmPYK'></fieldset></dl></div>

      • <bdo id='nmPYK'></bdo><ul id='nmPYK'></ul>
    1. <legend id='nmPYK'><style id='nmPYK'><dir id='nmPYK'><q id='nmPYK'></q></dir></style></legend>

      1. 如何在 asp.net core 2.2 中實現(xiàn) Cookie 基本身份驗證和

        How can i implement Cookie base authentication and jwt in asp.net core 2.2?(如何在 asp.net core 2.2 中實現(xiàn) Cookie 基本身份驗證和 jwt?)

        1. <i id='hoglb'><tr id='hoglb'><dt id='hoglb'><q id='hoglb'><span id='hoglb'><b id='hoglb'><form id='hoglb'><ins id='hoglb'></ins><ul id='hoglb'></ul><sub id='hoglb'></sub></form><legend id='hoglb'></legend><bdo id='hoglb'><pre id='hoglb'><center id='hoglb'></center></pre></bdo></b><th id='hoglb'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='hoglb'><tfoot id='hoglb'></tfoot><dl id='hoglb'><fieldset id='hoglb'></fieldset></dl></div>
        2. <tfoot id='hoglb'></tfoot>
            <tbody id='hoglb'></tbody>

          <small id='hoglb'></small><noframes id='hoglb'>

            <legend id='hoglb'><style id='hoglb'><dir id='hoglb'><q id='hoglb'></q></dir></style></legend>

                <bdo id='hoglb'></bdo><ul id='hoglb'></ul>
                  本文介紹了如何在 asp.net core 2.2 中實現(xiàn) Cookie 基本身份驗證和 jwt?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  限時送ChatGPT賬號..

                  我想在我的程序中同時使用基于 cookie 的身份驗證和 jwt,使用身份驗證用戶通過登錄和 JWT 訪問 mvc 控制器來訪問 WebApi 資源.

                  I want to use both cookie based authentication and jwt in my program, used authentication user to access mvc controller with login and JWT to access WebApi resource.

                  我嘗試使用其中兩個 首先,我的客戶端可以使用用戶名和密碼登錄并使用 cookie 進行身份驗證.使用帶有令牌承載的 WebApi 的應用程序的第二次訪問資源,但出現(xiàn)錯誤!

                  I tried using two of them First, my client can login and authenticate with the cookie using username and password. Second access resource from Application with WebApi with Token Bearer but I get an error!

                  在我的 startup.cs 文件中,我有:

                  In my startup.cs file I have:

                  public void ConfigureServices(IServiceCollection services)
                          {
                  
                  
                              services.Configure<CookiePolicyOptions>(options =>
                              {
                                  options.CheckConsentNeeded = context => true;
                                  options.MinimumSameSitePolicy = SameSiteMode.None;
                                  options.ConsentCookie.Name = "Cookie";
                              });
                              services.ConfigureApplicationCookie(options =>
                              {
                                  options.Cookie.Name = "Cookie";
                                  options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                              });
                  
                              services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
                  
                              services.AddDbContext<ApplicationDbContext>(options =>
                                  options.UseSqlServer(
                                      Configuration.GetConnectionString("DefaultConnection")));
                  
                              services.AddIdentity<ApplicationUser, ApplicationRole>()
                                  .AddEntityFrameworkStores<ApplicationDbContext>()
                                  .AddDefaultUI(UIFramework.Bootstrap4)
                                  .AddDefaultTokenProviders();
                  
                              services.Configure<IdentityOptions>(options =>
                              {
                                  // Password settings.
                                  options.Password.RequireDigit = true;
                                  options.Password.RequireLowercase = true;
                                  options.Password.RequireNonAlphanumeric = false;
                                  options.Password.RequireUppercase = false;
                                  options.Password.RequiredLength = 5;
                                  options.Password.RequiredUniqueChars = 1;
                  
                                  // Lockout settings.
                                  options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                                  options.Lockout.MaxFailedAccessAttempts = 5;
                                  options.Lockout.AllowedForNewUsers = true;
                  
                                  // User settings.
                                  options.User.AllowedUserNameCharacters =
                                  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                                  options.User.RequireUniqueEmail = false;
                  
                                  //Token
                              });
                  
                              services.AddAuthentication(options =>
                              {
                                  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                  
                              })
                                  .AddCookie(options =>
                                  {
                                      options.Cookie.Name = "Cookie";
                                      options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                                  })
                                  .AddMicrosoftAccount(microsoftOptions =>
                                   {
                                       microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
                                       microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
                                   })
                                  .AddGoogle(googleOptions => 
                                  {
                                      googleOptions.ClientId = "XXXXXXXXXXX.apps.googleusercontent.com";
                                      googleOptions.ClientSecret = "g4GZ2#...GD5Gg1x";
                                      googleOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
                                      googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Gender, "gender");
                                      googleOptions.SaveTokens = true;
                                      googleOptions.Events.OnCreatingTicket = ctx =>
                                      {
                                          List<AuthenticationToken> tokens = ctx.Properties.GetTokens()
                                              as List<AuthenticationToken>;
                                          tokens.Add(new AuthenticationToken()
                                          {
                                              Name = "TicketCreated",
                                              Value = DateTime.UtcNow.ToString()
                                          });
                                          ctx.Properties.StoreTokens(tokens);
                                          return Task.CompletedTask;
                                      };
                                  })
                                  .AddJwtBearer(options =>
                                  {
                                      options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                                      options.SaveToken = true;
                                      options.Authority = Configuration["Authentication:Authority"];
                                      options.Audience = Configuration["Authentication:Audience"];
                                      options.RequireHttpsMetadata = false;
                                      options.TokenValidationParameters = new TokenValidationParameters()
                                      {
                  
                                          ValidateIssuerSigningKey = true,
                  
                                          ValidateIssuer = true,
                                          ValidIssuer = Configuration["Authentication:ValidIssuer"],
                  
                                          ValidateAudience = true,
                                          ValidAudience = Configuration["Authentication:ValidAudience"],
                  
                                          ValidateLifetime = true,
                  
                                          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:SecurityKey"]))
                                      };
                                  });
                  
                  
                  
                  
                  
                  
                              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                              services.AddSession();
                  
                              services.AddSingleton<IConfiguration>(Configuration);
                  
                          }
                  

                  我在這個控制器中得到了一個令牌:

                  And I got a token in this controller:

                  [AllowAnonymous]
                          [HttpPost]
                          public async Task<IActionResult> GetToken(TokenLoginModel model)
                          {
                  
                              if (!ModelState.IsValid) return BadRequest("Token failed to generate");
                              var user = await _usermanager.FindByNameAsync(model.UserName);
                              //var user = true;// (model.Password == "password" && model.Username == "username");
                              if (user != null && await _usermanager.CheckPasswordAsync(user, model.Password))
                              {
                                  var claims = new[]{
                                      new Claim("ClaimsIssuer", _configuration.GetSection("Authentication:ClaimsIssuer").Value),
                                  new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Sub,user.UserName),
                                  new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                              };
                                  string SecurKey = Startup.StaticConfig.GetSection("Authentication:SecurityKey").Value;
                                  var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurKey));
                                  var token = new JwtSecurityToken(
                                      issuer: _configuration.GetSection("Authentication:ValidIssuer").Value,
                                      audience: _configuration.GetSection("Authentication:Audience").Value,
                                      expires: DateTime.UtcNow.AddDays(30),
                                      claims: claims,
                                      signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                                  );
                                  return Ok(new
                                  {
                                      token = new JwtSecurityTokenHandler().WriteToken(token),
                                      expiration = token.ValidTo
                                  });
                              }
                              return Unauthorized();
                  
                          }
                  

                  我實現(xiàn)了創(chuàng)建令牌的控制,但是當我嘗試使用它進行授權(quán)時,我得到了這個錯誤:

                  I implement control that creates token, but when I tried authorizing with that I get this error:

                  An unhandled exception occurred while processing the request.
                  
                  HttpRequestException: Response status code does not indicate success: 404 (Not Found).
                  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
                  
                  IOException: IDX20804: Unable to retrieve document from: 'https://localhost:44383/oauth2/default/.well-known/openid-configuration'.
                  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string address, CancellationToken cancel)
                  
                  InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://localhost:44383/oauth2/default/.well-known/openid-configuration'.
                  Microsoft.IdentityModel.Protocols.ConfigurationManager<T>.GetConfigurationAsync(CancellationToken cancel)
                  

                  推薦答案

                  為了增加對 JWT 的支持,我們添加了 AddCookie 和 AddJwtBearer.讓網(wǎng)站需要標頭中的令牌會讓人頭疼,尤其是對于不是純粹的 SPA 或 API 的項目.所以我真正想要的是同時支持 Cookie 和 JWT.

                  In order to add support for JWT, we added the AddCookie and AddJwtBearer. Having websites require the token in the header would be a headache, especially for projects that aren’t purely SPA or API. So what I really wanted was support for both Cookies and JWTs.

                  在 startup.cs 你有:

                  In startup.cs you have:

                      public class Startup
                    {
                      public Startup(IConfiguration configuration)
                      {
                        Configuration = configuration;
                      }
                      public IConfiguration Configuration { get; }
                  
                      // This method gets called by the runtime. Use this method to add services to the container.
                      public void ConfigureServices(IServiceCollection services)
                      {
                        services.AddDbContext<DualAuthContext>(options =>
                            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
                  
                        services.AddIdentity<ApplicationUser, IdentityRole>()
                            .AddEntityFrameworkStores<DualAuthContext>()
                            .AddDefaultTokenProviders();
                  
                        // Enable Dual Authentication 
                        services.AddAuthentication()
                          .AddCookie(cfg => cfg.SlidingExpiration = true)
                          .AddJwtBearer(cfg =>
                          {
                            cfg.RequireHttpsMetadata = false;
                            cfg.SaveToken = true;
                            cfg.TokenValidationParameters = new TokenValidationParameters()
                            {
                              ValidIssuer = Configuration["Tokens:Issuer"],
                              ValidAudience = Configuration["Tokens:Issuer"],
                              IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                            };
                          });
                  
                        // Add application services.
                        services.AddTransient<IEmailSender, EmailSender>();
                        services.AddMvc();
                      }
                  

                  在配置方法中:

                  public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataSeeder seeder)
                  {
                    ...
                    app.UseAuthentication();
                  }
                  

                  在您的控制器中使用 JWT 之后,您應該將 JWT Bearer AuthenticationSchemes 添加到 Authorize 屬性,如下所示:

                  After this in your controller that one you have used JWT, You should add JWT Bearer AuthenticationSchemes to Authorize attribute like this :

                  [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
                    [Route("/api/customers")]
                    public class ProtectedController : Controller
                    {
                      public ProtectedController()
                      {
                      }
                  
                      public IActionResult Get()
                      {
                        return Ok(new[] { "One", "Two", "Three" });
                      }
                    }
                  

                  參考:ASP.NET 中的兩個 AuthorizationSchemes核心2

                  使用起來非常簡單實用.

                  It's very simple and helpful to used.

                  這篇關(guān)于如何在 asp.net core 2.2 中實現(xiàn) Cookie 基本身份驗證和 jwt?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

                  【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

                  相關(guān)文檔推薦

                  What are good algorithms for vehicle license plate detection?(車牌檢測有哪些好的算法?)
                  onClick event for Image in Unity(Unity中圖像的onClick事件)
                  Running Total C#(運行總 C#)
                  Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(單擊帶有 JAvascript.ASP.NET C# 的超鏈接時刪除目錄)
                  asp.net listview highlight row on click(asp.net listview 在單擊時突出顯示行)
                  Calling A Button OnClick from a function(從函數(shù)調(diào)用按鈕 OnClick)
                    1. <legend id='ou6rt'><style id='ou6rt'><dir id='ou6rt'><q id='ou6rt'></q></dir></style></legend>
                    2. <i id='ou6rt'><tr id='ou6rt'><dt id='ou6rt'><q id='ou6rt'><span id='ou6rt'><b id='ou6rt'><form id='ou6rt'><ins id='ou6rt'></ins><ul id='ou6rt'></ul><sub id='ou6rt'></sub></form><legend id='ou6rt'></legend><bdo id='ou6rt'><pre id='ou6rt'><center id='ou6rt'></center></pre></bdo></b><th id='ou6rt'></th></span></q></dt></tr></i><div class="qwawimqqmiuu" id='ou6rt'><tfoot id='ou6rt'></tfoot><dl id='ou6rt'><fieldset id='ou6rt'></fieldset></dl></div>

                        <bdo id='ou6rt'></bdo><ul id='ou6rt'></ul>
                        <tfoot id='ou6rt'></tfoot>

                        <small id='ou6rt'></small><noframes id='ou6rt'>

                            <tbody id='ou6rt'></tbody>

                            主站蜘蛛池模板: 久久男女视频 | 在线不卡视频 | 999精彩视频| 国产探花 | 成人在线免费网站 | 久久久精品一区 | 视频在线观看亚洲 | 国产一区二区欧美 | 国产激情| 欧美日韩精品在线一区 | 男女免费观看在线爽爽爽视频 | 成人精品一区二区三区中文字幕 | 一区二区三区高清 | 久久午夜视频 | 亚洲色片网站 | 亚洲网站在线观看 | 中文字幕亚洲区一区二 | 亚洲欧美一区二区三区视频 | 99伊人| 午夜一区二区三区在线观看 | 在线播放中文字幕 | 国产成人精品一区 | 男女羞羞视频在线免费观看 | 日韩小视频 | 亚洲网一区 | 久草中文在线观看 | 中文字幕在线视频观看 | 在线播放中文字幕 | 国产精品永久免费视频 | 老司机深夜福利网站 | 女同久久 | 久操伊人 | 亚洲午夜av久久乱码 | 一区二区三区四区在线视频 | 青春草91| 91久久久久久| 亚洲国产精品日本 | 国产精品视频一区二区三区 | 粉嫩一区二区三区四区公司1 | 黄色大片毛片 | 中文在线一区二区 |