[HttpPost("~/login")] public IActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Username); if (user == null) { ModelState.AddModelError("Username", "Username or password is incorrect."); } elseif (!await _userManager.IsEmailConfirmedAsync(user)) { ModelState.AddModelError("Email", "You must have a confirmed email to log in."); } elseif (!await _userManager.CheckPasswordAsync(user, model.Password)) { ModelState.AddModelError("Username", "Username or password is incorrect."); } else { // 创建一个新的身份验证票据. var ticket = await CreateTicketAsync(user);
[HttpGet("~/register")] public IActionResult Register() { return View(); }
[HttpPost("~/register")] publicasync Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, };
var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var code = await _userManager.GenerateEmailConfirmationAsync(user); var callbackUrl= Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); await _emailSender.SendEmailAsync(model.Email, "Confirm your email", $"Please confirm your account by clicking this link: {callbackUrl}");
[HttpPost("~/api/token/refresh")] publicasync Task<IActionResult> Refresh([FromForm]string refreshToken) { var info = await HttpContext.AuthenticateAsync(OpenIddictServerDefaults.AuthenticationScheme);
if (info == null) { return BadRequest(new { error = OpenIddictConstants.Errors.InvalidRequest, error_description = "The refresh token is no longer valid." }); }
var principal = info.Principal;
var user = await _userManager.GetUserAsync(principal); if (user == null) { return BadRequest(new { error = OpenIddictConstants.Errors.InvalidRequest, error_description = "The refresh token is no longer valid." }); }
// 确保刷新令牌没有被撤销. if (!await _tokenManager.ValidateAsync( principal.GetId(), principal.GetClaim(OpenIddictConstants.Claims.JwtId))) { return BadRequest(new { error = OpenIddictConstants.Errors.InvalidRequest, error_description = "The refresh token is no longer valid." }); }
// 从数据库得到客户端应用程序详细信息 var application = await _applicationManager.FindByClientIdAsync( principal.GetClaim(OpenIddictConstants.Claims.ClientId)); if (application == null) { return BadRequest(new { error = OpenIddictConstants.Errors.InvalidRequest, error_description = "The client application associated with this token is no longer valid." }); }
var identity = await _userManager.CreateIdentityAsync(user, principal.GetScopes());
var ticket = await CreateTicketAsync(application, identity, principal);
var user = await _userManager.FindByIdAsync(model.UserId); if (user == null) { // 不要显示用户不存在 return View("ResetPasswordConfirmation"); }
var decodedCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(model.Code)); var result = await _userManager.ResetPasswordAsync(user, decodedCode, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(ResetPasswordConfirmation)); }
foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); }
return View(model); }
[HttpGet("~/reset-password-confirmation")] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); }
// 从数据库检索客户机应用程序. var application = await context.HttpContext.GetOpenIddictServerApplicationAsync(); if (application == null) { thrownew InvalidOperationException("The client application cannot be retrieved."); }
// 从授权服务器设置检索用户主体. var principal = context.HttpContext.User;
// 确保允许应用程序使用指定的授权类型。 if (!await ValidateClientRedirectUriAsync(application, context.Request)) { thrownew InvalidOperationException("The grant type is not allowed for this application."); }
//注意:这个自定义令牌终端点总是忽略“scopes”参数,并根据授予的scopes/roles自动定义声明。 var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), OpenIddictServerDefaults.AuthenticationScheme); // 根据请求的自定义授权类型自定义令牌生命周期. if (string.Equals(context.Request.GrantType, "urn:custom_grant", StringComparison.OrdinalIgnoreCase)) { // Set the token expiration to 1 hour. ticket.Properties.ExpiresUtc = context.Options.SystemClock.UtcNow.AddHours(1); } else { // 将令牌过期时间设置为默认持续时间(5分钟) ticket.Properties.ExpiresUtc = context.Options.SystemClock.UtcNow.Add( context.Options.AccessTokenLifetime ?? TimeSpan.FromMinutes(5)); }
context.Logger.LogInformation("The custom token request was successfully processed.");