public static UsuarioExterno ObtenerUsuarioDeTokenGoogle(string idToken, IGenService genService) { // Validamos firma del token var validPayload = GoogleJsonWebSignature.ValidateAsync(idToken); if (validPayload == null) { throw new SecurityTokenValidationException("Firma de token no válida."); } UsuarioExterno usuario = null; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); if (tokenHandler.CanReadToken(idToken)) { // Obtenemos datos de claims del payload JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(idToken); string idExterno = jwtToken.Claims.First(claim => claim.Type == "sub").Value; string nombre = jwtToken.Claims.First(claim => claim.Type == "given_name").Value; string apellido = jwtToken.Claims.First(claim => claim.Type == "family_name").Value; string direccionCorreo = jwtToken.Claims.First(claim => claim.Type == "email").Value; string emisorToken = jwtToken.Claims.First(claim => claim.Type == "iss").Value; string audiencia = jwtToken.Claims.First(claim => claim.Type == "aud").Value; // Validamos el emisor del token var respValorEmisor = genService.ValorParametro("GOOGLE_EMISOR_TOKEN"); if (!respValorEmisor.Codigo.Equals(RiskConstants.CODIGO_OK) || !emisorToken.Contains(respValorEmisor.Datos.Contenido, StringComparison.OrdinalIgnoreCase)) { throw new SecurityTokenValidationException("Emisor de token no válido."); } // Validamos el cliente del token var respValorCliente = genService.ValorParametro("GOOGLE_IDENTIFICADOR_CLIENTE"); if (!respValorCliente.Codigo.Equals(RiskConstants.CODIGO_OK) || respValorCliente.Datos.Contenido != audiencia) { throw new SecurityTokenValidationException("Cliente de token no válido."); } MailAddress addr = new MailAddress(direccionCorreo); string username = addr.User; string domain = addr.Host; usuario = new UsuarioExterno { Alias = username, Nombre = nombre, Apellido = apellido, DireccionCorreo = direccionCorreo, Origen = OrigenSesion.Google, IdExterno = idExterno }; } return(usuario); }
public GenController(IGenService genService, IConfiguration configuration) : base(configuration) { _genService = genService; }
public static string GenerarAccessToken(string usuario, IAutService autService, IGenService genService) { var respDatosUsuario = autService.DatosUsuario(usuario); if (!respDatosUsuario.Codigo.Equals(RiskConstants.CODIGO_OK)) { return(string.Empty); } Usuario datosUsuario = respDatosUsuario.Datos; // Crea la lista de claims (pertenencias, características) del usuario List <Claim> claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, datosUsuario.Alias)); claims.Add(new Claim(ClaimTypes.GivenName, datosUsuario.Nombre ?? "")); claims.Add(new Claim(ClaimTypes.Surname, datosUsuario.Apellido ?? "")); claims.Add(new Claim(ClaimTypes.Email, datosUsuario.DireccionCorreo ?? "")); //claimsList.Add(new Claim(ClaimTypes.HomePhone, usuario.NumeroTelefono ?? "")); claims.Add(new Claim(ClaimTypes.GroupSid, datosUsuario.Origen.ToString() ?? "")); // Agrega los roles del usuario a la lista de claims foreach (var rol in datosUsuario.Roles) { claims.Add(new Claim(ClaimTypes.Role, rol.Nombre)); } var respTiempoExpiracionToken = autService.TiempoExpiracionToken(TipoToken.AccessToken); if (!respTiempoExpiracionToken.Codigo.Equals(RiskConstants.CODIGO_OK)) { return(string.Empty); } int tiempoExpiracion = int.Parse(respTiempoExpiracionToken.Datos.Contenido); var respValorParametro = genService.ValorParametro("CLAVE_VALIDACION_ACCESS_TOKEN"); if (!respValorParametro.Codigo.Equals(RiskConstants.CODIGO_OK)) { return(string.Empty); } var signingKey = Encoding.ASCII.GetBytes(respValorParametro.Datos.Contenido); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims.ToArray()), Expires = DateTime.UtcNow.AddSeconds(tiempoExpiracion), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(signingKey), SecurityAlgorithms.HmacSha256Signature) }; var tokenHandler = new JwtSecurityTokenHandler(); var createdToken = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(createdToken)); }
public static UsuarioExterno ObtenerUsuarioDeTokenFacebook(string accessToken, IGenService genService) { UsuarioExterno usuario = null; try { // Validamos el token a través del Graph de facebook using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://graph.facebook.com"); HttpResponseMessage response = client.GetAsync($"me?fields=id,name,email,first_name,last_name&access_token={accessToken}").Result; response.EnsureSuccessStatusCode(); string result = response.Content.ReadAsStringAsync().Result; var jsonRes = JsonConvert.DeserializeObject <dynamic>(result); // Obtenemos datos recibidos del usuario en la respuesta del Graph de facebook string idExterno = jsonRes["id"].ToString(); string nombre = jsonRes["first_name"].ToString(); string apellido = jsonRes["last_name"].ToString(); string direccionCorreo = jsonRes["email"].ToString(); MailAddress addr = new MailAddress(direccionCorreo); string username = addr.User; string domain = addr.Host; usuario = new UsuarioExterno { Alias = username, Nombre = nombre, Apellido = apellido, DireccionCorreo = direccionCorreo, Origen = OrigenSesion.Facebook, IdExterno = idExterno }; } } catch (Exception e) { throw new SecurityTokenValidationException("Token no válido.", e); } return(usuario); }
public RiskSecurityTokenValidator(IAutService autService, IGenService genService) { _autService = autService; _genService = genService; _tokenHandler = new JwtSecurityTokenHandler(); }
public FanController(IFanService fanService, IGenService genService, IHubContext <FanHub> hubContext, IConfiguration configuration) : base(configuration) { _fanService = fanService; _genService = genService; _hubContext = hubContext; }
public AutController(IAutService autService, IGenService genService, INotificationHubClientConnection notificationHubClientConnection, IConfiguration configuration) : base(configuration) { _autService = autService; _genService = genService; _notificationHubClientConnection = notificationHubClientConnection; }
public MsjHelper(ILogger <MsjHelper> logger, IGenService genService, IMsjService msjService) { _logger = logger; _genService = genService; _msjService = msjService; }