/// <summary>
        /// Login using the specified credentials.
        /// </summary>
        /// <param name="credentials">The credentials.</param>
        /// <returns>Refresh Token</returns>
        public async Task Login(string username, string password)
        {
            if (this.AuthorizationEndpoint == null)
            {
                var info = await this.Info.GetInfo();

                this.AuthorizationEndpoint = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", info.AuthorizationEndpoint.TrimEnd('/'), "/oauth/token"));
            }

            var authUrl = new Uri(AuthorizationEndpoint.ToString().TrimEnd('/') + "/oauth/token");

            //var client = new HttpClient();
            var data = new List <KeyValuePair <string, string> >();

            data.Add(new KeyValuePair <string, string>("grant_type", "password"));
            data.Add(new KeyValuePair <string, string>("username", username));
            data.Add(new KeyValuePair <string, string>("password", password));

            this.token = await PostFormUrlEncoded(authUrl.AbsoluteUri, data);

            //if (context.IsLoggedIn)
            {
                //// Workaround for HCF. Some CC requests (e.g. dev role + bind route, update app, etc..) will fail the first time after login with 401.
                //// Calling the CC's /v2/info endpoint will prevent this misbehavior.
                await this.Info.GetInfo();
            }
        }
예제 #2
0
        public async Task <AuthenticationContext> Login(string refreshToken)
        {
            if (this.AuthorizationEndpoint == null)
            {
                var info = await this.V2.Info.GetInfo();

                this.AuthorizationEndpoint = new Uri(info.AuthorizationEndpoint);
            }

            var authUrl = new Uri(AuthorizationEndpoint.ToString().TrimEnd('/') + "/oauth/token");

            this.UAAClient = new UAAClient(authUrl, this.HttpProxy, this.SkipCertificateValidation);

            var context = await this.UAAClient.Login(refreshToken);

            await this.V2.Login(refreshToken);

            if (context.IsLoggedIn)
            {
                //// Workaround for HCF. Some CC requests (e.g. dev role + bind route, update app, etc..) will fail the first time after login with 401.
                //// Calling the CC's /v2/info endpoint will prevent this misbehavior.
                await this.V2.Info.GetInfo();
            }

            return(context);
        }
        /// <summary>
        /// Login using the specified raw token.
        /// </summary>
        /// <param name="refreshToken">A raw token.</param>
        /// <returns>Token Object</returns>
        public async Task Login(string refreshToken)
        {
            if (this.AuthorizationEndpoint == null)
            {
                var info = await this.Info.GetInfo();

                this.AuthorizationEndpoint = new Uri(info.AuthorizationEndpoint);
            }

            var data = new List <KeyValuePair <string, string> >();

            data.Add(new KeyValuePair <string, string>("grant_type", "refresh_token"));
            data.Add(new KeyValuePair <string, string>("refresh_token", refreshToken));

            var authUrl = new Uri(AuthorizationEndpoint.ToString().TrimEnd('/') + "/oauth/token");

            this.token = await PostFormUrlEncoded(authUrl.AbsoluteUri, data);

            //if (context.IsLoggedIn)
            {
                //// Workaround for HCF. Some CC requests (e.g. dev role + bind route, update app, etc..) will fail the first time after login with 401.
                //// Calling the CC's /v2/info endpoint will prevent this misbehavior.
                await this.Info.GetInfo();
            }

            //return context;
        }
예제 #4
0
        public string GetAuthorizationEndpoint(string tenantId)
        {
            if (!AuthorizationEndpoint.Contains("/common/"))
            {
                throw new InvalidOperationException("Invalid authorization_endpoint: " + AuthorizationEndpoint);
            }

            return(String.IsNullOrEmpty(tenantId) ? AuthorizationEndpoint : AuthorizationEndpoint.Replace("/common/", String.Format("/{0}/", tenantId)));
        }
