简体   繁体   English

获取访问令牌Asp.NET Web Api 2

[英]Get Access Token Asp.NET Web Api 2

I'm having trouble problem with web api 2. Web API 2出现问题。

I'm using vs2015 and have developed my project on asp.net mvc single page template that use knockout and sammy to get/authorize identity through owin middleware. 我正在使用vs2015,并在asp.net mvc单页模板上开发了我的项目,该模板使用剔除和sammy通过owin中间件来获取/授权身份。

When I request for access token via default single page app.js, that is working well but if I try to get a token via postman ( grant_type=password&username=admin@mail.com&password=1234 ) that returns invalid_cliend error. 当我通过默认的单页app.js请求访问令牌时,效果很好,但是如果我尝试通过邮递员( grant_type=password&username=admin@mail.com&password=1234 )获取令牌,则会返回invalid_cliend错误。

{
  "error": "invalid_client"
}

Provider : 提供者:

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 : 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; }

I need your help. 我需要你的帮助。

I think that you must override ValidateClientAuthentication instead of ValidateClientRedirectUri when you want use a grant of type password(grant_type=password). 我认为,当您要使用类型为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

}

The solution for others : 其他解决方案:

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.");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM