예제 #1
0
        public async Task <AuthenResponseModel> GetAccessToken(LoginViewModel model)
        {
            try
            {
                var loginAsJson = JsonSerializer.Serialize(model);

                var response = await _httpClient.PostAsync($"api/{_apiOptions.Version}/Token/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));

                var loginResult = JsonSerializer.Deserialize <AuthenResponseModel>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });

                if (!response.IsSuccessStatusCode)
                {
                    loginResult.Successful = false;
                    return(loginResult);
                }

                await _localStorage.SetItemAsync("authToken", loginResult.AuthenToken);

                ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginResult.Email);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.AuthenToken);
                loginResult.Successful = true;
                return(loginResult);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(new AuthenResponseModel()
                {
                    Successful = false
                });
            }
        }
        public async Task <bool> Login(LoginModel user)
        {
            var response = await _client.PostAsJsonAsync(Endpoints.LoginEndpoint, user);

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }

            var content = await response.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <TokenResponse>(content);

            //store the token
            await _localStorage.SetItemAsync("authToken", token.Token);

            //change the authorization state of the application
            //we need to call this to do the login
            await((APIAuthenticationStateProvider)_authenticationStateProvider).LogginIn();

            //setting the default request header, this is not necessary because we are already adding this to the call everytime
            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("bearer", token.Token);
            return(true);
        }
        public async Task SetCurrentCultureAsync(string cultureCode)
        {
            var culture = new CultureInfo(cultureCode);

            SetCurrentCultureForApplication(culture);
            await _localStorageService.SetItemAsync(LocalStorageKeys.CURRENT_CULTURE, cultureCode);
        }
        public async Task <bool> Login(LoginModel user)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, Endpoints.LoginEndpoint)
            {
                Content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json")
            };

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

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }

            var content = await response.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <TokenResponse>(content);

            //Store Token
            await _localStorage.SetItemAsync("authToken", token.Token);

            //Change auth state of app
            await((ApiAuthenticationStateProvider)_authenticationStateProvider).LoggedIn();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.Token);

            return(true);
        }
    public async Task <ProjectsMetadataContainer?> Migrate(ProjectsMetadataContainer?container)
    {
        if (container?.Version == 1 && container.Item?.Count > 1)
        {
            List <int>             checkedIds    = new();
            List <ProjectMetadata> itemsToRemove = new();

            foreach (var item in container.Item)
            {
                if (!checkedIds.Contains(item.Id))
                {
                    checkedIds.Add(item.Id);
                }
                else
                {
                    itemsToRemove.Add(item);
                }
            }

            foreach (var itemToRemove in itemsToRemove)
            {
                container.Item.Remove(itemToRemove);
            }

            container.Version = 2;
        }

        if (container != null)
        {
            await _localStorage.SetItemAsync(container.StorageTableName, container);
        }

        return(container);
    }
        public async Task <AuthenticatedUserModel> Login(AuthenticationUserModel authenticationUserModel)
        {
            var data = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "password"),
                new KeyValuePair <string, string>("username", authenticationUserModel.Email),
                new KeyValuePair <string, string>("password", authenticationUserModel.Password),
            });

            string api        = _configuration["apiLocation"] + _configuration["tokenEndpoint"];
            var    authResult = await _httpClient.PostAsync(api, data);

            var authContent = await authResult.Content.ReadAsStringAsync();

            if (authResult.IsSuccessStatusCode == false)
            {
                return(null);
            }

            var result = JsonSerializer.Deserialize <AuthenticatedUserModel>(authContent, new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            await _localStorageService.SetItemAsync(authTokenStorageKey, result.Access_Token);

            ((AuthStateProvider)_authenticationStateProvider).NotifyUserAuthentication(result.Access_Token);

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Access_Token);

            return(result);
        }
        public async Task <bool> Login(LoginModel user)
        {
            var response = await _client.PostAsJsonAsync(Endpoints.LoginrUrl, user);

            if (response.IsSuccessStatusCode == false)
            {
                return(false);
            }

            // get the Token from the response
            var content = await response.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <TokenResponse>(content);

            // Store token
            await _localStorage.SetItemAsync("authToken", token.Token);

            // Change State of the app
            await _authStateProvider.LoggedIn();

            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("bearer", token.Token);

            return(true);
        }
