Exemple #1
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    bool isValid = false;
                    isValid = context.ClientId == "1235" && clientSecret == "6779ef20e75817b79602" ? true : false;

                    if (isValid)
                    {
                        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        oAuthIdentity.AddClaim(new Claim("ClientID", context.ClientId));
                        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    else
                    {
                        context.SetError("Error", "Credentials not valid");
                    }
                }
                catch (Exception)
                {
                    context.SetError("Error", "internal server error");
                }
            }));
        }
Exemple #2
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    bool isValid = false;
                    isValid = true; //This should be the Service/DB call to validate the client id, client secret.
                                    //ValidateApp(context.ClientId, clientSecret);

                    if (isValid)
                    {
                        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                        oAuthIdentity.AddClaim(new Claim("ClientID", context.ClientId));
                        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                        context.Validated(ticket);
                    }
                    else
                    {
                        context.SetError("cannot authentication ");
                        // logger.Error(string.Format("GrantResourceOwnerCredentials(){0}Credentials not valid for ClientID : {1}.", Environment.NewLine, context.ClientId));
                    }
                }
                catch (Exception)
                {
                    context.SetError("Error", "internal server error");
                    //  logger.Error(string.Format("GrantResourceOwnerCredentials(){0}Returned tuple is null for ClientID : {1}.", Environment.NewLine, context.ClientId));
                }
            }));
        }
Exemple #3
0
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ObjectId.TryParse(context.ClientId, out var mongoObjectId))
            {
                context.SetError("invalid_request");
                return;
            }
            var client = await _clientManager.FindClientByIdAsync(context.ClientId);

            if (client == null || !client.IsActive)
            {
                context.SetError("invalid_client");
                return;
            }
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType, client.Name, "client_application");

            oAuthIdentity.AddClaim(new Claim("client_id", context.ClientId));
            foreach (var scope in client.Scopes)
            {
                oAuthIdentity.AddClaim(new Claim(CustomClaimTypes.AuthorisedScopes, scope));
            }
            var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

            ticket.Properties.Dictionary.Add("client_id", client.Id);
            context.Validated(ticket);
        }
        /// <summary>
        /// 当grant_type=client_credentials触发该事件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            logger.Debug("GrantClientCredentials");
            string error = "invalid_grant";

            if (string.IsNullOrEmpty(context.ClientId))
            {
                context.SetError(error, "无效clientId");
            }
            else
            {
                OauClient client = Clients.ApiClients.FirstOrDefault(a => a.AppId == context.ClientId);
                if (client != null)
                {
                    //获取附加的请求参数
                    IDictionary <string, object> parameters = context.OwinContext.Environment;

                    int tokenLifeTime = client.RefreshTokenLifeTime;
                    var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                    if (parameters != null)
                    {
                        //foreach (var item in parameters)
                        //{
                        //    //添加附加凭证信息
                        //   oAuthIdentity.AddClaim(new Claim(OAuthKeys.Prefix+item.Key,item.Value.ToString()));
                        //}
                    }
                    bool validateResult = false;
                    var  oauthProps     = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        {
                            OAuthKeys.AuthPropClientId, context.ClientId
                        }
                    })
                    {
                        // Gets or sets the time at which the authentication ticket was issued.
                        IssuedUtc = DateTime.UtcNow,
                        // Gets or sets the time at which the authentication ticket expires.
                        ExpiresUtc = DateTime.UtcNow.AddMinutes(client.RefreshTokenLifeTime)
                    };
                    //替换此上下文中的票据信息,并将其标记为已验证
                    var ticket = new AuthenticationTicket(oAuthIdentity, oauthProps);
                    validateResult = context.Validated(ticket);
                    if (!validateResult)
                    {
                        context.SetError(error, "validate失败");
                    }
                }
                else
                {
                    context.SetError(error, "无效clientId");
                }
            }
            await base.GrantClientCredentials(context);
        }
