title: How can i implement Cookie base authentication and jwt in asp.net core 2.2?
body: <p>I want to use both cookie based authentication and <code>jwt</code> in my program, used authentication user to access <code>mvc</code> controller with login and JWT to access WebApi resource.</p>
  
  <p>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! </p>
  
  <p>In my <code>startup.cs</code> file I have:</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
          {
  
  
              services.Configure&lt;CookiePolicyOptions&gt;(options =&gt;
              {
                  options.CheckConsentNeeded = context =&gt; true;
                  options.MinimumSameSitePolicy = SameSiteMode.None;
                  options.ConsentCookie.Name = "Cookie";
              });
              services.ConfigureApplicationCookie(options =&gt;
              {
                  options.Cookie.Name = "Cookie";
                  options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
              });
  
              services.AddAntiforgery(options =&gt; options.HeaderName = "X-XSRF-TOKEN");
  
              services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
                  options.UseSqlServer(
                      Configuration.GetConnectionString("DefaultConnection")));
  
              services.AddIdentity&lt;ApplicationUser, ApplicationRole&gt;()
                  .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
                  .AddDefaultUI(UIFramework.Bootstrap4)
                  .AddDefaultTokenProviders();
  
              services.Configure&lt;IdentityOptions&gt;(options =&gt;
              {
                  // 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 =&gt;
              {
                  options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  
              })
                  .AddCookie(options =&gt;
                  {
                      options.Cookie.Name = "Cookie";
                      options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                  })
                  .AddMicrosoftAccount(microsoftOptions =&gt;
                   {
                       microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
                       microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
                   })
                  .AddGoogle(googleOptions =&gt; 
                  {
                      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 =&gt;
                      {
                          List&lt;AuthenticationToken&gt; tokens = ctx.Properties.GetTokens()
                              as List&lt;AuthenticationToken&gt;;
                          tokens.Add(new AuthenticationToken()
                          {
                              Name = "TicketCreated",
                              Value = DateTime.UtcNow.ToString()
                          });
                          ctx.Properties.StoreTokens(tokens);
                          return Task.CompletedTask;
                      };
                  })
                  .AddJwtBearer(options =&gt;
                  {
                      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&lt;IConfiguration&gt;(Configuration);
  
          }
  </code></pre>
  
  <p>And I got a token in this controller:</p>
  
  <pre><code>[AllowAnonymous]
          [HttpPost]
          public async Task&lt;IActionResult&gt; 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" &amp;&amp; model.Username == "username");
              if (user != null &amp;&amp; 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();
  
          }
  </code></pre>
  
  <p>I implement control that creates token, but when I tried authorizing with that I get this error:</p>
  
  <pre><code>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&lt;T&gt;.GetConfigurationAsync(CancellationToken cancel)
  </code></pre>