我有一个MVC和一个Web API项目,使用ASP.NET MVC Web API身份(OWIN安全性)进行身份验证。
我在Register
函数中添加了一封确认无效的电子邮件,但我不确定如何在登录前检查是否emailConfirmed = true
,因为Web API标识上没有明确的登录功能, 隐含。
我知道微软有充分的理由深度封装授权功能,但是没有办法实现这一目标吗?
请告知。
这是我的注册功能:
[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();
}
答案 0 :(得分:12)
经过大量的研究,我找到了答案。
我添加了以下代码来检查emailconfirmed = true
:
var userid = userManager.FindByEmail(context.UserName).Id;
if (!userManager.IsEmailConfirmed(userid))
{
context.SetError("invalid_grant", "Email registration wasn't confirmed.");
return;
}
到GrantResourceOwnerCredentials
类中的ApplicationOAuthProvider.cs
函数(在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);
}
完美无缺,并且在他确认注册电子邮件之前阻止用户登录。