예제 #5
0
        /// <summary>
        /// 根据关联的系统登录终结点查询指定名称的关联验证终结点
        /// </summary>
        /// <param name="systemLoginEndpointId"></param>
        /// <param name="authorizationName"></param>
        /// <returns></returns>
        public async Task <AuthorizationEndpoint> QueryBySystemLoginEndpointRelation(Guid systemLoginEndpointId, string authorizationName)
        {
            AuthorizationEndpoint result = null;
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateReadForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;

                    command.CommandText = string.Format(@"  SELECT 
	                                                             {0}
                                                            FROM [DBO].[AUTHORIZATIONENDPOINT] A JOIN DBO.SYSTEMLOGINENDPOINTAUTHORIZATIONENDPOINTRELATION R
                                                            ON(A.ID = R.AUTHORIZATIONENDPOINTID AND R.SYSTEMLOGINENDPOINTID = @systemLoginEndpointId
	                                                            AND A.Name = @name
                                                            );", StoreHelper.GetAuthorizationEndpointStoreSelectFields("A"));

                    parameter = new SqlParameter("@systemLoginEndpointId", SqlDbType.UniqueIdentifier)
                    {
                        Value = systemLoginEndpointId
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@name", SqlDbType.NVarChar, 500)
                    {
                        Value = authorizationName
                    };
                    command.Parameters.Add(parameter);

                    await command.PrepareAsync();

                    SqlDataReader reader = null;


                    await using (reader = await command.ExecuteReaderAsync())
                    {
                        if (await reader.ReadAsync())
                        {
                            result = new AuthorizationEndpoint();
                            StoreHelper.SetAuthorizationEndpointSelectFields(result, reader, "A");
                        }
                        await reader.CloseAsync();
                    }
                }
            });

            return(result);
        }
예제 #6
0
        /// <summary>
        /// 为终结点从DbDataReader中赋值
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="reader"></param>
        /// <param name="prefix"></param>
        public static void SetAuthorizationEndpointSelectFields(AuthorizationEndpoint endpoint, DbDataReader reader, string prefix)
        {
            endpoint.ID = (Guid)reader[string.Format("{0}id", prefix)];

            if (reader[string.Format("{0}name", prefix)] != DBNull.Value)
            {
                endpoint.Name = reader[string.Format("{0}name", prefix)].ToString();
            }
            if (reader[string.Format("{0}thirdpartytype", prefix)] != DBNull.Value)
            {
                endpoint.ThirdPartyType = reader[string.Format("{0}thirdpartytype", prefix)].ToString();
            }

            if (reader[string.Format("{0}thirdpartypostexecutetype", prefix)] != DBNull.Value)
            {
                endpoint.ThirdPartyPostExecuteType = reader[string.Format("{0}thirdpartypostexecutetype", prefix)].ToString();
            }

            if (reader[string.Format("{0}thirdpartyconfiguration", prefix)] != DBNull.Value)
            {
                endpoint.ThirdPartyConfiguration = reader[string.Format("{0}thirdpartyconfiguration", prefix)].ToString();
            }

            if (reader[string.Format("{0}thirdpartypostconfiguration", prefix)] != DBNull.Value)
            {
                endpoint.ThirdPartyPostConfiguration = reader[string.Format("{0}thirdpartypostconfiguration", prefix)].ToString();
            }

            if (reader[string.Format("{0}keepthirdpartytoken", prefix)] != DBNull.Value)
            {
                endpoint.KeepThirdPartyToken = (bool)reader[string.Format("{0}keepthirdpartytoken", prefix)];
            }

            if (reader[string.Format("{0}authmodes", prefix)] != DBNull.Value)
            {
                var strModes   = reader[string.Format("{0}authmodes", prefix)].ToString();
                var arrayModes = strModes.Split(',');
                var intModes   = new List <int>();
                foreach (var arrayItem in arrayModes)
                {
                    intModes.Add(Convert.ToInt32(arrayItem));
                }

                endpoint.AuthModes = intModes.ToArray();
            }


            if (reader[string.Format("{0}createtime", prefix)] != DBNull.Value)
            {
                endpoint.CreateTime = (DateTime)reader[string.Format("{0}createtime", prefix)];
            }

            if (reader[string.Format("{0}modifytime", prefix)] != DBNull.Value)
            {
                endpoint.ModifyTime = (DateTime)reader[string.Format("{0}modifytime", prefix)];
            }
        }
