Exemplo n.º 1
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            var validationSettings = new GoogleJsonWebSignature.ValidationSettings();

            validationSettings.Audience = new List <string>()
            {
                _settingsService.GoogleApiCrendentials.ClientId !
            };
            try
            {
                var payload = GoogleJsonWebSignature.ValidateAsync(securityToken, validationSettings).Result;

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, payload.Name),
                    new Claim(ClaimTypes.Name, payload.Name),
                    new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName),
                    new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName),
                    new Claim(JwtRegisteredClaimNames.Email, payload.Email),
                    new Claim(JwtRegisteredClaimNames.Sub, payload.Subject),
                    new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer),
                };

                validatedToken = null;
                var principle = new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationTypes.Google));
                return(principle);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
Exemplo n.º 2
0
        /// <summary>
        /// Sends the jwt token to Google's Servers to be validated.
        /// </summary>
        /// <returns>
        /// The payload received from Google, or null if the token is invalid.
        /// </returns>
        /// <param name="token">A JWT.</param>
        /// <param name="env">The environment, used to check if validation should be skipped.</param>
        public static async Task <GoogleJsonWebSignature.Payload> ValidateUser(string token, IAppEnvironment env)
        {
            if (env.SkipValidation == "true")
            {
                return(new GoogleJsonWebSignature.Payload()
                {
                    Name = "Smitty Jensens",
                    GivenName = "Smitty",
                    FamilyName = "Jensens",
                    Email = "*****@*****.**",
                    Subject = "123456789109876543210",  // Subject is longer than Int64
                });
            }

            try
            {
                var settings = new GoogleJsonWebSignature.ValidationSettings()
                {
                    Audience = new string[] { env.Audience },
                };

                var validPayload = await GoogleJsonWebSignature.ValidateAsync(token);

                return(validPayload);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 3
0
        public async Task <NewExternalUserViewModel> GetUserViewModelUserFromGoogleToken(string googleIdToken)
        {
            var googleTokenSettings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new List <string>()
                {
                    "680869894998-hujg19vbq0lhmhc8vf8ldmc1dnepvrti.apps.googleusercontent.com"
                }
            };

            try
            {
                var validToken = await GoogleJsonWebSignature.ValidateAsync(googleIdToken, googleTokenSettings);

                var user = new NewExternalUserViewModel()
                {
                    AuthenticationTypeId = (int)AuthenticationType.GoogleApi,
                    Email     = validToken.Email,
                    FirstName = validToken.Name,
                    LastName  = validToken.GivenName,
                    Password  = GenerateRandomPasswordForSocialUser(),
                    Username  = validToken.Email
                };
                return(user);
            }
            catch (InvalidJwtException ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> LoginGoogle(GoogleTokenDto googleToken)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = Enumerable.Repeat(_config["Authentication:Google:ClientId"], 1),
            };

            var payload = await GoogleJsonWebSignature.ValidateAsync(googleToken.IdToken, settings);

            if (!payload.EmailVerified)
            {
                return(Unauthorized());
            }
            User user;

            if (await _repo.UserExists(payload.Email))
            {
                user = await _repo.GetExistingUser(payload.Email);
            }
            else
            {
                var userToCreate = new User
                {
                    Email      = payload.Email,
                    FullName   = payload.Name,
                    Activated  = true,
                    Registered = false,
                    Role       = Role.User,
                };

                user = await _repo.CreateUserWithoutRegistration(userToCreate);
            }

            // generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config["JWTSecret"]);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.NameIdentifier, user.UserId),
                    new Claim(ClaimTypes.Email, user.Email),
                    new Claim(ClaimTypes.Role, user.Role)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            HttpContext.Response.Cookies.Append("JWT", tokenString, new CookieOptions {
                HttpOnly = true, Expires = DateTime.Now.AddDays(14)
            });
            return(Ok());
        }
Exemplo n.º 5
0
        public async Task <GoogleJsonWebSignature.Payload> ValidateGooglePayLoad(string tokenId)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new string[] { _config.GetSection("Google:ClientId").Value }
            };

            var payload = await GoogleJsonWebSignature.ValidateAsync(tokenId, settings);

            return(payload);
        }
