public async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            ExternalLoginDto info = null;

            foreach (var argument in context.ActionArguments.Values.Where(v => v is ExternalLoginDto || v is string))
            {
                if (argument is ExternalLoginDto)
                {
                    info = argument as ExternalLoginDto;
                }
            }
            if (info == null)
            {
                throw new Exception("Parameter missing.");
            }

            if (string.IsNullOrEmpty(info.ProviderAccessToken))
            {
                throw new Exception("Provider token empty or null");
            }

            await VerifyExternalAccessToken(info);

            var resultContext = await next();
        }
示例#2
0
        public async Task <IActionResult> ExternalLogin([FromBody] ExternalLoginDto userDto)
        {
            var user = await _userManager.FindByNameAsync(userDto.userName);

            if (user == null)
            {
                user = new IdentityUser
                {
                    UserName       = userDto.userName,
                    Email          = userDto.email,
                    EmailConfirmed = true
                };
                var result = await _userManager.CreateAsync(user);

                await _userManager.AddToRoleAsync(user, Constants.UserRole);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    return(Ok(await GenerateJwtToken(user.UserName, user)));
                }
            }
            else
            {
                await _signInManager.SignInAsync(user, false);

                return(Ok(await GenerateJwtToken(user.UserName, user)));
            }

            throw new ApplicationException("UNKNOWN_ERROR");
        }
示例#3
0
        public async Task <IdentityResult> ExternalRegister(ExternalLoginInfo info, ExternalLoginDto model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            IdentityResult result;

            if (user != null)
            {
                result = await _userManager.AddLoginAsync(user, info);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent : false);
                }
            }
            else
            {
                model.Principal = info.Principal;
                user            = _mapper.Map <AppUser>(model);
                result          = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);
                    }
                }
            }
            return(result);
        }
        public static IIdentityUserLogin BuildEntity(ExternalLoginDto dto)
        {
            var entity = new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, dto.UserId, dto.CreateDate);

            // reset dirty initial properties (U4-1946)
            entity.ResetDirtyProperties(false);
            return(entity);
        }
示例#5
0
        public IIdentityUserLogin BuildEntity(ExternalLoginDto dto)
        {
            var entity = new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, dto.UserId, dto.CreateDate);

            //on initial construction we don't want to have dirty properties tracked
            // http://issues.umbraco.org/issue/U4-1946
            entity.ResetDirtyProperties(false);
            return(entity);
        }
示例#6
0
    protected override void PersistUpdatedItem(IIdentityUserLogin entity)
    {
        entity.UpdatingEntity();

        ExternalLoginDto dto = ExternalLoginFactory.BuildDto(entity);

        Database.Update(dto);

        entity.ResetDirtyProperties();
    }
示例#7
0
        public static IIdentityUserLogin BuildEntity(ExternalLoginDto dto)
        {
            var entity = new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, dto.UserId.ToString(CultureInfo.InvariantCulture), dto.CreateDate)
            {
                UserData = dto.UserData
            };

            // reset dirty initial properties (U4-1946)
            entity.ResetDirtyProperties(false);
            return(entity);
        }
