我有用于身份驗證用戶的身份驗證 API (jwt)。將其用于多個客戶端,并且現在正在添加第二個客戶端。第一個可以正常作業。我確信問題出在這一部分:
var _authorizePolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
var _serviceProvider = builder.Services.BuildServiceProvider();
var _authenticationSettings = _serviceProvider.GetService<IAuthenticationSettings>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddCookie(JwtBearerDefaults.AuthenticationScheme,
options => {
options.LoginPath = _authenticationSettings.LoginPath;
options.AccessDeniedPath = _authenticationSettings.AccessDeniedPath;
options.Events = new CookieAuthenticationEvents
{
// Check if JWT needs refreshment
OnValidatePrincipal = RefreshTokenMonitor.ValidateAsync
};
options.Cookie.Name = "MainAppCookie";
}
);
builder.Services.AddMvc(config =>
{
config.Filters.Add(new AuthorizeFilter(_authorizePolicy));
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
})
.AddViewOptions(options => options.HtmlHelperOptions.ClientValidationEnabled = true);
我有相同的代碼(Cookie 的不同名稱)是第一個應用程式,它在那里作業正常。


這里有 AccountController:
public class AccountController : Controller
{ 私有只讀 ISecurityManager _securityManager;
public AccountController(ISecurityManager securityManager)
{
_securityManager = securityManager;
}
public async Task<IActionResult> Login()
{
return View(new LoginViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid)
{
ViewBag.ErrorMessage = "Input data incorrect. Please try again";
ModelState.AddModelError(string.Empty, "Invalid login form");
return View(model);
}
if (await _securityManager.LoginUser(model.Email, model.Password))
return RedirectToLocal(returnUrl);
else
{
ViewBag.ErrorMessage = "Invalid login attempt.";
return View(model);
}
return View(model);
}
public async Task<IActionResult> AccessDenied()
{
return View();
}
[HttpGet]
[Route("account/password/forgot")]
public async Task<IActionResult> ForgotPassword()
{
return View(new ForgotPasswordModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPasswordSubmit(ForgotPasswordModel model)
{
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
[Route("account/password/confirmation")]
public async Task<IActionResult> ForgotPasswordConfirmation()
{
return View();
}
[HttpGet]
[Route("account/password/reset")]
public async Task<IActionResult> ResetPassword()
{
return View(new PasswordResetModel());
}
[HttpPost]
public async Task<IActionResult> ResetPasswordSubmit(PasswordResetModel model)
{
return RedirectToAction(nameof(Login), new { });
}
public async Task<IActionResult> LogOut()
{
//await _securityManager.LogOut();
return RedirectToAction(nameof(Login));
}
// Prevent session stealing
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
在這里你有實際的登錄:
private async Task<bool> Login(AuthResult token)
{
if(token.Token.IsNullOrEmpty())
return false;
await LogOut();
var _tokenHandler = new JwtSecurityTokenHandler();
var _tokenSettings = _jwtTokenValidationSettings.CreateTokenValidationParameters();
var _principal = _tokenHandler.ValidateToken(token.Token, _tokenSettings, out var _validatedToken);
var _identity = _principal.Identity as ClaimsIdentity;
var _securityToken = _tokenHandler.ReadToken(token.Token) as JwtSecurityToken;
var _extraClaims = _securityToken.Claims.Where(c => !_identity.Claims.Any(x => x.Type == c.Type)).ToList();
_extraClaims.Add(new Claim("jwt", token.Token));
_extraClaims.Add(new Claim("refreshToken", token.RefreshToken));
_identity.AddClaims(_extraClaims);
var _authenticationProperties = new AuthenticationProperties()
{
IssuedUtc = _identity.Claims.First(c => c.Type == JwtRegisteredClaimNames.Iat)?.Value.ToInt64().ToUnixEpochDate(),
ExpiresUtc = _identity.Claims.First(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value.ToInt64().ToUnixEpochDate(),
IsPersistent = true
};
await _httpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, _principal, _authenticationProperties);
return _identity.IsAuthenticated;
}
并進一步澄清......這是我得到的錯誤:

uj5u.com熱心網友回復:
您的LoginControler(或它的幾個操作)需要[AllowAnonymous]允許它繞過身份驗證檢查。否則,用戶將無權查看這些路線。
uj5u.com熱心網友回復:
錯誤實際上是在 AccountController 的 [AllowAnonymous] 屬性中。洗掉它并構建專案,再次添加屬性。奇跡般有效 :)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404859.html
標籤:
