using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace New_College.Common
{
public class CasdoorHttpHelper
{
///
/// 获取accesstoken
///
///
///
///
public static T Post_AccessToken(string code) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("{0}/api/login/oauth/access_token", CasdoorConfig.Endpoint);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRequest() { code = code, grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json");
var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 刷新token
///
///
///
///
///
public static T Post_RefreshToken(string refresh_token, string scope) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("{0}/api/login/oauth/refresh_token", CasdoorConfig.Endpoint);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRefeshToken() { refresh_token = refresh_token, scope = "built-in", grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json");
var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
private class CasdoorRequest
{
public string grant_type { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
public string code { get; set; }
}
private class CasdoorRefeshToken
{
public string grant_type { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
public string scope { get; set; }
public string refresh_token { get; set; }
}
}
}