In my web API that works with .net core 2.0, I implemented a JWT authentication token-authenticator-carrier. Now I have created another website that speaks with my web API. Getting work with the token, I add it to cookies, when I debug it, I see that my cookie (name "identity") has the correct value.
The project template has a HomeController with actions. I use the Contact action for my purposes and comment on it with AuthorizeAttribute :
[Authorize] public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); }
Now I browse (as an anonymous user) to /home/contact - perfect: it redirects me to /home/login , where I need to login.
When I try to log in, I get the following error message:
No IAuthenticationSignInHandler is configured to handle input for the schema: Media
I assume the marker configuration is incorrect - I think there are a few more things that I am doing wrong here.
Firstly, here is my Startup.cs (I did not delete anything, since there are order dependencies):
public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("mysupersecret_secretkey!123")), ValidateIssuer = true, ValidIssuer = "ExampleIssuer", ValidateAudience = true, ValidAudience = "ExampleAudience", ValidateLifetime = true, ClockSkew = TimeSpan.Zero, SaveSigninToken = true }; options.Events = new JwtBearerEvents { OnTokenValidated = context => { JwtSecurityToken accessToken = context.SecurityToken as JwtSecurityToken; if (accessToken != null) { ClaimsIdentity identity = context.Result.Principal.Identity as ClaimsIdentity; identity?.AddClaim(new Claim("access_token", accessToken.RawData)); } return Task.CompletedTask; } }; }) .AddCookie( o => { o.Cookie.Name = "beareridentity"; o.LoginPath = new PathString("/Home/Login/"); o.AccessDeniedPath = new PathString("/Home/Login/"); }); services.AddMvc(); services.AddTransient<IAccountService, AccountService>(); services.AddTransient(typeof(ISession), serviceProvider => { var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>(); return httpContextAccessor.HttpContext.Session; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseSession(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
and here is my login step:
[HttpPost] public async Task<IActionResult> Login(LoginData data) { var loginresult = (await _accountService.GetLoginToken(data.Username, data.Password)); if (!loginresult.Success) return RedirectToAction("Login"); Response.Cookies.Append("identity", loginresult.Token, new CookieOptions { Expires = DateTimeOffset.Now.Add int id = await _getIdFromToken(loginresult); ApplicationUser user; await _signin(user = await _accountService.GetUserAsync(id)); _session.SetData("actualuser", user); return RedirectToAction("Index"); } private async Task _signin(ApplicationUser c) { var claims = new List<Claim> { new Claim(ClaimTypes.MobilePhone, c.Phone??""), new Claim(ClaimTypes.Name, c.UserName) }; var userIdentity = new ClaimsIdentity(); userIdentity.AddClaims(claims); ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity); try { await HttpContext.SignInAsync( JwtBearerDefaults.AuthenticationScheme, userPrincipal, new Microsoft.AspNetCore.Authentication.AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = true, AllowRefresh = true, IssuedUtc = DateTimeOffset.Now }); } catch (Exception e) { throw; } }