ich implementiert eine JWT Bearer Token- Authentifizierung in meinem Web-API, das 2.0 mit .net Kern läuft. Jetzt habe ich eine andere Website erstellt, die mit meiner Web-API spricht. Abrufen des Tokens funktioniert, ich füge es in Cookies ein, wenn ich debugge, kann ich meinen Cookie (Name ist "Identität") mit dem korrekten Wert sehen.AuthorizeAttribute mit JWT Token- Authentifizierung in .NET Core 2.0
In den Projekten Vorlage gibt es die Steuerung HomeController
mit den Aktionen. Ich bin mit der Aktion Contact
für meine Zwecke und mit Anmerkungen versehen es mit der AuthorizeAttribute
:
[Authorize]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
Jetzt bin Navigation I (als anonymer Benutzer) zu /home/contact
- perfekt: es leitet mich zu /home/login
wo ich brauche um sich einzuloggen .
Wenn ich versuche ich folgende Fehlermeldung erhalten einzuloggen:
Kein IAuthenticationSignInHandler konfiguriert ist für das Programm zu handhaben melden Sie sich an: Bearer
Ich denke, die Token-Konfiguration ist falsch - Ich denke, es gibt ein paar weitere Dinge, die ich hier falsch mache.
Als erstes ist hier mein Startup.cs (ich habe nichts löschen, da es Abhängigkeiten von der Reihenfolge):
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?}");
});
}
und hier ist meine Login-Aktion:
[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;
}
}
Haben Sie eine Lese dafür hatte: [JWT Token-Authentifizierung für Cookies in ASP.NET-Core] (https://amanagrawal.blog/2017/09/18/jwt-token-authentication-with-cookies-in- asp-net-core /)? Ich habe es nicht ausprobiert, aber es sieht so aus, als ob Sie das versuchen. –
@FrankFajardo danke für diesen Link. Ich habe es in meine Anwendung implementiert und es funktioniert jetzt.AYCS gibt es nur Dummy-Daten, also muss ich jetzt diese Dummy-Daten in produktive Daten umwandeln (das kommt von meinem Service/api). –
so nehme ich an, dass Ihre Frage beantwortet. Was bedeutet AYCS? –