Exemplo n.º 6
0
        private async Task <GoogleJsonWebSignature.Payload> VerifyGoogleToken(AuthRequest authRequest)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new List <string>()
                {
                    _authGoogleConfig.ClientId
                }
            };

            return(await GoogleJsonWebSignature.ValidateAsync(authRequest.IdToken, settings));
        }
        public async Task <GoogleJsonWebSignature.Payload> VerifyGoogleToken(ExternalAuth externalAuth)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new List <string>()
                {
                    _appSettings.ClientId
                }
            };

            return(await GoogleJsonWebSignature.ValidateAsync(externalAuth.IdToken, settings));
        }
        public async Task <GoogleJsonWebSignature.Payload> ValidateGoogleToken(string idToken)
        {
            var validationSettings = new GoogleJsonWebSignature.ValidationSettings
            {
                Audience = new[] { _authOptions.Value.GoogleClientId }
            };

            // Todo: Research: Is this secure enough?
            var payload = await GoogleJsonWebSignature.ValidateAsync(idToken, validationSettings);

            return(payload);
        }
Exemplo n.º 9
0
        public async Task <ActionResult> TokenLogin(string idToken)
        {
            if (idToken == null)
            {
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(null);
            }

            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new List <string>()
                {
                    _config["GoogleClientId"]
                }
            };

            string subject = null;
            string email   = null;

            try
            {
                var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken, settings);

                subject = validPayload.Subject;
                email   = validPayload.Email;
            }
            catch (InvalidJwtException)
            {
                Response.StatusCode = 403;
                // Provide body?

                // Should probably log this.
                return(null);
            }

            var user = _db.Users.FirstOrDefault(u => u.VendorID == subject);

            if (user == null)
            {
                var newUser = new User()
                {
                    Email = email, VendorID = subject
                };
                _db.Users.Add(newUser);
                _db.SaveChanges();
            }

            HttpContext.Session.SetString("userID", user.ID.ToString());

            // Should be able to insert this into SQL Server.
            return(Content(JsonConvert.SerializeObject(user), "application/json"));
        }
Exemplo n.º 10
0
        public IActionResult Authenticate([FromBody] AuthenticateRequest data)
        {
            GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();

            // Change this to your google client ID
            settings.Audience = new List <string>()
            {
                "425874635785-9qbseena0h69r9f6jbe7o84qpfjk6krr.apps.googleusercontent.com"
            };

            GoogleJsonWebSignature.Payload payload = GoogleJsonWebSignature.ValidateAsync(data.IdToken, settings).Result;
            return(Ok(new { AuthToken = _jwtGenerator.CreateUserAuthToken(payload.Email) }));
        }
Exemplo n.º 11
0
    public async Task <GoogleUserDto> Handle(GetGoogleUser request, CancellationToken cancellationToken)
    {
        var settings = new GoogleJsonWebSignature.ValidationSettings
        {
            Audience = new List <string> {
                _audience
            }
        };

        GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(request.IdToken, settings);

        return(new GoogleUserDto(payload.Email));
    }
