我遇到了网络API 2的问题。
我正在使用vs2015,并在asp.net mvc单页模板上开发了我的项目,该模板使用knockout和sammy通过owin
中间件获取/授权身份。
当我通过默认单页app.js请求访问令牌时,这样做效果很好,但如果我尝试通过邮递员(grant_type=password&username=admin@mail.com&password=1234
)获取令牌,则会返回invalid_cliend
错误。
{
"error": "invalid_client"
}
提供者:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
else if (context.ClientId == "web")
{
var expectedUri = new Uri(context.Request.Uri, "/");
context.Validated(expectedUri.AbsoluteUri);
}
}
return Task.FromResult<object>(null);
}
}
Startup.Auth:
static Startup()
{
PublicClientId = "web";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
AuthorizeEndpointPath = new PathString("/Account/Authorize"),
Provider = new ApplicationOAuthProvider(PublicClientId),
//Provider = new AuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
我需要你的帮助。
答案 0 :(得分:0)
我认为当您要使用类型为password(grant_type = password)的授权时,必须覆盖ValidateClientAuthentication而不是ValidateClientRedirectUri。
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
//here simply call context.Validated() or add your client id validation logic
}
答案 1 :(得分:0)
其他人的解决方案:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// set CORS
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
//validate to get access_token
if (context.UserName == "admin@mail.com" && context.Password == "1234")
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "Invalid username or password.");
}
}