asp.net core razor(非mvc)接入gitee OAuth2


      

新增Login.cshtml页面,并添加如下代码

public async Task< IActionResult> OnGetAsync()
        {
            string path = System.IO.Path.Combine(Env.WebRootPath, "accessToken.json");
            if (System.IO.File.Exists(path))
            {
                return Redirect("Redirect");
            }
            string client_id = configuration["Gitee:client_id"];
            string state = configuration["Gitee:state"];
            string redirect_uri = "http://localhost:8089/gitee/redirect";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("client_id", client_id);
            dict.Add("redirect_uri", redirect_uri);
            dict.Add("response_type", "code");
            dict.Add("scope", "user_info");
            dict.Add("state", state);
            FormUrlEncodedContent content = new FormUrlEncodedContent(dict);
            string p = await content.ReadAsStringAsync();
            return Redirect($"https://gitee.com/oauth/authorize?{p}");
        }

 

新增Redirect.cshtml页面接受gitee返回的参数code和state,并调用获取用户信息接口

 

public async Task<IActionResult> OnGetAsync(string code,string state)
        {
            string path = System.IO.Path.Combine(Env.WebRootPath, "accessToken.json");
            string json;
            if (string.IsNullOrEmpty(code))
            {
                json = System.IO.File.ReadAllText(path);
            }
            else
            {
                string client_id = configuration["Gitee:client_id"];
                string client_secret = configuration["Gitee:client_secret"];
                string state_config = configuration["Gitee:state"];
                if (state != state_config)
                {
                    return new JsonResult(new { code = -1, msg = "invalid state data!" });
                }
                string redirect_uri = "http://localhost:8089/gitee/redirect";
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("grant_type", "authorization_code");
                dict.Add("code", code);
                dict.Add("client_id", client_id);
                dict.Add("redirect_uri", redirect_uri);
                dict.Add("client_secret", client_secret);
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
                FormUrlEncodedContent content = new FormUrlEncodedContent(dict);
                var requestPos = new HttpRequestMessage(HttpMethod.Post, "https://gitee.com/oauth/token");
                requestPos.Content = content;
                var client = new HttpClient();
                var response = await client.SendAsync(requestPos);
                json = await response.Content.ReadAsStringAsync();
                System.IO.File.WriteAllText(path, json);
            }
            var jObj = Newtonsoft.Json.Linq.JObject.Parse(json);
            string access_token = jObj.SelectToken("access_token")?.ToString();
            int expires_in = Convert.ToInt32(jObj.SelectToken("expires_in")?.ToString());
            long created_at = Convert.ToInt64(jObj.SelectToken("created_at")?.ToString());
            DateTime created_time = GetCreateDate(created_at);
            if (created_time.AddSeconds(expires_in) < DateTime.Now)
            {
                string refresh_token = jObj.SelectToken("refresh_token")?.ToString();
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("grant_type", "refresh_token");
                dict.Add("refresh_token", refresh_token);
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
                FormUrlEncodedContent content = new FormUrlEncodedContent(dict);
                var requestPos = new HttpRequestMessage(HttpMethod.Post, "https://gitee.com/oauth/token");
                requestPos.Content = content;
                var client = new HttpClient();
                var response = await client.SendAsync(requestPos);
                json = await response.Content.ReadAsStringAsync();
                System.IO.File.WriteAllText(path, json);
            }
            return Redirect($"https://gitee.com/api/v5/user?access_token={access_token}");
        }


        DateTime GetCreateDate(long timestamp)
        {
            DateTime dt = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            return dt.AddTicks(timestamp*10000000);
        }