Exemplo n.º 12
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var token = context.HttpContext.Request.Headers["authorization"];

            GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
            settings.Audience = new List <string>()
            {
                "419273351615-a2kp1blvs5f3idt3mlr5vbkeqtqgjvr6.apps.googleusercontent.com"
            };
            GoogleJsonWebSignature.Payload payload = GoogleJsonWebSignature.ValidateAsync(token, settings).Result;

            context.ActionArguments["nome"]  = payload.Name;
            context.ActionArguments["email"] = payload.Email;

            base.OnActionExecuting(context);
        }
        public async Task <GoogleJsonWebSignature.Payload> ValidateToken([FromQuery] string idToken, CancellationToken cancellationToken)
        {
            //var validPayload = await GoogleJsonWebSignature.ValidateAsync(idToken);
            //Assert.NotNull(validPayload, "GoogleValidationResponse", "Id_Token is not valid!");

            //return Ok("Token is Valid");

            GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
            settings.Audience = new List <string>()
            {
                _configuration.GetSection("Authentication:Google")["ClientId"]
            };
            GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(idToken, settings);

            return(payload);
        }
Exemplo n.º 14
0
        public async Task<GoogleJsonWebSignature.Payload> VerifyGoogleToken(ExternalAuthDto externalAuth)
		{
			try
			{
				var settings = new GoogleJsonWebSignature.ValidationSettings()
				{
					Audience = new List<string>() { _goolgeSettings.GetSection("clientId").Value }
				};

				var payload = await GoogleJsonWebSignature.ValidateAsync(externalAuth.IdToken, settings);
				return payload;
			}
			catch (Exception ex)
			{
				//log an exception
				return null;
			}
		}
Exemplo n.º 15
0
        //public GoogleService(GoogleDataStore googleDataStore)
        //{
        //    _googleDataStore = googleDataStore;
        //}

        public async Task <ExternalAuthDto?> LogInAsync(string jwt, CancellationToken cancellationToken)
        {
            var settings = new GoogleJsonWebSignature.ValidationSettings
            {
                Audience = new[]
                {
                    "341737442078-ajaf5f42pajkosgu9p3i1bcvgibvicbq.apps.googleusercontent.com", // Web site
                    "99716345448-73b697k11joufrvkqtc18ep2j36trgci.apps.googleusercontent.com"   // Android
                }
            };

            try
            {
                var result = await GoogleJsonWebSignature.ValidateAsync(jwt, settings);


                if (result == null)
                {
                    return(null);
                }

                if (!result.EmailVerified)
                {
                    return(null);
                }

                return(new ExternalAuthDto()
                {
                    Id = result.Subject,
                    FirstName = result.GivenName,
                    LastName = result.FamilyName,
                    Email = result.Email,
                    Language = result.Locale,
                    Name = result.Name,
                    Picture = result.Picture
                });
            }
            catch (InvalidJwtException)
            {
                return(null);
            }
        }
Exemplo n.º 16
0
        public async Task <ActionResult <AuthenticateResponse> > GoogleLogin(GoogleLoginResponse model)
        {
            //var refreshToken = Request.Cookies["refreshToken"];
            GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings
            {
                // your google client ID
                Audience = new List <string>()
                {
                    "505653862664-h65g6rpnso3aiukv5i4fgd3o5f8okvm2.apps.googleusercontent.com"
                }
            };

            GoogleJsonWebSignature.Payload payload = GoogleJsonWebSignature.ValidateAsync(model.IdToken, settings).Result;

            //return Ok(new { AuthToken = _jwtGenerator.CreateUserAuthToken(payload.Email) });
            var response = await _accountService.GoogleLogin(payload, IpAddress(), Request.Headers["origin"]);

            SetTokenCookie(response.RefreshToken);
            return(Ok(response));
        }
