我对WebApi和MVC有点困惑。我创建了一个空白的 WebApi 项目,并选择了"个人用户帐户"作为身份验证方法。
这将生成帐户控制器:Api控制器类。这里有注册、获取用户信息等方法,但没有登录方法。
MVC 用户应该如何登录?
干杯/r3plica
默认的Web Api模板使用OWIN中间件对用户进行身份验证。
在 Startup.Auth 中.cs您可以找到有关身份验证 URL 的配置信息。
static Startup()
{
PublicClientId = "self";
UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token") - this url for get token for user,
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
在参数中使用用户名和密码向 TokenEndPointPath 发送请求后,OWIN 中间件调用方法 GrantResourceOwnerCredentials,该方法在具有用户帐户的默认模板中的 ApplicationOAuthProvider 中实现。在此方法中,您可以检查用户名和密码并授予用户访问权限。
您可以在下面找到此方法的默认实现。
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (UserManager<IdentityUser> userManager = _userManagerFactory())
{
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}