예제 #7
0
        /// <inheritdoc />
        public override void Validate()
        {
            base.Validate();

            if (_environment == SuperOfficeAuthenticationEnvironment.Production &&
                !AuthorizationEndpoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                throw new NotSupportedException("Production environment requires secure endpoints, i.e. begins with 'https://'.");
            }

            if (ConfigurationManager == null)
            {
                throw new InvalidOperationException($"Provide {nameof(Authority)}, {nameof(MetadataAddress)}, or {nameof(ConfigurationManager)} to {nameof(SuperOfficeAuthenticationOptions)}.");
            }
        }
예제 #8
0
        /// <summary>
        /// 通过ID进行查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <AuthorizationEndpoint> QueryById(Guid id)
        {
            AuthorizationEndpoint result = null;
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateReadForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;

                    command.CommandText = string.Format(@"SELECT {0} FROM [dbo].[AuthorizationEndpoint] WHERE id=@id;", StoreHelper.GetAuthorizationEndpointStoreSelectFields(string.Empty));
                    parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = id
                    };
                    command.Parameters.Add(parameter);

                    await command.PrepareAsync();

                    SqlDataReader reader = null;


                    await using (reader = await command.ExecuteReaderAsync())
                    {
                        if (await reader.ReadAsync())
                        {
                            result = new AuthorizationEndpoint();
                            StoreHelper.SetAuthorizationEndpointSelectFields(result, reader, string.Empty);
                        }
                        await reader.CloseAsync();
                    }
                }
            });

            return(result);
        }
예제 #9
0
        private AuthorisationResult AuthorizeV1()
        {
            if (!IsCurrentUserAuthorized())
            {
                if (!HaveVerificationCode())
                {
                    string ret = null;

                    string response = RequestToken();

                    if (response.Length > 0)
                    {
                        //response contains token and token secret. We only need the token.
                        NameValueCollection qs = HttpUtility.ParseQueryString(response);

                        if (qs[OAuthCallbackConfirmedKey] != null)
                        {
                            if (qs[OAuthCallbackConfirmedKey] != "true")
                            {
                                throw new Exception("OAuth callback not confirmed.");
                            }
                        }

                        if (qs[OAuthTokenKey] != null)
                        {
                            ret = AuthorizationEndpoint.ToString() + "?" + OAuthTokenKey + "=" + qs[OAuthTokenKey];

                            AuthToken   = qs[OAuthTokenKey];
                            TokenSecret = qs[OAuthTokenSecretKey];
                            SaveTokenCookie("_request");
                        }
                    }

                    HttpContext.Current.Response.Redirect(ret, true);

                    return(AuthorisationResult.RequestingCode);
                }

                ExchangeRequestTokenForToken();
            }

            return(AuthorisationResult.Authorized);
        }
예제 #10
0
        public void Merge(OpenidEndpoints endpoints)
        {
            if (endpoints == null)
            {
                return;
            }

            if (Issuer.IsEmpty())
            {
                Issuer = endpoints.Issuer;
            }
            if (JwksUri.IsEmpty())
            {
                JwksUri = endpoints.JwksUri;
            }
            if (AuthorizationEndpoint.IsEmpty())
            {
                AuthorizationEndpoint = endpoints.AuthorizationEndpoint;
            }
            if (TokenEndpoint.IsEmpty())
            {
                TokenEndpoint = endpoints.TokenEndpoint;
            }
            if (UserinfoEndpoint.IsEmpty())
            {
                UserinfoEndpoint = endpoints.UserinfoEndpoint;
            }
            if (EndSessionEndpoint.IsEmpty())
            {
                EndSessionEndpoint = endpoints.EndSessionEndpoint;
            }
            if (CheckSessionIframe.IsEmpty())
            {
                CheckSessionIframe = endpoints.CheckSessionIframe;
            }
            if (RevocationEndpoint.IsEmpty())
            {
                RevocationEndpoint = endpoints.RevocationEndpoint;
            }
        }
 public string GetAuthorizationEndpoint(string tenantId)
 {
     // ADFS URLs may not contain /common/. Replace /common/ with tenantID only if /common/ is present.
     return(String.IsNullOrEmpty(tenantId) ? AuthorizationEndpoint : AuthorizationEndpoint.Replace("/common/", String.Format("/{0}/", tenantId)));
 }
