我们可以使用OAuth来验证Web API中的使用者吗?

时间:2015-02-15 16:23:08

标签: asp.net-web-api oauth

我正在开发一个Web应用程序,移动应用程序和桌面应用程序,它们都可以借助可以由ASP.NET Web API开发的单个API来访问数据。

在我的Web API中,我可以在OAuth的帮助下验证用户凭据和消费者应用程序密钥吗? 你能指导我用任何例子来实现同样的目标吗?

1 个答案:

答案 0 :(得分:1)

在启动类

中添加以下行
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

            var oauthProvider = new OAuthAuthorizationServerProvider
            {
                OnGrantResourceOwnerCredentials = async context =>
                {
                    IsValid = true;
//You can get the username and password by context.username and context.password
                    if (IsValid)
                    {
                        var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        claimsIdentity.AddClaim(new Claim("user", context.UserName));
                        context.Validated(claimsIdentity);

                        return;
                    }
                    context.Rejected();
                },
                OnValidateClientAuthentication = async context =>
                {
                    string clientId;
                    string clientSecret;
                    if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                    {
                        if (clientId == GlobalAppSettings.SystemSettings.ApplicationKey)
                        {
                            context.Validated();
                        }
                    }
                }
            };
            var oauthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/accesstoken"),
                Provider = oauthProvider,
                AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(3),
                SystemClock = new SystemClock()

            };
            app.UseOAuthAuthorizationServer(oauthOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
        }

    }

通过启动您需要授权和OAuth令牌的新OAuth APP来调用启动方法

您可以使用自托管命名空间来使用自己的主机。 否则,您可以使用Microsoft.Owin.Host.HttpListener命名空间并在不同主机中托管OAuth应用程序,如下所示

var Basesite = "http://localhost:9327/";
            var homeProcessorModel = new HomeProcessorModel();
            using (WebApp.Start<Startup>(url: Basesite))
            {
                var client = new HttpClient();
                   var form = new Dictionary<string, string>
                   {
                       {"grant_type","password"},
                       {"userName",username},
                       {"passWord",password}
                   };//If you are using grant_type as password, you have to send the username and password to OAuth protocol.
                var tokenResponse = client.PostAsync(Basesite + "accesstoken", new FormUrlEncodedContent(form)).Result;
                var token = tokenResponse.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
                //You can get the token with token.AccessToken object
            }