Exemple #5
0
        /// <summary>
        /// 客户端授权模式 grant_type=client_credentials
        /// 生成 access_token(client_credentials 授权方式)client_id=client0&client_secret=secret0
        /// </summary>
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });//GET,POST,PUT,DELETE,PATCH,OPTIONS....

            string clientSecret = context.OwinContext.Get <string>("clientSecret");
            var    client       = Repository.clients.SingleOrDefault(t => t.clientId == context.ClientId && t.clientSecret == clientSecret);

            if (client != null)
            {
                var identity = new ClaimsIdentity(new GenericIdentity(
                                                      context.ClientId, OAuthDefaults.AuthenticationType),
                                                  context.Scope.Select(x => new Claim("urn:oauth:scope", x))
                                                  );

                var props = new AuthenticationProperties(new Dictionary <string, string> {
                    { "自定义参数0", "0" },
                    { "自定义参数1", context.ClientId }
                });//自定义输出参数

                var ticket = new AuthenticationTicket(identity, props);
                context.Validated(ticket);
            }
            else
            {
                context.SetError("invalid_client_credentials", "客户端授权失败,clientSecret不正确");
            }

            return(Task.FromResult(0));
        }
Exemple #6
0
        /// <summary>
        /// Client Credentialsグラント種別のカスタム認証ロジック
        /// TokenEndpointPathへの grant_type=client_credentials アクセスは、こちらに到達する。
        /// ・client_id, client_secret の検証は、(2) ValidateClientAuthenticationで済。
        /// ・クライアントは"access_token"を取得する。
        /// </summary>
        /// <param name="context">OAuthGrantClientCredentialsContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn343586.aspx"/>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ASPNETIdentityConfig.EnableClientCredentialsGrantType)
            {
                throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableClientCredentialsGrantType);
            }

            // ASP.Net MVC: Creating an OAuth client credentials grant type token endpoint
            // http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-client-credentials-grant-type-token-endpoint
            //var client = clientService.GetClient(context.ClientId);

            // WEB API 2 OAuth Client Credentials Authentication, How to add additional parameters? - Stack Overflow
            // http://stackoverflow.com/questions/29132031/web-api-2-oauth-client-credentials-authentication-how-to-add-additional-paramet

            try
            {
                ApplicationUser        user = null;
                ApplicationUserManager userManager
                    = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

                // client_idに対応するApplicationUserを取得する。
                user = await userManager.FindByNameAsync(
                    OAuth2ProviderHelper.GetInstance().GetClientName(context.ClientId));

                if (user == null)
                {
                    // *.configに定義したclient_idの場合は、アカウントが存在しない。
                    // その場合、どうするか?は案件毎に検討する(既定では、既定の管理者ユーザを使用する)。
                    user = await userManager.FindByNameAsync(ASPNETIdentityConfig.AdministratorUID);

                    // ClaimsIdentityを自前で生成する場合、
                    //ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    //・・・
                }

                // ユーザーに対応するClaimsIdentityを生成する。
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ExternalBearer);

                // ClaimsIdentityに、その他、所定のClaimを追加する。
                OAuth2ProviderHelper.AddClaim(identity, context.ClientId, "", "", context.Scope);

                // 検証完了
                context.Validated(identity);

                // オペレーション・トレース・ログ出力
                Logging.MyOperationTrace(string.Format("{0}({1}) passed the 'client credentials flow' by {2}({3}).",
                                                       user.Id, user.UserName, context.ClientId, OAuth2ProviderHelper.GetInstance().GetClientName(context.ClientId)));
            }
            catch
            {
                // ユーザーを取得できませんでした。
                context.SetError(
                    "server_error",
                    Resources.ApplicationOAuthBearerTokenProvider.server_error1);

                // 拒否
                context.Rejected();
            }
        }
