我有一个web api应用程序,我需要配置 Oauth 来生成令牌:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/oauth/token"),
Provider = new AuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
AllowInsecureHttp = true,
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
UserManager<IdentityUser> userManager = context.OwinContext.GetUserManager<UserManager<IdentityUser>>();
IdentityUser user;
try
{
user = await userManager.FindAsync(context.UserName, context.Password);
}
catch
{
// Could not retrieve the user due to error.
context.SetError("server_error");
context.Rejected();
return;
}
if (user != null)
{
ClaimsIdentity identity = await userManager.CreateIdentityAsync(
user,
DefaultAuthenticationTypes.ExternalBearer);
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "Invalid User Id or password'");
context.Rejected();
}
}
我使用Advanced Rest Client
chrome扩展来测试令牌的生成,如下所示:
如何解决此问题?