예제 #8
0
        public async Task <bool?> SignInAsync(string email, string password)
        {
            var response = await _userService.SignInAsync(new SignInRequest
            {
                Email    = email,
                Password = password
            });

            if (response?.HttpResponse is null)
            {
                return(null);
            }

            if (!response.Succeeded)
            {
                return(false);
            }

            User = new User
            {
                Id           = response.Value.Id,
                Email        = response.Value.Email,
                Role         = response.Value.Role,
                AccessToken  = response.Value.AccessToken,
                RefreshToken = response.Value.RefreshToken,
                Expires      = response.Value.Expires
            };
            await _localStorageService.SetItemAsync("user", User);

            return(true);
        }
예제 #9
0
        public async Task <LoginResponseDto> Login(LoginRequestDto userFromAuthentication)
        {
            var content     = JsonConvert.SerializeObject(userFromAuthentication);
            var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");
            var response    = await _client.PostAsync("api/account/login", bodyContent);

            var contentTemp = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <LoginResponseDto>(contentTemp);

            if (response.IsSuccessStatusCode)
            {
                await _localStorage.SetItemAsync(MagicStrings.Local_Token, result.Token);

                //await _localStorage.SetItemAsync(MagicStrings.Local_UserDetails, result.User);
                ((MyAuthenticationStateProvider)_authStateProvider).NotifyUserLoggedIn(result.Token);
                _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);
                return(new LoginResponseDto {
                    IsSuccessful = true
                });
            }
            else
            {
                return(result);
            }
        }
예제 #10
0
        public async Task <LoginResult> Login(LoginModel loginModel)
        {
            JsonContent content  = JsonContent.Create(loginModel);
            var         response = await _httpClient.PostAsync(GetApiEndpoint("login"), content);

            var loginResult = System.Text.Json.JsonSerializer.Deserialize <LoginResult>(
                await response.Content.ReadAsStringAsync(),
                new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            if (!response.IsSuccessStatusCode)
            {
                loginResult.Successful = false;
                loginResult.Error      = "Invalid username or password";
                return(loginResult);
            }

            loginResult.Successful = true;

            await _localStorage.SetItemAsync("authToken", loginResult.Token);

            ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.Email);

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);

            return(loginResult);
        }
예제 #11
0
        public async Task <LoginResult> Login(LoginModel loginModel)
        {
            //var loginAsJson = JsonSerializer.Serialize(loginModel);
            //var response = await _httpClient.PostAsync("api/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));
            //var loginResult = JsonSerializer.Deserialize<LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            //if (loginResult.Successful)
            //{
            //    await _localStorage.SetItemAsync("authToken", loginResult.Token);
            //    ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginResult.Token);
            //    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);

            //    return loginResult;
            //}

            //return loginResult;
            var result = await _httpClient.PostJsonAsync <LoginResult>("api/Login", loginModel);

            if (result.Successful)
            {
                await _localStorage.SetItemAsync("authToken", result.Token);

                ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(result.Token);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);

                return(result);
            }

            return(result);
        }
예제 #12
0
        private async Task SetCultureInternal(string cultureName)
        {
            var newCulture = GetCulture(cultureName);
            await _localStorageService.SetItemAsync(_blazorCultureKey, newCulture.Name).ConfigureAwait(true);

            CultureInfo.CurrentCulture = newCulture;
        }
예제 #13
0
 public async Task SaveApiKey()
 {
     if (HasApiKey)
     {
         await LocalStorage.SetItemAsync("GitterKey", apiKey);
     }
 }