Exemple #7
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var user = context.Request.Get <ApiV2User>("ApiUser");

            if (user == null)
            {
                context.Rejected();
                context.SetError("unauthorized_client");
                return(Task.CompletedTask);
            }

            var body = ParseBody(context.Request);

            var claims = new List <Claim>
            {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id.ToString()),
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Name),
                new Claim("client_id", body["client_id"])
            };

            void AddClaimFromBody(String name)
            {
                var val = body[name];

                if (val != null)
                {
                    claims.Add(new Claim(name, val));
                }
            }

            if (user.Segment != null)
            {
                claims.Add(new Claim("Segment", user.Segment));
            }
            if (user.TenantId != 0)
            {
                claims.Add(new Claim("TenantId", user.TenantId.ToString()));
            }

            AddClaimFromBody("session_id");
            AddClaimFromBody("state");

            var oaClaim = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            var ticket  = new AuthenticationTicket(oaClaim, new AuthenticationProperties());

            context.Validated(ticket);

            return(Task.CompletedTask);
        }
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            try
            {
                var actorId  = context.Request.Headers["ActorId"];
                var identity = _container.Resolve <ClaimsIdentityProvider>().GetActorIdentity(Guid.Parse(actorId), context.Options.AuthenticationType);
                context.Validated(identity);
                context.Request.Context.Authentication.SignIn(identity);
                return(Task.FromResult(0));
            }
            catch (Exception ex)
            {
                context.Rejected();
                context.SetError(OAuth2Constants.Errors.UnauthorizedClient, ex.Message);
            }

            return(Task.FromResult(0));
        }
        //Todo: this method, seed method
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            bool validated = false;

            OAuthClient oauthClient = context.OwinContext.Get <OAuthClient>(OwinClientKey);

            if (oauthClient != null && oauthClient.AllowedGrant == OAuthGrant.ClientCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType));

                string[] scopes = { NicksOAuthConstants.ValuesAvailableScope };
                identity.AddClaim(new Claim(NicksOAuthConstants.ScopeClaimType, String.Join(" ", scopes)));

                Guid oauthSessionValue = Guid.NewGuid();
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));

                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthClientCredentialsGrantKey, "true"));

                AuthenticationProperties properties = CreateProperties(context.ClientId);
                properties.Dictionary.Add("scope", String.Join(" ", scopes));
                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5); //Success!
                //properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.

                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
                //ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.

                context.Validated(ticket);
                //context.Ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                validated = true;
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
        }
Exemple #10
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            try
            {
                string ComputerName = context.Request.Headers.FirstOrDefault(x => x.Key == "User-Agent")
                                      .Value.FirstOrDefault();
                ComputerName += " (" + context.Request.RemoteIpAddress + ":" + context.Request.RemotePort + ")";


                var identity = new ClaimsIdentity(new GenericIdentity(ComputerName, context.Options.AuthenticationType), //var identity = new ClaimsIdentity(new GenericIdentity(ComputerName, OAuthDefaults.AuthenticationType),
                                                  context.Scope.Select(x => new Claim(ClaimTypes.System, context.ClientId))
                                                  );
                //var identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType),
                //    context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
                context.Validated(identity);
            }
            catch
            {
                context.Rejected();
                context.SetError("error: invalid_client");
            }
            return(Task.FromResult(0));
        }
        //Todo: this method, seed method
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            bool validated = false;

            OAuthClient oauthClient = context.OwinContext.Get<OAuthClient>(OwinClientKey);
            if (oauthClient != null && oauthClient.AllowedGrant == OAuthGrant.ClientCredentials)
            {
                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(context.ClientId, OAuthDefaults.AuthenticationType));
                
                string[] scopes = { NicksOAuthConstants.ValuesAvailableScope };
                identity.AddClaim(new Claim(NicksOAuthConstants.ScopeClaimType, String.Join(" ", scopes)));

                Guid oauthSessionValue=Guid.NewGuid();
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthSessionClaimKey, oauthSessionValue.ToString()));
                
                identity.AddClaim(new Claim(OAuthBearerAuthenticationWithRevocationProvider.OAuthClientCredentialsGrantKey, "true"));
                                
                AuthenticationProperties properties = CreateProperties(context.ClientId);
                properties.Dictionary.Add("scope", String.Join(" ", scopes));
                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5); //Success!
                //properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                
                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);                
                //ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                
                context.Validated(ticket);
                //context.Ticket.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5); //Hmmm... this gets overwritten.
                validated = true;
            }

            if(!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            return Task.FromResult<object>(null);
        }