예제 #12
0
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public async Task Update(AuthorizationEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;

                    command.CommandText = @"update [dbo].[AuthorizationEndpoint]
                                                   set name = @name
                                                      ,thirdpartytype=@thirdpartytype
                                                      ,thirdpartypostexecutetype=@thirdpartypostexecutetype
                                                      ,thirdpartyconfiguration=@thirdpartyconfiguration
                                                      ,thirdpartypostconfiguration=@thirdpartypostconfiguration
                                                      ,keepthirdpartytoken=@keepthirdpartytoken
                                                      ,authmodes=@authmodes
                                                      ,modifytime = getutcdate()
                                                   where id = @id";
                    parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                    {
                        Value = endpoint.ID
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.Name
                    };
                    command.Parameters.Add(parameter);


                    parameter = new SqlParameter("@thirdpartytype", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.ThirdPartyType
                    };
                    command.Parameters.Add(parameter);

                    object thirdPartyPostExecuteType = DBNull.Value;
                    if (endpoint.ThirdPartyPostExecuteType != null)
                    {
                        thirdPartyPostExecuteType = endpoint.ThirdPartyPostExecuteType;
                    }
                    parameter = new SqlParameter("@thirdpartypostexecutetype", SqlDbType.VarChar, 150)
                    {
                        Value = thirdPartyPostExecuteType
                    };
                    command.Parameters.Add(parameter);


                    parameter = new SqlParameter("@thirdpartyconfiguration", SqlDbType.NVarChar, endpoint.ThirdPartyConfiguration.Length)
                    {
                        Value = endpoint.ThirdPartyConfiguration
                    };
                    command.Parameters.Add(parameter);

                    object thirdPartyPostConfiguration    = DBNull.Value;
                    int thirdPartyPostConfigurationLength = 100;
                    if (endpoint.ThirdPartyPostConfiguration != null)
                    {
                        thirdPartyPostConfiguration       = endpoint.ThirdPartyPostConfiguration;
                        thirdPartyPostConfigurationLength = endpoint.ThirdPartyPostConfiguration.Length;
                    }
                    parameter = new SqlParameter("@thirdpartypostconfiguration", SqlDbType.NVarChar, thirdPartyPostConfigurationLength)
                    {
                        Value = thirdPartyPostConfiguration
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@keepthirdpartytoken", SqlDbType.Bit)
                    {
                        Value = endpoint.KeepThirdPartyToken
                    };
                    command.Parameters.Add(parameter);

                    var strAuthmodes = await endpoint.AuthModes.ToDisplayString(async(item) => await Task.FromResult(item.ToString()), async() => await Task.FromResult(","));

                    parameter = new SqlParameter("@authmodes", SqlDbType.VarChar, strAuthmodes.Length)
                    {
                        Value = strAuthmodes
                    };
                    command.Parameters.Add(parameter);

                    await command.PrepareAsync();

                    await command.ExecuteNonQueryAsync();
                }
            });
        }