예제 #14
0
        public async Task <Result> Login(LoginRequestModel model)
        {
            var response = await httpClient.PostAsJsonAsync("api/identity/login", model);

            if (!response.IsSuccessStatusCode)
            {
                var errors = await response.Content.ReadFromJsonAsync <string[]>();

                return(Result.Failure(errors));
            }

            var responseAsString = await response.Content.ReadAsStringAsync();

            var responseObject = JsonSerializer.Deserialize <LoginResponseModel>(responseAsString, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            var token = responseObject.Token;

            await localStorage.SetItemAsync("authToken", token);

            ((ApiAuthenticationStateProvider)authenticationStateProvider).MarkUserAsAuthenticated(model.Email);

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            return(Result.Success);
        }
예제 #15
0
        private async Task <AuthenticationState> CreateAuthenticationState(User user)
        {
            await _localStorageService.SetItemAsync("authToken", user.Token);

            _currentUserService.CurrentUser = user;
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", user.Token);

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(user.Token);

            var claims    = token.Claims.ToList();
            var roleClaim = claims.FirstOrDefault(c => c.Type == "role");

            if (roleClaim != null)
            {
                var newRoleClaim = new Claim(ClaimTypes.Role, roleClaim.Value);
                claims.Add(newRoleClaim);
            }

            Console.WriteLine(JsonSerializer.Serialize(claims));

            var claimsPrincipal = new ClaimsPrincipal(
                new ClaimsIdentity(claims, "apiauth"));

            //var claimsPrincipal = new ClaimsPrincipal(
            //	new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }, "apiauth"));
            return(new AuthenticationState(claimsPrincipal));
        }
예제 #16
0
        public async Task <bool> Authenticate(string email, string password)
        {
            try
            {
                AuthenticationRequest authenticationRequest = new AuthenticationRequest()
                {
                    Email = email, Password = password
                };
                var authenticationResponse = await _client.AuthenticateAsync(authenticationRequest);

                if (authenticationResponse.Token != string.Empty)
                {
                    await _localStorage.SetItemAsync("token", authenticationResponse.Token);

                    ((CustomAuthenticationStateProvider)_authenticationStateProvider).SetUserAuthenticated(email);
                    _client.HttpClient.DefaultRequestHeaders.Authorization
                        = new AuthenticationHeaderValue("bearer", authenticationResponse.Token);
                    return(true);
                }
                return(false);
            }
            catch
            {
                return(false);
            }
        }
예제 #17
0
        async Task MarkUserAsAuthenticated(string token)
        {
            await localStorage.SetItemAsync("authToken", token);

            ((ApiAuthenticationStateProvider)authenticationStateProvider).MarkUserAsAuthenticated(token);
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
        }
예제 #18
0
        public async Task <string> LoginUserAsync(LoginModel model)
        {
            var client = _clientFactory.CreateClient();

            var response = await client.PostAsJsonAsync <LoginModel>($"{_baseURL}Login", model);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync <UserResponse>();

                var userInfo = new UserModel()
                {
                    AccessToken = result.Message,
                };

                var handler = new JwtSecurityTokenHandler();
                var token   = handler.ReadJwtToken(result.Message);
                userInfo.UserName = token.Claims.First(c => c.Type == "UserName").Value;

                await _storageService.SetItemAsync("user", userInfo);

                await _autenticationStateProvide.GetAuthenticationStateAsync();

                return(string.Empty);
            }
            else
            {
                var result = await response.Content.ReadFromJsonAsync <UserResponse>();

                return(result.Message);
            }
        }
