Не получен access_token в трехстороннем потоке oauth 2.0 в asp.net mvc (Blackboard Learn) - PullRequest
0 голосов
/ 08 февраля 2019

Я должен реализовать трехстороннюю аутентификацию в ASP.NET MVC.Я выполнил действия в соответствии с документацией Blackboard, особенно по ссылке https://community.blackboard.com/docs/DOC-3976-three-legged-oauth

. Я получил код авторизации, позвонив в REST API /learn/api/public/v1/oauth2/authorizationcode.After.что в соответствии с документацией (я точно следовал документации, но я не знаю, чего мне не хватало), я создал запрос POST для / learn / api / public / v1 / oauth2 / token, чтобы получить access_token, но не могуполучить access_token.

Вместо access_token я получил BadRequest.Это означает, что я делаю ошибку при создании второго запроса, но не могу решить проблему.Я не нашел ни одного примера кода в .NET для реализации трехсторонней аутентификации для Blackboard Learn.Не могли бы вы помочь мне решить проблему?

Это мой код для вызова обоих API для получения access_token.

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // GET /learn/api/public/v1/oauth2/authorizationcode

            Guid stateId = Guid.NewGuid();

            string applicationKey = "Application key goes here";

            string redirectUrl = string.Format("https://Blackboard Learn URL goes here/learn/api/public/v1/oauth2/authorizationcode" +

            "?redirect_uri=https://localhost:44300/Home/OAuth2Response&response_type=code&client_id={0}&scope=read&state={1}",

            applicationKey, stateId);

            Response.Redirect(redirectUrl, true);

            return View();
        }


        public async Task<bool> OAuth2Response(string code = null, string state = null, string error = null, string error_description = null)    
        {    
            bool success = true;  

            string json = string.Empty;

            string urlCommand = string.Format("/learn/api/public/v1/oauth2/token?code={0}&redirect_url=https://localhost:44300/Home/OAuth2Response", code);

            try    
            {    
                using (HttpClient client = new HttpClient())    
                {    
                    var endpoint = new Uri("Blackboard Learn URL goes here" + urlCommand);


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

                    postData.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));    

                        HttpContent body = new FormUrlEncodedContent(postData);       

                    // POST /learn/api/public/v1/oauth2/token

                    using (HttpResponseMessage response = await client.PostAsync(endpoint, body)) // Problem is here    
                    {    
                        if (response.IsSuccessStatusCode)

                        {

                            json = await response.Content.ReadAsStringAsync();

                        }

                        else

                        {

                            success = false;

                        }

                    }

                }

            }

            catch (Exception err)

            {

                //hopefully we never end up here, log this exception for forensics

                success = false;

            }

            return success;    
        }    
    }

ПРИМЕЧАНИЕ: я могу успешно получить access_token в инструменте Почтальон.

1 Ответ

0 голосов
/ 19 февраля 2019

Наконец, приведенный ниже код отлично работает для трехсторонних аутентификаций в ASP.NET MVC.

public class HomeController : Controller
    {
        //https://blackboard.jiveon.com/docs/DOC-3976-three-legged-oauth 

        public ActionResult Index()
        {
            // GET /learn/api/public/v1/oauth2/authorizationcode

            Guid stateId = Guid.NewGuid();

            string applicationKey = "Application key goes here";

            string redirectUrl = string.Format("Blackboard Learn URL goes here/learn/api/public/v1/oauth2/authorizationcode" +
                "?redirect_uri=https://localhost:44300/Home/OAuth2Response&response_type=code&client_id={0}&scope=read&state={1}",
                applicationKey, stateId);

            Response.Redirect(redirectUrl, true);

            return View();
        }


        public async Task<bool> OAuth2Response(string code = null, string state = null, string error = null, string error_description = null)
        {
            bool success = true;
            string json = string.Empty;
            string urlCommand = string.Format("/learn/api/public/v1/oauth2/token?code={0}&redirect_uri=https://localhost:44300/Home/OAuth2Response", code);

            try
            {
                using (HttpClient client = new HttpClient())
                {

                    var endpoint = new Uri("Blackboard Learn URL goes here" + urlCommand);


                    client.DefaultRequestHeaders.Accept.Clear();

                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("client_id:client_secret")));                  

                    var postData = new List<KeyValuePair<string, string>>();
                    postData.Add(new KeyValuePair<string, string>("grant_type", "authorization_code")); 

                    HttpContent body = new FormUrlEncodedContent(postData);


                    using (HttpResponseMessage response = await client.PostAsync(endpoint, body))
                    {

                        if (response.IsSuccessStatusCode)
                        {
                            json = await response.Content.ReadAsStringAsync();

                            dynamic oauth2Result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);     

                            string access_token = oauth2Result.access_token;

                            string refresh_token = oauth2Result.refresh_token;           }
                        else
                        {
                            success = false;
                        }
                    }
                }
            }
            catch (Exception err)            {
                //hopefully we never end up here, log this exception for forensics      
                success = false;
            }
            return success;           
        }     
    }
...