예제 #13
0
        /// <summary>
        /// 根据关联的系统登录终结点分页查询匹配名称的关联验证终结点
        /// </summary>
        /// <param name="systemLoginEndpointId"></param>
        /// <param name="authorizationName"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task <QueryResult <AuthorizationEndpoint> > QueryBySystemLoginEndpointRelationPage(Guid systemLoginEndpointId, string authorizationName, int page, int pageSize)
        {
            QueryResult <AuthorizationEndpoint> result = new QueryResult <AuthorizationEndpoint>();
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, true, false, _dbConnectionFactory.CreateReadForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    CommandText = string.Format(@"SET @currentpage = @page;
                                                    SELECT @count = COUNT(*)
                                                    FROM [DBO].[AUTHORIZATIONENDPOINT] A JOIN DBO.SYSTEMLOGINENDPOINTAUTHORIZATIONENDPOINTRELATION R
                                                            ON(A.ID = R.AUTHORIZATIONENDPOINTID AND R.SYSTEMLOGINENDPOINTID = @systemLoginEndpointId
	                                                            AND A.Name like @name)

                                                    IF @pagesize * @page >= @count
                                                    BEGIN
                                                        SET @currentpage = @count / @pagesize;
                                                        IF @count % @pagesize <> 0
                                                        BEGIN
                                                            SET @currentpage = @currentpage + 1;
                                                        END;
                                                        IF @currentpage = 0
                                                            SET @currentpage = 1;
                                                    END;
                                                    ELSE IF @page < 1
                                                    BEGIN
                                                        SET @currentpage = 1;
                                                    END;

                                                    SELECT 
	                                                             {0}
                                                            FROM [DBO].[AUTHORIZATIONENDPOINT] A JOIN DBO.SYSTEMLOGINENDPOINTAUTHORIZATIONENDPOINTRELATION R
                                                            ON(A.ID = R.AUTHORIZATIONENDPOINTID AND R.SYSTEMLOGINENDPOINTID = @systemLoginEndpointId
	                                                            AND A.Name like @name)
                                                    ORDER BY [Asequence] OFFSET (@pagesize * (@currentpage - 1)) ROWS FETCH NEXT @pagesize ROWS ONLY;", StoreHelper.GetAuthorizationEndpointStoreSelectFields("A")),
                    Transaction = sqlTran
                })
                {
                    var parameter = new SqlParameter("@page", SqlDbType.Int)
                    {
                        Value = page
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@pagesize", SqlDbType.Int)
                    {
                        Value = pageSize
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@count", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@currentpage", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@systemLoginEndpointId", SqlDbType.UniqueIdentifier)
                    {
                        Value = systemLoginEndpointId
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@name", SqlDbType.NVarChar, 500)
                    {
                        Value = $"{authorizationName.ToSqlLike()}%"
                    };
                    command.Parameters.Add(parameter);
                    await command.PrepareAsync();
                    SqlDataReader reader = null;

                    await using (reader = await command.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            var authorizationEndpoint = new AuthorizationEndpoint();
                            StoreHelper.SetAuthorizationEndpointSelectFields(authorizationEndpoint, reader, "A");
                            result.Results.Add(authorizationEndpoint);
                        }
                        await reader.CloseAsync();
                        result.TotalCount  = (int)command.Parameters["@count"].Value;
                        result.CurrentPage = (int)command.Parameters["@currentpage"].Value;
                    }
                };
            });

            return(result);
        }