Exemple #12
0
        /// <summary>
        /// Client Credentialsグラント種別のカスタム認証ロジック
        /// TokenEndpointPathへの grant_type=client_credentials アクセスは、こちらに到達する。
        /// ・client_id, client_secret の検証は、(2) ValidateClientAuthenticationで済。
        /// ・クライアントは"access_token"を取得する。
        /// </summary>
        /// <param name="context">OAuthGrantClientCredentialsContext</param>
        /// <returns>Task</returns>
        /// <see cref="https://msdn.microsoft.com/ja-jp/library/dn343586.aspx"/>
        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            if (!ASPNETIdentityConfig.EnableClientCredentialsGrantType)
            {
                throw new NotSupportedException(Resources.ApplicationOAuthBearerTokenProvider.EnableClientCredentialsGrantType);
            }

            // ASP.Net MVC: Creating an OAuth client credentials grant type token endpoint
            // http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-client-credentials-grant-type-token-endpoint
            // WEB API 2 OAuth Client Credentials Authentication, How to add additional parameters? - Stack Overflow
            // http://stackoverflow.com/questions/29132031/web-api-2-oauth-client-credentials-authentication-how-to-add-additional-paramet

            try
            {
                ApplicationUser        user = null;
                ApplicationUserManager userManager
                    = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();

                // client_idに対応するApplicationUserを取得する。
                user = await userManager.FindByNameAsync(
                    OAuth2Helper.GetInstance().GetClientName(context.ClientId));

                // ClaimsIdentity
                ClaimsIdentity identity = null;
                if (user != null)
                {
                    // User Accountの場合、

                    // ユーザーに対応するClaimsIdentityを生成する。
                    identity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                    // ClaimsIdentityに、その他、所定のClaimを追加する。
                    identity = OAuth2Helper.AddClaim(identity, context.ClientId, "", context.Scope, "");

                    // オペレーション・トレース・ログ出力
                    Logging.MyOperationTrace(
                        string.Format("{0}({1}) passed the 'client credentials flow' by {2}({3}).",
                                      user.Id, user.UserName, context.ClientId, OAuth2Helper.GetInstance().GetClientName(context.ClientId)));

                    // 検証完了
                    context.Validated(identity);
                }
                else
                {
                    // Client Accountの場合、

                    string clientName = OAuth2Helper.GetInstance().GetClientName(context.ClientId);
                    if (string.IsNullOrEmpty(clientName))
                    {
                        // 検証失敗
                        context.Rejected();
                    }
                    else
                    {
                        // ClaimsIdentityを自前で生成する。
                        identity = new ClaimsIdentity(context.Options.AuthenticationType);
                        // Name Claimを追加
                        identity.AddClaim(new Claim(ClaimTypes.Name, OAuth2Helper.GetInstance().GetClientName(context.ClientId)));
                        // ClaimsIdentityに、その他、所定のClaimを追加する。
                        identity = OAuth2Helper.AddClaim(identity, context.ClientId, "", context.Scope, "");

                        // オペレーション・トレース・ログ出力
                        Logging.MyOperationTrace(string.Format(
                                                     "Passed the 'client credentials flow' by {0}({1}).", context.ClientId, clientName));

                        // 検証完了
                        context.Validated(identity);
                    }
                }
            }
            catch
            {
                // ユーザーを取得できませんでした。
                context.SetError(
                    "server_error",
                    Resources.ApplicationOAuthBearerTokenProvider.server_error1);

                // 拒否
                context.Rejected();
            }
        }
