C# ASP.NET核心-同时使用Cookie和JWT for WebAPI
我已经设法为我的ASP.NET核心Web API配置了JWT身份验证。它在使用邮递员时有效 我还建立了一个MVC管理部分,我想登录。我遵循的创建管理部分的指南使用cookies而不是JWT身份验证来创建登录页面 它不工作,我在登录后收到401身份验证错误。它会将我重定向到正确的页面,您可以在浏览器中看到标识cookie,但我没有经过身份验证 我在这里太深了哈哈 我还可以使用cookies和JWT身份验证吗?JWT适用于任何想要访问WebAPI的手机应用程序,但不适用于通过WebAPI的管理页面登录的Cookie和会话 我的中间件C# ASP.NET核心-同时使用Cookie和JWT for WebAPI,c#,asp.net-core,asp.net-web-api,asp.net-identity,asp.net-authentication,C#,Asp.net Core,Asp.net Web Api,Asp.net Identity,Asp.net Authentication,我已经设法为我的ASP.NET核心Web API配置了JWT身份验证。它在使用邮递员时有效 我还建立了一个MVC管理部分,我想登录。我遵循的创建管理部分的指南使用cookies而不是JWT身份验证来创建登录页面 它不工作,我在登录后收到401身份验证错误。它会将我重定向到正确的页面,您可以在浏览器中看到标识cookie,但我没有经过身份验证 我在这里太深了哈哈 我还可以使用cookies和JWT身份验证吗?JWT适用于任何想要访问WebAPI的手机应用程序,但不适用于通过WebAPI的管理页
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// Tell Entity how to connect to the SQL Server
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});
// Configure Identity
services.Configure<IdentityOptions>(options =>
{
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.SignIn.RequireConfirmedEmail = false; // Set to true for production, test it
options.User.RequireUniqueEmail = false; // Set to true for production
});
services.Configure<PasswordHasherOptions>(options =>
{
// First byte of the hashed password is 0x00 = V2 and 0x01 = V3
options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV3; // Default IdentityV2 is used, it uses SHA1 for hashing, 1000 iterations.
options.IterationCount = 12000; // With IdentityV3 we can use SHA256 and 12000 iterations.
});
// We need to add the IdentityUser to Entity and create a token for authentication.
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
// JWT Authentication Tokens
services.AddAuthentication(auth =>
{
// This will stop Identity using Cookies and make it use JWT tokens by default.
auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = "http://mywebsite.com",
ValidIssuer = "http://mywebsite.com",
ValidateLifetime = true,
RequireExpirationTime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("rsvgy555262gthsdfrthga"))
};
options.RequireHttpsMetadata = true; // Use HTTPS to transmit the token.
});
// Admin Login Cookie
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Admin/Login"; // Url for users to login to the app
options.Cookie.Name = ".AspNetCore.Identity.Application";
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
});
services.AddControllers();
services.AddControllersWithViews();
}
谢谢,如果您能帮助cookies正常工作,我们将不胜感激。您的asp.net核心版本是什么,是5.0吗?是3.1。老实说,这太难了,我正在考虑重新开始,只用饼干。
public class AdminController : Controller
{
private UserManager<User> userManager; // Manage user accounts in DB
private IPasswordHasher<User> passwordHasher; // Hash user passwords
private SignInManager<User> signInManager; // Login
// Constructor
public AdminController(UserManager<User> usrMgr, IPasswordHasher<User> passwordHash, SignInManager<User> signinMgr)
{
userManager = usrMgr;
passwordHasher = passwordHash;
signInManager = signinMgr;
}
// Admin Login Page
[AllowAnonymous]
public IActionResult Login(string returnUrl)
{
Login login = new Login();
return View(login);
}
// Admin Login Module
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(Login login)
{
if (ModelState.IsValid)
{
User loginUser = await userManager.FindByEmailAsync(login.Email);
if (loginUser != null)
{
// Sign out any user already signed in
await signInManager.SignOutAsync();
// Sign in the new user
Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(loginUser, login.Password, false, false);
if (result.Succeeded)
{
return Redirect("/Admin"); // Send user to localhost/Admin after login
}
}
ModelState.AddModelError(nameof(login.Email), "Login Failed: Invalid Email or password");
}
return View(login);
}
// Admin Logout
public async Task<IActionResult> Logout()
{
await signInManager.SignOutAsync();
return RedirectToAction("Index");
}
// Admin Index Page
[Authorize]
public IActionResult Index()
{
return View(userManager.Users);
}
}