AuthorizeAttribute with JWT Token - Authentication in .NET Core 2.0

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; } } 
+7
c # asp.net-web-api asp.net-core jwt
source share
3 answers

Here is a blog post on how you can use cookies as a delivery mechanism for your JWT on ASP.NET Core 2.0, and this is what you are trying to do: Authenticate the JWT token with Cookies in the ASP.NET core

I have not tried it, but it could help you figure out where you can do it wrong.

+2
source share

The default scheme does not match any handler (in this case, a cookie). If you can, try installing this in your code (this may be the .net 2 kernel specification):

 services.AddAuthentication("YourSchemeNameHere") .AddCookie("YourSchemeNameHere", options => { ... }); 

If this does not work, change the AuthenticationScheme property in the cookie settings to match the DefaultAuthenticateScheme in the authentication settings.

0
source share

I had a similar problem. Please check Web.config and check if you have a node or check if there is a node for authentication, maybe this is the reason, or maybe the configuration is wrong.

I am developing an mvc 5 application and my web configuration is similar to this

  <modules> <remove name="FormsAuthentication" /> <remove name="ApplicationInsightsWebTracking" /> <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> </modules> <authentication mode="None" /> 

I am using prebuilt asp.net authentication modules with my db

0
source share

All Articles