예제 #19
0
        public async Task <bool> Login(LoginModel user)
        {
            if (user == null)
            {
                return(false);
            }

            var response = await _client.PostAsJsonAsync(Endpoints.LoginEndpoint, user);

            if (!response.IsSuccessStatusCode)
            {
                return(false);
            }

            var content = await response.Content.ReadAsStringAsync();

            var token = JsonConvert.DeserializeObject <TokenResponse>(content);

            //Store Token
            await _localStorage.SetItemAsync("authToken", token.Token);

            //Change auth state of app
            await((ApiAuthenticationStateProvider)_authenticationStateProvider).LoggedIn();

            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("bearer", token.Token);

            return(true);
        }
예제 #20
0
        public async Task <bool> Login(TokenRequest user)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, Endpoints.LoginEndpoint);
            var myData  = new
            {
                Phone    = user.Phone,
                Password = user.Password
            };

            request.Content = new StringContent(JsonConvert.SerializeObject(myData), Encoding.UTF8, "application/json");
            var client = _client.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);

            var content = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <Wrapper.Result <TokenResponse> >(content);

            //Store Token
            await _localStorage.SetItemAsync("authToken", result.Data.Token);

            //Change auth state of app
            await((ApiAuthenticationStateProvider)_authenticationStateProvider)
            .LoggedIn();

            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("bearer", result.Data.Token);

            return(true);
        }
        public async Task <List <TLookupData> > List()
        {
            string key        = typeof(TLookupData).Name;
            var    cacheEntry = await _localStorageService.GetItemAsync <CacheEntry <List <TLookupData> > >(key);

            if (cacheEntry != null)
            {
                _logger.LogInformation($"Loading {key} from local storage.");
                if (cacheEntry.DateCreated.AddMinutes(1) > DateTime.UtcNow)
                {
                    return(cacheEntry.Value);
                }
                else
                {
                    _logger.LogInformation($"Cache expired; removing {key} from local storage.");
                    await _localStorageService.RemoveItemAsync(key);
                }
            }

            var types = await _catalogTypeService.List();

            var entry = new CacheEntry <List <TLookupData> >(types);
            await _localStorageService.SetItemAsync(key, entry);

            return(types);
        }
예제 #22
0
        public async Task <RepositoryResponce> Login(UserLoginDTO userData)
        {
            if (userData == null)
            {
                return(RepositoryResponce.ArgumentNullResponce);
            }
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            using var client = _ClientFactory.CreateClient();
            string             url = Flurl.Url.Combine(apiUrl, ConventionalUrls.LoginRelativeUrl);
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = new StringContent(JsonConvert.SerializeObject(userData), Encoding.UTF8, MediaTypeNames.Application.Json)
            };
            var responce = await client.SendAsync(httpRequestMessage);

            if (!responce.IsSuccessStatusCode)
            {
                return(RepositoryResponce.StatusCodeResponce(responce.StatusCode));
            }
            else
            {
                var loginData = JsonConvert.DeserializeObject <Data.DTOs.SessionDataObject>(await responce.Content.ReadAsStringAsync());
                await _LocalStorage.SetItemAsync(ConventionalKeys.TokenStorageKey, loginData.Token);

                await((ApiAuthentificationStateProvider)_AuthenticationStateProvider).LoggedIn();
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                    "bearer", loginData.Token);

                var reponse = RepositoryResponce.StatusCodeResponce(responce.StatusCode);
                reponse.Message = loginData.Answer;
                return(reponse);
            }
        }
예제 #23
0
        private async Task <string> RefreshTokenEndPoint(TokenModel tokenModel)
        {
            var response = await _httpClient.PostAsJsonAsync <TokenModel>("/account/activate-token-by-refreshtoken", tokenModel);

            if (!response.IsSuccessStatusCode)
            {
                return(string.Empty);
            }
            AuthResponse authResponse = await response.Content.ReadFromJsonAsync <AuthResponse>();

            await _localStorageService.SetItemAsync <string>("token", authResponse.Token);

            await _localStorageService.SetItemAsync <string>("refreshToken", authResponse.RefreshToken);

            return(authResponse.Token);
        }