示例#8
0
        public IEnumerable <WeatherForecast> Post([FromBody] ExternalLoginDto dto)
        {
            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
示例#9
0
    protected override void PersistNewItem(IIdentityUserLogin entity)
    {
        entity.AddingEntity();

        ExternalLoginDto dto = ExternalLoginFactory.BuildDto(entity);

        var id = Convert.ToInt32(Database.Insert(dto));

        entity.Id = id;

        entity.ResetDirtyProperties();
    }
示例#10
0
        public ExternalLoginDto BuildDto(IIdentityUserLogin entity)
        {
            var dto = new ExternalLoginDto
            {
                Id            = entity.Id,
                CreateDate    = entity.CreateDate,
                LoginProvider = entity.LoginProvider,
                ProviderKey   = entity.ProviderKey,
                UserId        = entity.UserId
            };

            return(dto);
        }
示例#11
0
        public static ExternalLoginDto BuildDto(IIdentityUserLogin entity)
        {
            var dto = new ExternalLoginDto
            {
                Id            = entity.Id,
                CreateDate    = entity.CreateDate,
                LoginProvider = entity.LoginProvider,
                ProviderKey   = entity.ProviderKey,
                UserId        = int.Parse(entity.UserId, CultureInfo.InvariantCulture), // TODO: This is temp until we change the ext logins to use GUIDs
                UserData      = entity.UserData
            };

            return(dto);
        }
        public static ExternalLoginDto BuildDto(IIdentityUserLogin entity)
        {
            var asExtended = entity as IIdentityUserLoginExtended;
            var dto        = new ExternalLoginDto
            {
                Id            = entity.Id,
                CreateDate    = entity.CreateDate,
                LoginProvider = entity.LoginProvider,
                ProviderKey   = entity.ProviderKey,
                UserId        = entity.UserId,
                UserData      = asExtended?.UserData
            };

            return(dto);
        }
示例#13
0
        public static IIdentityUserLogin BuildEntity(ExternalLoginDto dto)
        {
            //If there exists a UserId - this means the database is still not migrated. E.g on the upgrade state.
            //At this point we have to manually set the key, to ensure external logins can be used to upgrade
            var key = dto.UserId.HasValue ? dto.UserId.Value.ToGuid().ToString() : dto.UserOrMemberKey.ToString();

            var entity = new IdentityUserLogin(dto.Id, dto.LoginProvider, dto.ProviderKey, key, dto.CreateDate)
            {
                UserData = dto.UserData
            };

            // reset dirty initial properties (U4-1946)
            entity.ResetDirtyProperties(false);
            return(entity);
        }
        public async Task ExternalLogin_Failed_ReturnsUnauthorized()
        {
            var loginDto = new ExternalLoginDto()
            {
                Provider = ExternalAuthenticationProvider.Google, IdToken = "idToken"
            };
            var signInResponse = MySignInResult.Failed;

            _mockExternalSignInService.Setup(x => x.SignInExternal(loginDto.Provider, loginDto.IdToken))
            .ReturnsAsync((signInResponse, null));

            var result = await _sut.ExternalLogin(loginDto);

            result.Result.Should().BeAssignableTo(typeof(UnauthorizedObjectResult));
        }
示例#15
0
        public IEnumerable <ExternalLoginDto> GetExternalLogins(string returnUrl, bool generateState = false)
        {
            IEnumerable <AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
            List <ExternalLoginDto> logins = new List <ExternalLoginDto>();

            string state;

            if (generateState)
            {
                const int strengthInBits = 256;
                state = RandomOAuthStateGenerator.Generate(strengthInBits);
            }
            else
            {
                state = null;
            }

            foreach (AuthenticationDescription description in descriptions)
            {
                ExternalLoginDto login = new ExternalLoginDto
                {
                    Name = description.Caption,
                    Url  = Url.Route("ExternalLogin", new
                    {
                        provider      = description.AuthenticationType,
                        response_type = "token",
                        client_id     = Startup.PublicClientId,
                        redirect_uri  = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
                        state         = state
                    }),
                    State = state
                };
                logins.Add(login);
            }

            return(logins);
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginDto model, string returnUrl = "/")
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var info = await _userService.GetExternalLoginInfo();

            if (info == null)
            {
                return(View());
            }
            var result = await _userService.ExternalRegister(info, model);

            if (result.Succeeded)
            {
                return(RedirectToLocal(returnUrl));
            }
            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }
            return(View(nameof(ExternalLoginConfirmation), model));
        }
        public async Task ExternalLogin_Successful_ReturnsLoginData()
        {
            var loginDto = new ExternalLoginDto()
            {
                Provider = ExternalAuthenticationProvider.Google, IdToken = "idToken"
            };
            var signInResponse = MySignInResult.Success;
            var signInData     = new SignInData {
                Token = new TokenModel("Bearer", "veryFancyToken", DateTime.Now.AddDays(5))
            };

            _mockExternalSignInService.Setup(x => x.SignInExternal(loginDto.Provider, loginDto.IdToken))
            .ReturnsAsync((signInResponse, signInData));

            var result = await _sut.ExternalLogin(loginDto);

            result.Result.Should().BeAssignableTo(typeof(OkObjectResult));
            var tokenResult = (LoginResponseDto)((OkObjectResult)result.Result).Value;

            tokenResult.TokenType.Should().Be(signInData.Token.TokenType);
            tokenResult.AccessToken.Should().Be(signInData.Token.AccessToken);
            tokenResult.Username.Should().Be(signInData.Username);
            tokenResult.ExpiresIn.Should().BePositive();
        }
        private async Task VerifyExternalAccessToken(ExternalLoginDto info)
        {
            if (string.IsNullOrEmpty(info.ProviderAccessToken))
            {
                throw new Exception("NoProviderAccessTokenSuplied");
            }

            if (string.IsNullOrEmpty(info.ProviderKey))
            {
                throw new Exception("NoProviderUserIdSuplied");
            }

            string verifyTokenEndPoint;
            bool   isValid = false;

            if (info.ProviderType == ExternalLoginProviderType.Facebook)
            {
                //You can get it from here: https://developers.facebook.com/tools/accesstoken/
                //More about debug_tokn here: http://stackoverflow.com/questions/16641083/how-does-one-get-the-app-access-token-for-debug-token-inspection-on-facebook
                var appToken = "";// _configService.GetValue<string>("Authentication:Facebook:AppToken");
                verifyTokenEndPoint = string.Format("https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", info.ProviderAccessToken, appToken);
            }
            else if (info.ProviderType == ExternalLoginProviderType.Google)
            {
                verifyTokenEndPoint = string.Format("https://oauth2.googleapis.com/tokeninfo?id_token={0}", info.ProviderAccessToken);
            }
            else
            {
                throw new Exception("NotSupportedExternalProvider");
            }

            var client = new HttpClient();
            var uri    = new Uri(verifyTokenEndPoint);
            HttpResponseMessage response;

            try
            {
                response = await client.GetAsync(uri);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("ErrorDuringValidatingExternalProvider_ErrorDetail{0}", ex.Message));
            }

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();

                if (string.IsNullOrEmpty(content))
                {
                    throw new Exception("ProviderUrlReturnedNoResult");
                }

                JObject jObj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(content);


                if (info.ProviderType == ExternalLoginProviderType.Facebook)
                {
                    //if (string.Equals(_configService.GetValue<string>("Authentication:Facebook:AppId"), (string)jObj.SelectToken("data.app_id"), StringComparison.OrdinalIgnoreCase))
                    //{
                    //    if (string.Equals(userId, (string)jObj.SelectToken("data.user_id"), StringComparison.OrdinalIgnoreCase))
                    //    {
                    //        isValid = true;
                    //    }
                    //}
                }
                else if (info.ProviderType == ExternalLoginProviderType.Google)
                {
                    if (string.Equals(info.ProviderKey, (string)jObj.SelectToken("sub"), StringComparison.OrdinalIgnoreCase) &&
                        ((string)jObj.SelectToken("iss")).Contains("accounts.google.com", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!string.Equals(info.Email, (string)jObj.SelectToken("email"), StringComparison.OrdinalIgnoreCase))
                        {
                            throw new Exception("EmailShouldNotBeModifiedWhichComingFromAProviderLikeGoogleFacebookEtc");
                        }

                        if (!(bool)jObj.SelectToken("email_verified"))
                        {
                            throw new Exception("PleaseUseAnAlreadyConfirmedEmailWhichComingFromAProviderLikeGoogleFacebookEtc");
                        }
                        isValid = true;
                    }
                }
            }
            if (!isValid)
            {
                throw new Exception(string.Format("ProviderUserIsNotAuthorized_AccessTokenLengthIs{0}", info.ProviderAccessToken.Length));
            }
        }
 public Task <IdentityResult> ExternalRegister(ExternalLoginInfo info, ExternalLoginDto model)
 {
     throw new NotImplementedException();
 }