Exemple #13
0
        public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            YiFang_CustomerComplaintEntities dbContext = new YiFang_CustomerComplaintEntities();

            try
            {
                //var data = await context.Request.ReadFormAsync();
                var    formData = context.Request.ReadFormAsync();
                string Code     = formData.Result["Code"];
                string CS       = formData.Result["CS"];
                //ClaimsIdentity oAuthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                ////用户名
                //oAuthIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, "19423657671291041"));
                ////设置授权凭据
                //AuthenticationProperties properties = CreateProperties("19423657671291041");
                //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                //context.Validated(ticket);
                //return base.GrantClientCredentials(context);
                //Code临时授权码为null执行微信登录,不为null执行钉钉登录
                if (!string.IsNullOrEmpty(Code))
                {
                    if (CS == "CS")
                    {
                        ClaimsIdentity oAuthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                        //用户名
                        oAuthIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, Code));
                        //设置授权凭据
                        AuthenticationProperties properties = CreateProperties(Code);
                        AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                        context.Validated(ticket);
                    }
                    else
                    {
                        DefaultDingTalkClient      defaultDingTalk = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
                        OapiUserGetuserinfoRequest req             = new OapiUserGetuserinfoRequest();
                        req.Code = Code;
                        req.SetHttpMethod("GET");
                        OapiUserGetuserinfoResponse execute = defaultDingTalk.Execute(req, AccessToken.GetAccessToken());
                        if (execute.Errcode != 0)
                        {
                            DingTalk.Core.Logs.LogHelper.WriteLog(execute.Body);
                            context.SetError("授权码出错啦或配置错误");
                            return(base.GrantClientCredentials(context));
                        }
                        string userid = execute.Userid;
                        var    Person = dbContext.OR_Person.FirstOrDefault(p => p.LoginName == userid);
                        if (Person == null)
                        {
                            context.SetError("该人员不在组织中");
                            return(base.GrantClientCredentials(context));
                        }
                        ClaimsIdentity oAuthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                        //用户名
                        oAuthIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, userid));
                        //设置授权凭据
                        AuthenticationProperties properties = CreateProperties(userid);
                        AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                        context.Validated(ticket);
                    }
                    //return base.GrantClientCredentials(context);
                    #region 钉钉登录
                    //if (Code=="123")
                    //{
                    //    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                    //                                                                         //010742350933650042
                    //    oAuthIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, "010742350933650042"));
                    //    AuthenticationProperties properties = CreateProperties("010742350933650042");
                    //    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    //    context.Validated(ticket);
                    //    return base.GrantClientCredentials(context);
                    //}

                    //var AccessToken= Jusoft.YiFang.Db.ThirdSystem.AccessToken.GetAccessToken();
                    //if (string.IsNullOrEmpty(AccessToken))
                    //{
                    //    context.SetError("AccessToken", $"Code【{Code}】获取token失败");
                    //    return base.GrantClientCredentials(context);
                    //}
                    //var resUserId= Jusoft.YiFang.Db.ThirdSystem.AccessToken.GetUserId(Code, AccessToken);
                    //if (resUserId.Errcode!=0)
                    //{
                    //    context.SetError("resUserId", $"Code【{Code}】"+resUserId.Errmsg);
                    //    return base.GrantClientCredentials(context);
                    //}
                    //var Person = dbContext.OR_Person.FirstOrDefault(p=>p.LoginName == resUserId.Userid);
                    //if (Person != null)
                    //{
                    //    ClaimsIdentity oAuthIdentity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
                    //    oAuthIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, Person.LoginName));
                    //    AuthenticationProperties properties = CreateProperties(Person.LoginName);
                    //    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    //    context.Validated(ticket);
                    //}
                    //else
                    //{
                    //    context.SetError("Person", $"Code【{Code}】未找到人员,请联系管理员");
                    //    return base.GrantClientCredentials(context);
                    //}
                    #endregion
                }
                else
                {
                    #region 微信登录
                    //string userid = formData.Result["username"];//用户名
                    //string password = formData.Result["password"];//密码
                    //string openid = formData.Result["openid"];//微信openid
                    //                                          //优先校验openid
                    //if (string.IsNullOrEmpty(openid))
                    //{
                    //    context.SetError("invalid_grant", "openid不合法");
                    //    return base.GrantClientCredentials(context);
                    //}
                    //if (!string.IsNullOrEmpty(userid))
                    //{
                    //    var person = dbContext.OR_Person.FirstOrDefault(k => k.LoginName == userid);
                    //    if (person == null)
                    //    {
                    //        context.SetError("1001", "门店账号信息不对,请重新输入");
                    //        return base.GrantClientCredentials(context);
                    //    }
                    //    else if (!string.IsNullOrEmpty(person.WeChatOpenId))
                    //    {
                    //        context.SetError("1001", $"门店账号信息已绑定用户,请联系管理员操作");
                    //        return base.GrantClientCredentials(context);
                    //    }
                    //    if (!dbContext.AC_SysUsers.Any(k => k.UserName == userid && k.PasswordHash == password))
                    //    {
                    //        context.SetError("1001", "门店密码信息不对,请重新输入");
                    //        return base.GrantClientCredentials(context);
                    //    }
                    //    person.WeChatOpenId = openid;
                    //    dbContext.SaveChanges();
                    //}
                    //else
                    //{
                    //    var person = dbContext.OR_Person.FirstOrDefault(k => k.WeChatOpenId == openid);
                    //    if (person == null)
                    //    {
                    //        context.SetError("1002", "用户还未绑定账号,请先绑定");
                    //        return base.GrantClientCredentials(context);
                    //    }
                    //    userid = person.LoginName;
                    //}

                    ////TODO: 校验该用户是否存在与我们自身的系统之中,若存在,则正常加入凭据信息
                    //var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
                    //oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, userid));
                    //var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
                    //context.Validated(ticket);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                context.SetError("invalid_grant", ex.ToString());
            }
            return(base.GrantClientCredentials(context));
        }