Exemplo n.º 17
0
        public async Task <GoogleJsonWebSignature.Payload> VerifyGoogleToken(ExternalAuthenticationRequestModel externalAuth)
        {
            try
            {
                var settings = new GoogleJsonWebSignature.ValidationSettings()
                {
                    Audience = new List <string>()
                    {
                        _goolgeSettings.GetSection("clientId").Value
                    }
                };
                var payload = await GoogleJsonWebSignature.ValidateAsync(externalAuth.IdToken, settings);

                return(payload);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 18
0
        public IActionResult GoogleLogin(SocialNetworkIdTokenModel data)
        {
            try
            {
                GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
                settings.Audience = new List <string>()
                {
                    "752253873246-cg9qrlhp0tmtn7cd8vpg4qrfk03br55c.apps.googleusercontent.com"
                };
                GoogleJsonWebSignature.Payload userGoogle = GoogleJsonWebSignature.ValidateAsync(data.IdToken, settings).Result;

                _serviceAuth.SocialNetworksAuthenticate(userGoogle.Email, userGoogle.GivenName, userGoogle.FamilyName, userGoogle.Picture);

                var response = GiveJWTToken(userGoogle.Email, "0");
                return(Ok(response));
            }
            catch (Exception ee)
            {
                return(BadRequest(ee.Message));
            }
        }
Exemplo n.º 19
0
        private async Task <GoogleJsonWebSignature.Payload> VerifyGoogleToken(GoogleLoginModel model)
        {
            try
            {
                var settings = new GoogleJsonWebSignature.ValidationSettings()
                {
                    Audience = new List <string>()
                    {
                        _googleConfiguration.ClientId
                    }
                };
                var payload = await GoogleJsonWebSignature.ValidateAsync(model.IdToken, settings);

                return(payload);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> POSTAsync([FromBody] TokenDto value)
        {
            try
            {
                GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
                //settings.Audience = new List<string>() { "781444592241-5l8d33p832p4muissesek9gvr74p08rk.apps.googleusercontent.com" };
                settings.Audience = new List <string>()
                {
                    "491676760446-n2786agrpa456hcr6cfns835t130glnm.apps.googleusercontent.com"
                };
                GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(value.token, settings);

                if (payload.EmailVerified)
                {
                    Payload userPayload = new Payload
                    {
                        Name          = payload.Name,
                        Email         = payload.Email,
                        EmailVerified = payload.EmailVerified,
                        Picture       = payload.Picture
                    };
                    TTSUserDetailsByEmail user = loginService.LoginCheck(payload.Email).Result;
                    if (user != null)
                    {
                        var token = loginService.GenerateJWTToken(user, userPayload);
                        return(Ok(token));
                    }
                }
                return(BadRequest());
            }
            catch (Exception ex)
            {
                return(StatusCode(500));

                throw;
            }
        }
        public void ValidationSettingsToSignedTokenVerificationOptions()
        {
            MockClock            clock = new MockClock(DateTime.UtcNow);
            FakeCertificateCache cache = new FakeCertificateCache();
            var options = new GoogleJsonWebSignature.ValidationSettings
            {
                Clock                        = clock,
                Audience                     = new[] { "audience" },
                HostedDomain                 = "hosted_domain",
                IssuedAtClockTolerance       = TimeSpan.FromSeconds(5),
                ExpirationTimeClockTolerance = TimeSpan.FromSeconds(10),
                CertificateCache             = cache,
                ForceGoogleCertRefresh       = true
            }.ToVerificationOptions();

            Assert.Same(clock, options.Clock);
            Assert.Single(options.TrustedAudiences, "audience");
            Assert.Equal(TimeSpan.FromSeconds(5), options.IssuedAtClockTolerance);
            Assert.Equal(TimeSpan.FromSeconds(10), options.ExpiryClockTolerance);
            Assert.Same(cache, options.CertificateCache);
            Assert.True(options.ForceCertificateRefresh);
            Assert.Equal(GoogleAuthConsts.JsonWebKeySetUrl, options.CertificatesUrl);
            Assert.Equal(GoogleJsonWebSignature.ValidJwtIssuers.Count(), options.TrustedIssuers.Count);
        }
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;

            // Create a new list of claims that is to contain Google JWT payload data that will become part of the Identity
            List <Claim> claims = null;

            // Create a new payload object
            GoogleJsonWebSignature.Payload payload = null;

            // Validate token
            try
            {
                // GoogleJsonWebSignature class contains methods to validate the Google issued JWT
                // ValidationSettings() method contains definitions for default auth settings (clock deviation tolerances, hosted domain validation for GSuite
                // and Client ID verification. Nothing is overriden, so all settings are at default for now.
                GoogleJsonWebSignature.ValidationSettings validationSettings = new GoogleJsonWebSignature.ValidationSettings();

                // ValidateAsync() performs the validation of the JWT token. Token payload contains the targeted data as defined during the Auth Token definition
                // (scope of access to various Google services/APIs/personal information, etc. The payload data will be stored into a list of claims.
                payload = GoogleJsonWebSignature.ValidateAsync(securityToken, validationSettings).Result;

                // Create a list of claims containing Google JWT payload data
                claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, payload.Name),
                    new Claim(ClaimTypes.Name, payload.Name),
                    new Claim(JwtRegisteredClaimNames.FamilyName, payload.FamilyName),
                    new Claim(JwtRegisteredClaimNames.GivenName, payload.GivenName),
                    new Claim(JwtRegisteredClaimNames.Website, payload.Picture),
                    new Claim(JwtRegisteredClaimNames.Email, payload.Email),
                    new Claim(JwtRegisteredClaimNames.Sub, payload.Subject),
                    new Claim(JwtRegisteredClaimNames.Iss, payload.Issuer),
                };

                // Check if the user exists in the local database.
                using (DataContext _DataContext = new DataContext())
                {
                    // Get DB record associated with the Email, if it exists.

                    User userData = _DataContext.Users.Where(x => x.Email == payload.Email).Include(user => user.StaffData).FirstOrDefault();

                    if (userData != null)
                    {
                        if (!userData.Active)
                        {
                            throw new SecurityTokenValidationException($"[LOGIN] FAILURE User {payload.Email} attempted to login but set to inactive");
                        }

                        bool userIsStaff     = userData.StaffData != null;
                        bool userIsSuperUser = userIsStaff ? userData.StaffData.SuperUser : false;
                        claims.Add(new Claim(ClaimTypes.Role, (userIsSuperUser ? "SuperAdmin" : userIsStaff ? "Staff" : "Student")));

                        // Compare the current id token in database to the new one. If they differ, store the new token and create a log entry
                        if (userData.ActiveToken != securityToken)
                        {
                            userData.ActiveToken = securityToken;
                            _DataContext.SaveChanges();

                            Logger.Msg <GoogleTokenValidator>($"[LOGIN] SUCCESS User {payload.Email} {(userIsSuperUser ? "(Super)" : userIsStaff ? "(Staff)" : string.Empty)}", Serilog.Events.LogEventLevel.Debug);
                        }
                    }
                    else
                    {
                        throw new SecurityTokenValidationException($"[LOGIN] FAILURE User with auth token belonging to {payload.Email} not found in database");
                    }
                }

                // Convert token to Identity
                if (payload != null)
                {
                    ClaimsPrincipal principal = new ClaimsPrincipal();
                    principal.AddIdentity(new ClaimsIdentity(claims, "Google"));
                    return(principal);
                }
                else
                {
                    throw new SecurityTokenValidationException($"[LOGIN] FAIL Unable to authenticate user with auth token belonging to {payload?.Email}");
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException?.Message != null)
                {
                    Logger.Msg <GoogleTokenValidator>(new SecurityTokenValidationException($"[LOGIN] FAILURE {ex.InnerException.Message}"));
                }
                else
                {
                    Logger.Msg <GoogleTokenValidator>(new SecurityTokenValidationException($"[LOGIN] FAILURE {ex.Message}"));
                }

                throw new SecurityTokenValidationException();
            }
        }
Exemplo n.º 23
0
        public async Task <User> ValidateGoogleUser(string TokenId)
        {
            var CLIENT_ID = "393357815889-jl0jci0rs1ghjvq94lcbgl1rfms0cruv.apps.googleusercontent.com";

            GoogleJsonWebSignature.Payload googleToken = null;
            var settings = new GoogleJsonWebSignature.ValidationSettings()
            {
                Audience = new List <string>()
                {
                    CLIENT_ID
                }
            };

            try { googleToken = await GoogleJsonWebSignature.ValidateAsync(TokenId, settings); }
            catch { return(null); }

            var user = await _userManager.FindByNameAsync(googleToken.Email);

            if (user == null)
            {
                var newUser = new User
                {
                    UserName = googleToken.Email,
                    Email    = googleToken.Email
                };
                await _userManager.CreateAsync(newUser);

                _userManager.AddToRoleAsync(newUser, "User").Wait();

                // authentication successful so generate jwt token
                var tokenHandler2    = new JwtSecurityTokenHandler();
                var key2             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor2 = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, newUser.Id.ToString())
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key2), SecurityAlgorithms.HmacSha256Signature)
                };
                var token2 = tokenHandler2.CreateToken(tokenDescriptor2);
                newUser.Token = tokenHandler2.WriteToken(token2);
                return(newUser);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);
            return(user);
        }
