我有一个MVC和一个Web API项目,使用ASP.NET MVC Web API身份(OWIN安全性)进行身份验证.
我向Register函数添加了一个电子邮件确认,该函数正常工作但我不确定如何在登录之前检查emailConfirmed = true是否因为Web API Identity上没有显式的Login函数,它是隐式的.
我知道微软有充分的理由深度封装授权功能,但是没有办法实现这一目标吗?
请指教.
这是我的注册功能:
[AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.Email,Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user,model.Password); if (!result.Succeeded) { return GetErrorResult(result); } try { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute",new { userId = user.Id,code = code })); var email = new Email(); email.To = user.Email; email.From = "info@mycompany.com"; email.Subject = "Please confirm your account"; email.Body = "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"; JsonSerializerSettings settings = new JsonSerializerSettings(); settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var data = JsonConvert.SerializeObject(email); WebClient client = new WebClient(); client.Headers.Add(HttpRequestHeader.ContentType,"application/json"); var resp = client.UploadString(@"http:...",data); } catch (Exception ex) { throw new Exception(ex.ToString()); } return Ok(); }
@R_502_323@
经过大量的研究,我找到了答案.
我添加了以下代码来检查emailconfirmed = true:
var userid = userManager.FindByEmail(context.UserName).Id; if (!userManager.IsEmailConfirmed(userid)) { context.SetError("invalid_grant","Email registration wasn't confirmed."); return; }
到ApplicationOAuthProvider.cs类中的GrantResourceOwnerCredentials函数(在Provider文件夹下).
这是整个功能:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password); if (user == null) { context.SetError("invalid_grant","The user name or password is incorrect."); return; } ////Added code here var userid = userManager.FindByEmail(context.UserName).Id; if (!userManager.IsEmailConfirmed(userid)) { context.SetError("invalid_grant","Email registration wasn't confirmed."); return; } //// ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); }