在MVC项目中实施全流程OAuth2.0 API授权

时间:2019-09-25 08:46:09

标签: asp.net asp.net-mvc api oauth-2.0 jira

首先让我说我是一个学徒。我创建了一个使用Atlassian Jira REST API的应用程序,该应用程序可能会创建问题以将用户分配给票证。基本功能已经存在,但是后来我发现我不能使用基本授权,而必须使用OAuth 2.0。

我已经花了10个小时来阅读Jira文档,stackoverflow和在youtube上查找有关如何使用OAuth 2.0的信息,但是我还没有找到任何明确的信息来做到这一点。

我的应用程序使用Azure Active Directory进行授权,我需要在其中实现Jira REST API的OAuth 2.0。

这就是我目前的代码

 [HttpPost]
    public  async Task<ActionResult> Index(TokenRequestBody model)
    {
        var user = await new UserProfileController().Index();

        var submitForm = new TokenRequestBody()
        {
            fields = new TokenRequestField()
            {
                project = model.fields.project,
                description = model.fields.description,
                summary = model.fields.summary,
                issuetype = model.fields.issuetype,
                assignee = model.fields.assignee,
                reporter = new ReporterName()
                {
                    name = user
                }
            },
        };

        using (var httpClient = new HttpClient())
        {              

            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(
                    "Basic", Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                           $"user.com:password"))); 
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = HttpMethod.Post;
            httpRequestMessage.RequestUri = new Uri("https://domain.atlassian.net/rest/api/2/issue/");
            httpRequestMessage.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(submitForm), Encoding.UTF8, "application/json");
            var response = httpClient.SendAsync(httpRequestMessage).Result;

            string responseBody =  await response.Content.ReadAsStringAsync();

            var jiraResponse = JsonConvert.DeserializeObject<TicketResponseBody>(responseBody);

            TempData["Message"] = "Ticked Created";
            TempData["Id"] = jiraResponse.Id;
            TempData["Key"] = jiraResponse.Key;
            TempData["Self"] = jiraResponse.Self;

            return RedirectToAction("Index", "Home");
        }
    }

我已在jira中注册了我的应用,以获取一个链接,该链接在访问并获得我的许可后将在URL中返回一个访问密钥,我必须使用该访问密钥来请求令牌。我相信我已具备完成这项工作的所有条件,但是对于经验不足(约4个月)的人,我找不到任何有用的教程。

0 个答案:

没有答案