예제 #14
0
        /// <summary>
        /// 通过Name进行分页查询
        /// </summary>
        /// <param name="authorizationName"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task <QueryResult <AuthorizationEndpoint> > QueryByPage(string authorizationName, int page, int pageSize)
        {
            QueryResult <AuthorizationEndpoint> result = new QueryResult <AuthorizationEndpoint>();
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, true, false, _dbConnectionFactory.CreateReadForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    CommandText = string.Format(@"SET @currentpage = @page;
                                                    SELECT @count = COUNT(*)
                                                    FROM [dbo].[AuthorizationEndpoint]
                                                    WHERE [name] LIKE @name                                                          
                                                    IF @pagesize * @page >= @count
                                                    BEGIN
                                                        SET @currentpage = @count / @pagesize;
                                                        IF @count % @pagesize <> 0
                                                        BEGIN
                                                            SET @currentpage = @currentpage + 1;
                                                        END;
                                                        IF @currentpage = 0
                                                            SET @currentpage = 1;
                                                    END;
                                                    ELSE IF @page < 1
                                                    BEGIN
                                                        SET @currentpage = 1;
                                                    END;

                                                    SELECT {0}
                                                    FROM [dbo].[AuthorizationEndpoint]
                                                    WHERE [name] LIKE @name
                                                    ORDER BY sequence OFFSET (@pagesize * (@currentpage - 1)) ROWS FETCH NEXT @pagesize ROWS ONLY;", StoreHelper.GetAuthorizationEndpointStoreSelectFields(string.Empty)),
                    Transaction = sqlTran
                })
                {
                    var parameter = new SqlParameter("@page", SqlDbType.Int)
                    {
                        Value = page
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@pagesize", SqlDbType.Int)
                    {
                        Value = pageSize
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@count", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@currentpage", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.Output
                    };
                    command.Parameters.Add(parameter);
                    parameter = new SqlParameter("@name", SqlDbType.NVarChar, 500)
                    {
                        Value = $"{authorizationName.ToSqlLike()}%"
                    };
                    command.Parameters.Add(parameter);
                    await command.PrepareAsync();
                    SqlDataReader reader = null;


                    await using (reader = await command.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            var authorizationEndpoint = new AuthorizationEndpoint();
                            StoreHelper.SetAuthorizationEndpointSelectFields(authorizationEndpoint, reader, string.Empty);
                            result.Results.Add(authorizationEndpoint);
                        }
                        await reader.CloseAsync();
                        result.TotalCount  = (int)command.Parameters["@count"].Value;
                        result.CurrentPage = (int)command.Parameters["@currentpage"].Value;
                    }
                };
            });

            return(result);
        }
