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

Can we use OAuth to authenticate the consumers in my Web API?

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

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

在启动中添加以下行class

    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
            }