Gitlab API:单元测试问题、项目和登录问题

问题描述

我必须为一个基于 gitlab api 的大学项目编写一些单元测试。几周前,我们不得不更改我们的登录功能,因为我们的旧功能不再工作并切换到 https://www.gitlab.com/oauth/token。这个东西现在可以用了,但是它搞砸了我们所有的测试,我无法再让它们运行了。

现在从测试调用方法和从控制器调用方法之间存在差异。

例如,当从控制器调用方法时,调用 https://www.gitlab.com/api/v4/projects/{projectId} 包含一个名为“Permission”的 JsonObject,但是当我使用测试中完全相同的值调用完全相同的方法时它没有它。

public async Task<int> GetAccessLevelOfUserForProject(string token,int projectId)
        {
            Console.WriteLine($"GitlabService::GetAccessLevelOfUserForProject Token: {token} projectId: {projectId}");

            var project = await rest.Get<GitlabProjects>($"https://www.gitlab.com/api/v4/projects/{projectId}",new Dictionary<string,string> { { "Authorization",$"Bearer {value}" });
            int aLevel = 0;
            if (project.Permissions.Project_access != null)
                aLevel = project.Permissions.Project_access.Access_level;
            else if(project.Permissions.Group_access != null)
                aLevel = project.Permissions.Group_access.Access_level;

            return aLevel;
        }

当我想登录时,我总是收到未经授权的 401 内容 {"error":"invalid_client","error_description":"Client authentication Failed due to unkNown client,no client authentication included,or unsupported authentication method."},尽管它使用与其他登录相同的方法并且它也使用相同的客户端身份验证。

public async Task<string> Login(LoginDTO login)
        {
            Console.WriteLine($"GitlabService::Login username:{login.Username}");
            var client = new RestClient($"{baseUrl}/oauth/token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            client.Authenticator = new HttpBasicAuthenticator({clientusername},{clientpassword});
            request.AddHeader("Content-Type",$"application/x-www-form-urlencoded");
            request.AddParameter("grant_type","password");
            request.AddParameter("username",login.Username);
            request.AddParameter("password",login.Password);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

            var data = JsonConvert.DeserializeObject<GitlabTokenData>(response.Content);
            return data.Access_token;
}

用您的客户端身份验证替换 {clientusername} 和 {clientpassword}。

这样的事情发生的情况甚至更多,我不明白为什么。也许对这个主题更熟悉的人可以帮助我?

解决方法

Gitlab 有时确实很奇怪。调用 https://www.gitlab.com/api/v4/.. 实际上是有区别的。和https://gitlab.com/api/v4/..。如果您使用 www 调用 gitlab,它会将您的请求重定向到 gitlab.com,但是它会丢弃您的所有标头(其中包含令牌),因此您将始终得到答案,就好像您甚至不会在其中给它一个令牌一样第一名。Calling www.gitlab.com

对比 Calling gitlab.com

真的很难弄清楚为什么。当你碰巧遇到同样的情况时,只需取出 Burp Suite Proxy 并通过在 HttpClient 的构造函数中设置代理来拦截请求。我希望这可以帮助将来和我一样疏忽的人。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...