如何在Web API中使用OAuthAuthorizationServerProvider

时间:2018-06-06 08:26:30

标签: authentication asp.net-web-api owin

我已经学习了一些使用OWIN进行Web API身份验证的教程。这些教程中的大多数都定制了OAuthAuthorizationServerProvider。但是,当我调试" F11"未达到OAuthAuthorizationServerProvider类

 private void ConfigureAuth(IAppBuilder app)
        {
            //
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {


            });

            //
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);

            OAuthAuthorizationServerOptions authorizationServerOption = new OAuthAuthorizationServerOptions()
            {
                /*
                 * for demo only
                 * to enforce the Token retrieval over SSL (any non-https requests for requesting the Token will be denied)
                 * set AllowInsecureHttp = false
                */

               // AllowInsecureHttp = true,

                // Add token to the API dir
                //TokenEndpointPath = new PathString("/token"),

                //
                //Provider = new AWOAuthServerProvider(),

                // For test only 1 Day token expiry
                //AccessTokenExpireTimeSpan = TimeSpan.FromDays(1)

            };


            authorizationServerOption.AllowInsecureHttp         = true;
            authorizationServerOption.TokenEndpointPath         = new PathString("/token");
    /*break point*/
            authorizationServerOption.Provider                  = new AWOAuthServerProvider();
            authorizationServerOption.AccessTokenExpireTimeSpan = TimeSpan.FromDays(1);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(authorizationServerOption);

            // Token Generation
            app.UseOAuthAuthorizationServer(authorizationServerOption);

            //Token Consumption
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {


            });

        }    

如何在OAuthAuthorizationServerProvider类中使用或调用该方法?

 public class AWOAuthServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication
            (OAuthValidateClientAuthenticationContext context)
        {
            await Task.FromResult(context.Validated());
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext  context)
        {

            if (!ValidCredential(context.Password,context.UserName))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("username", context.UserName));

         context.Validated(identity);

        }

这是从Active Directory验证Credential的辅助方法

         private bool ValidCredential (String password,String username)
                {
                    string[] NTId           = { "", "" };
                    string   netDomain      = "";
                    string   netUserName    = "";
                    bool     isValid        = false;

                    //
                    // context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });


                    /*****************************************************************************************/
                    if (username.Equals(null) || username.Equals(""))
                    {
                        //Request client Network username
                        try
                        {
                            NTId = (HttpContext.Current.Request.LogonUserIdentity.Name)
                                                   .Replace(@"\\", @"\")
                                                   .Split('\\');
                        }
                        // error
                        catch (Exception e)
                        {
                            return false;
                        }
        }
 if (NTId.Length == 2)
                {
                    netDomain = NTId[0];
                    netUserName = NTId[1];
                }
     try
                {
                    using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, netDomain))
                    {

                        isValid = principalContext.ValidateCredentials(netUserName, password);
                    }
                }
                // error 
                catch (Exception e)
                {
                    return false;
                }


                return isValid;
    }

Thinks

0 个答案:

没有答案