首先,我想告诉那些将这个问题标记为复制或存在的人,我已经看到解决方案存在,但在我的案例中没有人帮助我。
我正在使用我的自定义模型来注册用户,并且在生成令牌时,用户输入的凭据将匹配我的自定义模型中的记录,如果用户存在则返回令牌,如果不是,则返回例外。 这是我的自定义模型类。
public class userregistration
{
public int ID { get; set; }
[Required]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
这是我的 OAuthAuthrizationServerProvider
public class MyAutorization : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult(0);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (RegistrationRepos repo = new RegistrationRepos())
{
userregistration user = await repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
在上一节中,我从 RegistrationRepos 调用FindUser方法,该方法将通过将凭证与现有记录进行比较来返回用户。
RegistrationRepos类在这里
public class RegistrationRepos : IDisposable
{
private MyContext context = new MyContext();
protected DbSet<userregistration> DbSet { get; set; }
public RegistrationRepos()
{
DbSet = context.Set<userregistration>();
}
public async Task<userregistration> FindUser(string userName, string password)
{
var user = await DbSet.FirstOrDefaultAsync(x => x.UserName == userName && x.Password == password);
return user;
}
public void Dispose()
{
context.Dispose();
}
}
当我调试解决方案时,如果凭证匹配则用户返回正常,并且如果凭证不匹配则返回Null,这一切都正常工作但是不是生成令牌而是返回 {“error” : “invalid_grant”}
MY Owing Startup class is here.
public class owinstartup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // enables cors origin request
var myProvider = new MyAutorization();
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
Provider = myProvider
};
app.UseOAuthAuthorizationServer(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
}
场景背后的问题是什么?