コード例 #1
0
ファイル: OAuthLogin.cs プロジェクト: Vake93/cca.server
 public OAuthLogin(
     OAuthLoginDto loginRequest,
     CloudTable usersTable,
     ILogger logger)
 {
     _loginRequest = loginRequest;
     _usersTable   = usersTable;
     _logger       = logger;
 }
コード例 #2
0
        public async Task <object> SwaggerLogin([FromForm] OAuthLoginDto model)
        {
            if (model.GrantType != "password")
            {
                return(new BadRequestResult());
            }
            var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);

            if (result.Succeeded)
            {
                var appUser = _userManager.Users.Include(u => u.DeviceTokens).Include(i => i.RefreshTokens).SingleOrDefault(r => r.Email == model.Username);
                return(await GetSuccessfulOAuthLoginResponse(appUser));
            }
            throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
        }
コード例 #3
0
ファイル: Validator.cs プロジェクト: Vake93/cca.server
        public static bool ValidateRequest(OAuthLoginDto loginRequest)
        {
            var hasErrors = false;
            var errors    = new StringBuilder();

            if (string.IsNullOrEmpty(loginRequest?.State))
            {
                hasErrors = true;
                errors.AppendLine($"{nameof(loginRequest.State)} is required.");
            }

            if (string.IsNullOrEmpty(loginRequest?.Token))
            {
                hasErrors = true;
                errors.AppendLine($"{nameof(loginRequest.Token)} is required.");
            }

            if (hasErrors)
            {
                throw new ValidationException(errors.ToString());
            }

            return(true);
        }
コード例 #4
0
 public async Task <IActionResult> FacebookLogin(OAuthLoginDto loginDto)
 {
     return(this.GenerateResponse(await _authService.FacebookLogin(loginDto)));
 }
コード例 #5
0
ファイル: AuthService.cs プロジェクト: jriley15/jthreads-api
        public async Task <Response> FacebookLogin(OAuthLoginDto loginDto)
        {
            var request = new HttpRequestMessage(HttpMethod.Get,
                                                 $"https://graph.facebook.com/" + loginDto.UserId +
                                                 "?access_token=" + loginDto.AccessToken + "&fields=email,name");

            var client   = _clientFactory.CreateClient();
            var response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                return(new Response()
                       .WithError("*", "Unable to authenticate with Facebook"));
            }

            var responseStream = await response.Content.ReadAsStreamAsync();

            var user = await JsonSerializer.DeserializeAsync
                       <FacebookUserDto>(responseStream, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

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

            //Check if this user has signed in before (if we have a AspNetUser record for them)
            if (appUser != null)
            {
                if (appUser.AuthType != AuthType.Facebook)
                {
                    return(new Response().WithError("*", "Account already authenticated with " + appUser.AuthType.ToString()));
                }
                //await _signInManager.SignInAsync(appUser, false);
            }

            //No existing sign ins for this user, let's create a record for them
            else
            {
                appUser = new ApplicationUser
                {
                    //hack for now - force users to activate email before logging in?
                    UserName    = user.Email,
                    Email       = user.Email,
                    DisplayName = user.Name.Split(" ")[0],
                    AuthType    = AuthType.Facebook
                };
                var result = await _userManager.CreateAsync(appUser);

                if (!result.Succeeded)
                {
                    return(new Response()
                           .WithErrors(result.Errors
                                       .Select(error => new Response.Error()
                    {
                        Key = error.Code == "DuplicateUserName" ? "email" : "*",
                        Msg = error.Code == "DuplicateUserName" ? "Email already in use" : error.Description
                    }).ToList()));
                }
            }

            //Create JWT and cookie for user and return success
            var token = GenerateJwt(appUser).ToString();

            GenerateCookie(token);

            return(new DataResponse <TokenDto>()
                   .WithData(new TokenDto()
            {
                Token = token
            }));
        }
コード例 #6
0
ファイル: AuthService.cs プロジェクト: jriley15/jthreads-api
        public async Task <Response> GoogleLogin(OAuthLoginDto loginDto)
        {
            var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
            {
                ClientSecrets = new ClientSecrets()
                {
                    ClientId     = _configuration["GoogleClientId"],
                    ClientSecret = _configuration["GoogleClientSecret"]
                },
                Scopes = new[] { "email", "profile" },
            });

            try
            {
                //Exchange / validate code with Google
                var googleToken = await flow.ExchangeCodeForTokenAsync("user", loginDto.Code,
                                                                       _configuration["GoogleRedirectUri"], CancellationToken.None);

                var payload = (await GoogleJsonWebSignature.ValidateAsync(googleToken.IdToken,
                                                                          new GoogleJsonWebSignature.ValidationSettings()));
                var appUser = await _userManager.FindByNameAsync(payload.Email);

                //Check if this user has signed in before (if we have a AspNetUser record for them)
                if (appUser != null)
                {
                    if (appUser.AuthType != AuthType.Google)
                    {
                        return(new Response().WithError("*", "Account already authenticated with " + appUser.AuthType.ToString()));
                    }
                    if (appUser.AvatarUrl != payload.Picture)
                    {
                        appUser.AvatarUrl = payload.Picture;
                        await _userManager.UpdateAsync(appUser);
                    }
                    //await _signInManager.SignInAsync(appUser, false);
                }

                //No existing sign ins for this user, let's create a record for them
                else
                {
                    appUser = new ApplicationUser
                    {
                        //hack for now - force users to activate email before logging in?
                        UserName    = payload.Email,
                        Email       = payload.Email,
                        DisplayName = payload.GivenName,
                        AuthType    = AuthType.Google,
                        AvatarUrl   = payload.Picture
                    };
                    var result = await _userManager.CreateAsync(appUser);

                    if (!result.Succeeded)
                    {
                        return(new Response()
                               .WithErrors(result.Errors
                                           .Select(error => new Response.Error()
                        {
                            Key = error.Code == "DuplicateUserName" ? "email" : "*",
                            Msg = error.Code == "DuplicateUserName" ? "Email already in use" : error.Description
                        }).ToList()));
                    }
                }

                //Create JWT and cookie for user and return success
                var token = GenerateJwt(appUser).ToString();
                GenerateCookie(token);

                return(new DataResponse <TokenDto>()
                       .WithData(new TokenDto()
                {
                    Token = token
                }));
            }
            catch (Exception e)
            {
                return(new Response()
                       .WithError("*", "Error authenticating with Google: " + e.Message));
            }
        }