예제 #15
0
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public async Task Add(AuthorizationEndpoint endpoint)
        {
            await DBTransactionHelper.SqlTransactionWorkAsync(DBTypes.SqlServer, false, false, _dbConnectionFactory.CreateAllForSystemToken(), async (conn, transaction) =>
            {
                SqlTransaction sqlTran = null;
                if (transaction != null)
                {
                    sqlTran = (SqlTransaction)transaction;
                }
                await using (SqlCommand command = new SqlCommand()
                {
                    Connection = (SqlConnection)conn,
                    CommandType = CommandType.Text,
                    Transaction = sqlTran,
                })
                {
                    SqlParameter parameter;
                    if (endpoint.ID == Guid.Empty)
                    {
                        command.CommandText = @"insert into [dbo].[AuthorizationEndpoint]
                                                  (
                                                       [id]
                                                      ,[name]
                                                      ,[thirdpartytype]
                                                      ,[thirdpartypostexecutetype]
                                                      ,[thirdpartyconfiguration]
                                                      ,[thirdpartypostconfiguration]
                                                      ,[keepthirdpartytoken]
                                                      ,[authmodes]
                                                      ,[createtime]
                                                      ,[modifytime]
	                                              )
	                                              values
                                                  (
	                                                  default
	                                                  ,@name
                                                      ,@thirdpartytype
                                                      ,@thirdpartypostexecutetype
                                                      ,@thirdpartyconfiguration
                                                      ,@thirdpartypostconfiguration
	                                                  ,@keepthirdpartytoken
                                                      ,@authmodes
	                                                  ,getutcdate()
	                                                  ,getutcdate()
	                                              )
                                                select @newid =[id] from [dbo].[AuthorizationEndpoint] where [sequence] = SCOPE_IDENTITY()";
                        parameter           = new SqlParameter("@newid", SqlDbType.UniqueIdentifier)
                        {
                            Direction = ParameterDirection.Output
                        };
                        command.Parameters.Add(parameter);
                    }
                    else
                    {
                        command.CommandText = @"insert into [dbo].[AuthorizationEndpoint]
                                                  (
                                                       [id]
                                                      ,[name]
                                                      ,[thirdpartytype]
                                                      ,[thirdpartypostexecutetype]
                                                      ,[thirdpartyconfiguration]
                                                      ,[thirdpartypostconfiguration]
                                                      ,[keepthirdpartytoken]
                                                      ,[authmodes]
                                                      ,[createtime]
                                                      ,[modifytime]
	                                              )
	                                              values
                                                  (
	                                                  @id
	                                                  ,@name
                                                      ,@thirdpartytype
                                                      ,@thirdpartypostexecutetype
                                                      ,@thirdpartyconfiguration
                                                      ,@thirdpartypostconfiguration
	                                                  ,@keepthirdpartytoken
                                                      ,@authmodes
	                                                  ,getutcdate()
	                                                  ,getutcdate()
	                                              )
                                             ";
                        parameter           = new SqlParameter("@id", SqlDbType.UniqueIdentifier)
                        {
                            Value = endpoint.ID
                        };
                        command.Parameters.Add(parameter);
                    }
                    parameter = new SqlParameter("@name", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.Name
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@thirdpartytype", SqlDbType.VarChar, 150)
                    {
                        Value = endpoint.ThirdPartyType
                    };
                    command.Parameters.Add(parameter);

                    object thirdPartyPostExecuteType = DBNull.Value;
                    if (endpoint.ThirdPartyPostExecuteType != null)
                    {
                        thirdPartyPostExecuteType = endpoint.ThirdPartyPostExecuteType;
                    }
                    parameter = new SqlParameter("@thirdpartypostexecutetype", SqlDbType.VarChar, 150)
                    {
                        Value = thirdPartyPostExecuteType
                    };
                    command.Parameters.Add(parameter);


                    parameter = new SqlParameter("@thirdpartyconfiguration", SqlDbType.NVarChar, endpoint.ThirdPartyConfiguration.Length)
                    {
                        Value = endpoint.ThirdPartyConfiguration
                    };
                    command.Parameters.Add(parameter);

                    object thirdPartyPostConfiguration    = DBNull.Value;
                    int thirdPartyPostConfigurationLength = 100;
                    if (endpoint.ThirdPartyPostConfiguration != null)
                    {
                        thirdPartyPostConfiguration       = endpoint.ThirdPartyPostConfiguration;
                        thirdPartyPostConfigurationLength = endpoint.ThirdPartyPostConfiguration.Length;
                    }
                    parameter = new SqlParameter("@thirdpartypostconfiguration", SqlDbType.NVarChar, thirdPartyPostConfigurationLength)
                    {
                        Value = thirdPartyPostConfiguration
                    };
                    command.Parameters.Add(parameter);

                    parameter = new SqlParameter("@keepthirdpartytoken", SqlDbType.Bit)
                    {
                        Value = endpoint.KeepThirdPartyToken
                    };
                    command.Parameters.Add(parameter);



                    var strAuthmodes = await endpoint.AuthModes.ToDisplayString(async(item) => await Task.FromResult(item.ToString()), async() => await Task.FromResult(","));

                    parameter = new SqlParameter("@authmodes", SqlDbType.VarChar, strAuthmodes.Length)
                    {
                        Value = strAuthmodes
                    };
                    command.Parameters.Add(parameter);

                    await command.PrepareAsync();

                    try
                    {
                        await command.ExecuteNonQueryAsync();
                    }
                    catch (SqlException ex)
                    {
                        if (ex == null)
                        {
                            throw;
                        }
                        //违反主键约束
                        if (ex.Number == 2601)
                        {
                            var fragment = new TextFragment()
                            {
                                Code = TextCodes.ExistAuthorizationEndpointByName,
                                DefaultFormatting = "验证终结点数据中存在相同名称\"{0}\"数据",
                                ReplaceParameters = new List <object>()
                                {
                                    endpoint.Name
                                }
                            };

                            throw new UtilityException((int)Errors.ExistAuthorizationEndpointByName, fragment);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    //如果用户未赋值ID则创建成功后返回ID
                    if (endpoint.ID == Guid.Empty)
                    {
                        endpoint.ID = (Guid)command.Parameters["@newid"].Value;
                    }
                    ;
                }
            });
        }