Exemplo n.º 24
0
        public async Task <IActionResult> GoogleAutentificar([FromBody] GoogleAuthRequest googleAuthRequest)
        {
            AuthRequest  authRequest  = new();
            AuthResponse authResponse = new();

            try
            {
                //The authentication API will use the idToken from google and verify it.
                GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();

                //Here goes the app google client ID
                settings.Audience = new List <string>()
                {
                    "225689514544-qccdbtr164tekpjkgq0fn1f7630g2266.apps.googleusercontent.com"
                };

                GoogleJsonWebSignature.Payload payload = GoogleJsonWebSignature.ValidateAsync(googleAuthRequest.Id_token, settings).Result;


                //***LOGIN***
                //Revisa si el usuario figura en los registros de la base de datos, si es asi lo logea
                string hashCommonPassword = Encrypt.GetSHA256(_CommonPassSettings.Pass);
                bool   existe             = _context.Usuarios.Any(u => u.NombreUsuario == payload.Email && u.Clave == hashCommonPassword && u.Disabled.Equals(false));

                if (existe)
                {
                    //Then it creates an access token that grants access to the other APIs of your app.
                    authRequest.NombreUsuario = payload.Email;
                    authRequest.Clave         = _CommonPassSettings.Pass;

                    authResponse = await _authService.Authorize(authRequest);

                    return(Ok(authResponse));
                }


                //***REGISTRER...***
                //Agregamos el usuario nuevo
                Usuario usuarioNuevo = new();
                usuarioNuevo.NombreUsuario = payload.Email;
                usuarioNuevo.Clave         = hashCommonPassword;
                usuarioNuevo.RolID         = 1; //Corresponde al Cliente en la base de datos de Roles
                _context.Usuarios.Add(usuarioNuevo);
                _context.SaveChanges();         //Debería hacerse de forma asincrona, cambiar eso

                //Luego agregamos el cliente nuevo
                Cliente clienteNuevo = new();
                clienteNuevo.Nombre    = payload.GivenName;
                clienteNuevo.Apellido  = payload.FamilyName;
                clienteNuevo.Telefono  = 0;
                clienteNuevo.UsuarioID = usuarioNuevo.Id;
                _context.Clientes.Add(clienteNuevo);
                _context.SaveChanges(); //Debería hacerse de forma asincrona, cambiar eso

                //***...then LOGIN***
                //Then it creates an access token that grants access to the other APIs of your app.
                authRequest.NombreUsuario = payload.Email;
                authRequest.Clave         = _CommonPassSettings.Pass;

                authResponse = await _authService.Authorize(authRequest);

                return(Ok(authResponse));
            }
            catch
            {
                Console.WriteLine("Error en GoogleAuth");
            }
            return(StatusCode(500));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> SignInGoogle(GoogleIDToken googleIDToken)
        {
            if (string.IsNullOrEmpty(googleIDToken.Id_Token))
            {
                this._logger.LogInformation(googleIDToken.Id_Token);
                return(BadRequest());
            }

            var validationSettings = new GoogleJsonWebSignature.ValidationSettings();

            validationSettings.Audience = new List <string> {
                _configuration["Authentication_Google_ClientId"]
            };

            var result = await GoogleJsonWebSignature
                         .ValidateAsync(googleIDToken.Id_Token, validationSettings);

            var isSignedUp = await this._userService.IsSignedUp(result.Email);

            if (isSignedUp)
            {
                var user = await this._userService.GetUserByEmail(result.Email);

                if (user == null)
                {
                    return(NotFound(new { message = "User not found when sign in" }));
                }

                var authResult = await this._authenticationService.AuthenticateByUser(user);

                if (!authResult.Succeeded)
                {
                    return(BadRequest(new { message = "User was not signed in" }));
                }

                return(Ok(new { redirectUrl = googleIDToken.returnUrl }));
            }
            else
            {
                var newUser = new User {
                    Email    = result.Email,
                    Name     = result.Name,
                    UserName = result.Email.Split('@').First()
                };

                await this._userService.Create(newUser);

                var user = await this._userService.GetUserByEmail(newUser.Email);

                if (user == null)
                {
                    return(NotFound(new { message = "User was not found when sign in" }));
                }

                var authResult = await this._authenticationService.AuthenticateByUser(user);

                if (!authResult.Succeeded)
                {
                    return(BadRequest(new { message = "It wasn't possible to sign in the user." }));
                }

                return(Ok(new { redirectUrl = googleIDToken.returnUrl }));
            }
        }
Exemplo n.º 26
0
        public async Task <IActionResult> AuthenticateGoogleSignin(ExternalLoginModel externalLoginModel)
        {
            GoogleJsonWebSignature.Payload payload;
            var provider = "google";

            try
            {
                var validationSettings = new GoogleJsonWebSignature.ValidationSettings();
                //{ Audience = new[] { "YOUR_CLIENT_ID" } };

                payload = await GoogleJsonWebSignature
                          .ValidateAsync(externalLoginModel.IdToken, validationSettings);

                var user = await GetOrCreateExternalLoginUser(
                    "google",
                    payload.Subject,
                    payload.Email);

                var profilePicture = payload.Picture;

                /*
                 * result = userMgr.AddClaimsAsync(bob, new Claim[]{
                 *          new Claim(JwtClaimTypes.Name, "Bob Smith"),
                 *          new Claim(JwtClaimTypes.GivenName, "Bob"),
                 *          new Claim(JwtClaimTypes.FamilyName, "Smith"),
                 *          new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                 *          new Claim("location", "somewhere")
                 *      }).Result;
                 */

                // create custom claims for the user found from Google idToken
                var userRoleCustomClaim = new Claim("userRole", externalLoginModel.UserRole);

                var result = await _userManager.AddClaimAsync(user, userRoleCustomClaim);

                // get the new IdentityServer4 issued access token for the user
                var userSubscriptionToken = await _identityServerTools
                                            .IssueClientJwtAsync(
                    clientId : "userSubscriptionClient",
                    lifetime : 15,
                    scopes : new[] {
                    "userSubscription.read"
                },
                    audiences : new[] {
                    "https://user.subscription.service/"
                },
                    additionalClaims : new List <Claim>()
                {
                    userRoleCustomClaim
                });

                var jwttoken = await _identityServerTools
                               .IssueJwtAsync(
                    lifetime : 15,
                    claims : new List <Claim>()
                {
                    userRoleCustomClaim
                });

                return(Ok(new
                {
                    access_token = "want_to_give_identity_server4_provided_token"
                }));
            }
            catch (Exception ex)
            {
                // Invalid token
            }
            return(BadRequest());
        }