当您在 ASP.NET 中创建具有个人身份验证的新项目时,将使用 OAuth 提供程序创建解决方案以处理身份验证请求。
如果您查看您的解决方案,您应该会看到一个带有 ApplicationOAuthProvider 类的 Providers 文件夹。
这个类实现了在您的网站中验证您的成员的所有逻辑。
配置在启动时设置,允许您通过 OAuthOption 自定义 url 端点。
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
TokenEndPoint Path 属性定义了将触发 GrandResourceOwnerCredentials 的 GrantResourceOwnerCredentials 方法的 url。
如果你使用fiddler来认证和使用这种body
grant_type=password&username=testUserName&password=TestPassword
你应该传入以下方法:
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;
}
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);
}
其中 context.UserName 和 context.Password 使用请求中使用的数据进行设置。
确认身份后(此处使用实体框架和数据库中的一对用户名、密码),将不记名令牌发送给调用者。
然后可以使用此 Bearer 令牌对其他调用进行身份验证。
问候。