예제 #24
0
        /// <summary>
        /// Login user to service
        /// </summary>
        /// <param name="loginModel"></param>
        /// <returns></returns>
        public async Task <LoginResult> Login(LoginInput loginModel)
        {
            var lr = new LoginResult
            {
                Successful = false,
                Error      = ""
            };
            var token = await GetAuthToken(loginModel.Username, loginModel.Password);

            await _localStorage.SetItemAsync(Const.TokenKey, token);

            if (string.IsNullOrWhiteSpace(token.AuthToken))
            {
                return(lr);
            }
            await((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(token);

            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(Const.TokenApiKey, token.AuthToken);


            lr.Successful = true;
            lr.Token      = token.AuthToken;
            return(lr);
        }
예제 #25
0
        public async Task <UserSignInResultDto> Login(UserLoginDto userLogin)
        {
            var result = await requestService.PostAsync <UserLoginDto, UserSignInResultDto>(
                $"{apiSettings.IndentityUrl}/authentication/login", userLogin);

            if (result.Success)
            {
                await localStorage.SetItemAsync("authToken", result.Token);

                await localStorage.SetItemAsync("authUser", result.User);

                ((ApiAuthenticationStateProvider)authenticationStateProvider).MarkUserAsAuthenticated(result.User);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);
            }
            return(result);
        }
예제 #26
0
        public async Task <SignInResult> PasswordSignInAsync(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (password is null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (!_systemSetting.UserName.Equals(userName) || !_systemSetting.Password.Equals(password))
            {
                return(SignInResult.Failed);
            }

            try
            {
                var token = _jsonWebTokenService.GetJsonWebToken();



                await _localStorageService.SetItemAsync(STORAGE_KEY, token);

                NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(new ClaimsPrincipal())));
                return(SignInResult.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(SignInResult.Failed);
            }
        }
        private async Task <ClaimsPrincipal> GetPrincipal()
        {
            var version = await localStorage.GetItemAsync <string>("version");

            var correctVersion = configuration.GetSection("Version").Value;

            if (version != correctVersion)
            {
                await localStorage.ClearAsync();

                await localStorage.SetItemAsync(nameof(version), correctVersion);
            }
            try
            {
                var telegramUserInfo = await localStorage.GetItemAsync <TelegramUserInfo>("telegramUserInfo");

                if (telegramUserInfo == null)
                {
                    Console.WriteLine("no user info");
                    return(new ClaimsPrincipal());
                }
                else
                {
                    var(success, claims) = await TryGetInternalClaims(telegramUserInfo);

                    if (success)
                    {
                        var tgIdentity       = TelegramWidgetClaimsIdentityGenerator.GetIdentityForUserInfo(telegramUserInfo);
                        var internalIdentity = new ClaimsIdentity(claims, InternalClaimConstants.IDENTITY_AUTH_TYPE);

                        return(new ClaimsPrincipal(new ClaimsIdentity[] { tgIdentity, internalIdentity }));
                    }
                    else
                    {
                        Console.WriteLine("can't login");

                        return(new ClaimsPrincipal());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("exception");
                Console.WriteLine(ex);
                return(new ClaimsPrincipal());
            }
        }
예제 #28
0
        private async Task SaveToken(HttpResponseMessage response)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            var jwt = Json.Deserialize <JwToken>(responseContent);

            await _localStorage.SetItemAsync("authToken", jwt.Token);
        }
        public async Task AuthenticateUserAsync(string userToken)
        {
            await _localStorage.SetItemAsync(TokenKey, userToken);

            var authState = this.BuildAuthenticationStateFromToken(userToken);

            NotifyAuthenticationStateChanged(Task.FromResult(authState));
        }
        public async Task Login(string token)
        {
            await _localStorage.SetItemAsync(_tokenkey, token);

            var authState = buildAuthenticationState(token);

            NotifyAuthenticationStateChanged(Task.FromResult(authState));
        }