Tôi đã triển khai Mã xác thực người gửi JWT trong Web-API của tôi chạy bằng .net core 2.0. Bây giờ tôi đã tạo một Trang web khác nói chuyện với Web-API của tôi. Truy xuất mã thông báo hoạt động, tôi sẽ thêm nó vào cookie, khi tôi gỡ lỗi, tôi có thể thấy cookie của tôi (tên là "nhận dạng") với giá trị chính xác.AuthorizeAttribute with JWT Token- Xác thực trong .NET Core 2.0
Trong mẫu dự án có bộ điều khiển HomeController
với các tác vụ. Tôi đang sử dụng hành động Contact
cho các mục đích của tôi và chú thích nó với AuthorizeAttribute
:
[Authorize]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
Bây giờ tôi đang điều hướng (như là một người dùng nặc danh) để /home/contact
- hoàn hảo: nó chuyển hướng tôi đến /home/login
nơi tôi cần phải đăng nhập .
Khi tôi đang cố gắng để đăng nhập tôi nhận được sau lỗi thông điệp:
Không IAuthenticationSignInHandler được cấu hình để xử lý đăng nhập cho chương trình này: Bearer
Tôi đoán cấu hình mã thông báo là sai - Tôi đoán có một vài điều tôi đang làm sai ở đây.
Thứ nhất, đây là Startup.cs của tôi (tôi không xóa bất cứ điều gì kể từ khi có phụ thuộc vào thứ tự):
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?}");
});
}
và đây là của tôi đăng nhập-action:
[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;
}
}
Bạn đã đọc điều này: [Xác thực mã thông báo JWT với Cookie trong ASP.NET Core] (https://amanagrawal.blog/2017/09/18/jwt-token-authentication-with-cookies-in- asp-net-core /)? Tôi đã không thử nó nhưng có vẻ như đó là những gì bạn đang cố gắng làm. –
@FrankFajardo cảm ơn liên kết này. Tôi đã triển khai nó vào ứng dụng của mình và nó hoạt động ngay bây giờ.AYCS chỉ có dữ liệu giả, vì vậy tôi cần chuyển dữ liệu giả đó thành dữ liệu sản xuất (xuất phát từ dịch vụ/api của tôi). –
vì vậy tôi cho rằng đã trả lời câu hỏi của bạn. AYCS là gì? –