Implementacion de API OAuth Chaira en MVC Razor C#. Iniciar sesión y obtener información basica del usuario logeado.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Web.Mvc; | |
using Helpers; | |
using System.Web.Security; | |
namespace Project.Controllers { | |
[AllowAnonymous] | |
public class HomeController : Controller { | |
[HttpGet] | |
public ActionResult Index(string code, string error, string state) { | |
if (!string.IsNullOrEmpty(code)) { | |
RequestChaira.ResponseData response_data = RequestChaira.requestAccessToken(code); | |
RequestChaira.PersonProfile person_profile = RequestChaira.requestResource(RequestChaira.PUBLIC_PROFILE, response_data.access_token); | |
if (response_data.scope_ != null) { | |
RequestChaira.PersonProfile data_person = response_data.scope_[0] as RequestChaira.PersonProfile; | |
/* | |
TODO: Aquì tu còdigo de inicio de sesiòn. | |
P.ej: Redireccion al formulario de dashboard, | |
almacenamiento de los datos de la variable data_person, etc. | |
*/ | |
return View("../Usuario/Perfil"); | |
} else { | |
return Content("Scope_ es null. Ha ocurrido un error al iniciar la sesiòn"); | |
} | |
} else { | |
return View(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using RestSharp; | |
using System; | |
using Newtonsoft.Json; | |
using System.Collections.Generic; | |
namespace Helpers { | |
public class RequestChaira { | |
#region constantes para configuración | |
public static readonly string API_URL = "http://chaira.udla.edu.co/api/v0.1"; | |
public static readonly string REDIRECT_URL = "http://localhost:3000"; | |
public static readonly string CLIENT_ID = "919207462918"; | |
public static readonly string CLIENT_SECRET = "l31dj7e645jww7po9xe42gymr0oxkn"; | |
#endregion | |
#region Scopes | |
public static readonly string PUBLIC_PROFILE = "public_profile"; | |
public static readonly string STUDENT_ACADEMIC_INFORMATION = "student_academic_information"; | |
public static readonly string SCHEDULE = "schedule"; | |
public static readonly string SCHEDULE_PROFESSOR = "schedule_professor"; | |
#endregion | |
/** | |
* <summary> | |
* Realiza peticion POST al api de Chairá para solicitar un token valido | |
* </summary> | |
* <param name="code"> | |
* Codigo de autorización generado por | |
* el API Chaira luego de haber iniciado sesión | |
* </param> | |
*/ | |
public static ResponseData requestAccessToken(string code) { | |
var client = new RestClient(API_URL + "/oauth2/authorize.asmx/token"); | |
// client.Authenticator = new HttpBasicAuthenticator(username, password); | |
var request = new RestRequest("", Method.POST); | |
request.AddParameter("grant_type", "authorization_code"); | |
request.AddParameter("code", code); // adds to POST or URL querystring based on Method | |
request.AddParameter("redirect_uri", "http://localhost:3000"); | |
request.AddParameter("client_id", CLIENT_ID); | |
request.AddParameter("client_secret", CLIENT_SECRET); | |
request.AddParameter("state", "xyz"); | |
request.AddHeader("Content-type", "application/json"); | |
// automatically deserialize result | |
IRestResponse<ResponseData> response2 = client.Execute<ResponseData>(request); | |
if (response2.StatusCode == System.Net.HttpStatusCode.OK) { | |
ResponseData rd = JsonConvert.DeserializeObject<ResponseData>(response2.Content); | |
if (!string.IsNullOrEmpty(rd.access_token) && !string.IsNullOrEmpty(rd.refresh_token)) { | |
rd.scope_ = JsonConvert.DeserializeObject<List<PersonProfile>>(rd.scope); | |
return rd; | |
} | |
} | |
return new ResponseData(); | |
} | |
public static bool requestLogout(string token) { | |
var client = new RestClient(API_URL + "/oauth2/resource.asmx/logout"); | |
var request = new RestRequest("", Method.POST); | |
request.AddParameter("access_token", token); | |
request.AddHeader("Content-type", "application/json"); | |
// or automatically deserialize result | |
// return content type is sniffed but can be explicitly set via RestClient.AddHandler(); | |
IRestResponse<ResponseData> response2 = client.Execute<ResponseData>(request); | |
return response2.StatusCode == System.Net.HttpStatusCode.OK; | |
// var name = response2.Data.description; | |
} | |
/** | |
* <summary> | |
* Solicita información segun un scope ya definido. | |
* </summary> | |
* <param name="scope">Recurso a solicitar: Información personal, horarios...</param> | |
* <param name="token">Token de autorización para peticiones</param> | |
*/ | |
public static PersonProfile requestResource(string scope, string token) { | |
var client = new RestClient(API_URL + "/oauth2/resource.asmx/scope"); | |
var request = new RestRequest("", Method.POST); | |
request.AddParameter("access_token", token); | |
request.AddParameter("scope", scope); | |
request.AddHeader("Content-type", "application/json"); | |
IRestResponse<PersonProfile> response2 = client.Execute<PersonProfile>(request); | |
return response2.Data as PersonProfile; | |
} | |
/** | |
* <summary>Clase que almacena todos los datos de la petición</summary> | |
*/ | |
public class ResponseData { | |
#region variables de error | |
public string type { get; set; } | |
public string description { get; set; } | |
public string state { get; set; } | |
#endregion | |
#region variables de respuesta valida | |
public string access_token { get; set; } | |
public string token_type { get; set; } | |
public string expires_in { get; set; } | |
public string scope { get; set; } | |
public List<PersonProfile> scope_ { get; set; } | |
public string refresh_token { get; set; } | |
#endregion | |
public ResponseData() { } | |
} | |
public class PersonProfile { | |
#region PublicProfile | |
public string Nombres { get; set; } | |
public string Apellidos { get; set; } | |
public string Genero { get; set; } | |
public string RH { get; set; } | |
public string Correo { get; set; } | |
public string Rol { get; set; } | |
public string Departamento { get; set; } | |
public string Municipio { get; set; } | |
public string Estado { get; set; } | |
public string Foto { get; set; } | |
#endregion | |
#region PrivateProfile | |
public string Celular { get; set; } | |
public string Direccion { get; set; } | |
public string Documento { get; set; } | |
public string FechaNacimiento { get; set; } | |
public string TipoDocumento { get; set; } | |
#endregion | |
public PersonProfile() { } | |
} | |
public class AcademicInformation { | |
public string Codigo { get; set; } | |
public string Credito { get; set; } | |
public string Estado { get; set; } | |
public string Facultad { get; set; } | |
public string NombreMateria { get; set; } | |
public string Pensum { get; set; } | |
public string Programa { get; set; } | |
public int Semestre { get; set; } | |
public int UbicacionSemestral { get; set; } | |
public AcademicInformation() { } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment