public override async Task <AuthenticationState> GetAuthenticationStateAsync() { try { var savedToken = await _localStorage.GetItemAsStringAsync("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var tokenContent = _tokenHandler.ReadJwtToken(savedToken); var expiry = tokenContent.ValidTo; if (expiry < DateTime.Now) { await _localStorage.RemoveItemAsync("authToken"); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var claims = ParseClaims(tokenContent); var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); return(new AuthenticationState(user)); } catch (Exception) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } }
public async Task <List <MenuData> > LoadMenus() { var requestMessage = new HttpRequestMessage() { Method = new HttpMethod("Get"), RequestUri = new Uri(navigationManager.BaseUri + "api/menu/My"), }; var authToken = await local.GetItemAsStringAsync("authToken"); if (authToken == null) { if (navigationManager.Uri != "/Login") { navigationManager.NavigateTo("/Login"); return(null); } } requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken.Replace("\"", "")); var data = await httpClient.SendAsync(requestMessage); var str = await data.Content.ReadAsStringAsync(); var rtn = JsonSerializer.Deserialize <List <MenuData> >(str, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); localStorageService.MenuData = Task.FromResult(rtn); return(rtn); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var identity = new ClaimsIdentity(); try { var payloadStr = await _localStorage.GetItemAsStringAsync("auth"); if (!string.IsNullOrEmpty(payloadStr)) { var usr = JsonSerializer.Deserialize <CurrentUser>(payloadStr); var claims = new[] { new Claim(ClaimTypes.Name, usr.UserName), new Claim("Benutzer", usr.Description), new Claim("UserStatus", usr.UserStatus) }; identity = new ClaimsIdentity(claims, "Server authentication"); _sqlService.SetAuth(usr.AuthString); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } return(new AuthenticationState(new ClaimsPrincipal(identity))); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { string token = await localStorageService.GetItemAsStringAsync("token"); if (string.IsNullOrEmpty(token)) { return(anonymous); } string email = await localStorageService.GetItemAsStringAsync("email"); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Email, email) }, "jwtAuthType")); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); return(new AuthenticationState(claimsPrincipal)); }
public async override Task <AuthenticationState> GetAuthenticationStateAsync() { try { if (await _storageService.ContainKeyAsync("access_token")) { //Decrypt the token to use the content string accessToken = await _storageService.GetItemAsStringAsync("access_token"); var handler = new JwtSecurityTokenHandler(); var jwt = handler.ReadJwtToken(accessToken); var identity = new ClaimsIdentity(jwt.Claims, "Bearer"); var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); //Notify the application of the state change NotifyAuthenticationStateChanged(Task.FromResult(state)); //return the user with all the claims. return(state); } else { //return an empty claims principal return(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal())); } } catch (Exception e) { Console.WriteLine(e.Message); //Return an empty claims principal return(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal())); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { string authToken = await _localStorageService.GetItemAsStringAsync("authToken"); var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; if (!string.IsNullOrEmpty(authToken)) { try { identity = new ClaimsIdentity(ParseClaimsFromJwt(authToken), "jwt"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); await _bananaService.GetBananas(); } catch (Exception) { await _localStorageService.RemoveItemAsync("authToken"); identity = new ClaimsIdentity(); } } var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var token = await localStorageService.GetItemAsStringAsync(SessionStorageKey); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return(await base.SendAsync(request, cancellationToken)); }
public async Task <RepositoryResponce> ChangePassword(ChangePasswordDTO changePasswordDto) { if (changePasswordDto == null) { return(RepositoryResponce.ArgumentNullResponce); } System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; string url = Flurl.Url.Combine(_ApiUrl, ConventionalUrls.ChangePasswordRelativeUrl); try { _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( scheme: "bearer", parameter: await _LocalStorage.GetItemAsStringAsync(ConventionalKeys.TokenStorageKey) ); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(JsonConvert.SerializeObject(changePasswordDto), Encoding.UTF8, MediaTypeNames.Application.Json) }; var responce = await _Client.SendAsync(httpRequestMessage); PasswordActionAnswer answer = JsonConvert.DeserializeObject <PasswordActionAnswer>(await responce.Content.ReadAsStringAsync()); var repositoryReponce = RepositoryResponce.StatusCodeResponce(responce.StatusCode); repositoryReponce.Message = answer.ServerMessage; return(repositoryReponce); } catch (Exception e) { return(new RepositoryResponce() { Succeed = false, Errror = e.Message }); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { try { var accessToken = await _localStorageService.GetItemAsStringAsync(AccessToken); if (!string.IsNullOrWhiteSpace(accessToken)) { var autheticatedUser = await _httpClient.GetLoggedInUserAsync(accessToken); Console.WriteLine("autheticatedUser.First_Name)--autheticatedUser.First_Name) ---" + autheticatedUser.First_Name); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, autheticatedUser.FullName) }, " authentication type"); var user = new ClaimsPrincipal(identity); return(new AuthenticationState(user)); } else { var authenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); return(authenticationState); } } catch (Exception ex) { Console.WriteLine("GetLoggedInUserAsync exception --" + ex.ToString()); var authenticationState = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); return(authenticationState); } }
public async override Task <AuthenticationState> GetAuthenticationStateAsync() { try { if (await _storageService.ContainKeyAsync("access_token")) { string accessToken = await _storageService.GetItemAsStringAsync("access_token"); var handler = new JwtSecurityTokenHandler(); var jwt = handler.ReadJwtToken(accessToken); var identity = new ClaimsIdentity(jwt.Claims, "Bearer"); var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); } else { return(new AuthenticationState(new ClaimsPrincipal())); } } catch (Exception e) { Console.WriteLine(e.Message); return(new AuthenticationState(new ClaimsPrincipal())); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { // Get JWT string authToken = await _localStorageService.GetItemAsStringAsync("authToken"); var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; if (!string.IsNullOrEmpty(authToken)) { try { // Parse JWT and send it with every request identity = new ClaimsIdentity(ParseClaimsFromJwt(authToken), "jwt"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); } catch (Exception) { // Something went wrong, remove the token from loca storage. await _localStorageService.RemoveItemAsync("authToken"); identity = new ClaimsIdentity(); } } var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); }
public async Task <User> GetUserByJWTAsync() { //pulling the token from localStorage var jwtToken = await _localStorageService.GetItemAsStringAsync("jwt_token"); if (jwtToken == null) { return(null); } //preparing the http request var requestMessage = new HttpRequestMessage(HttpMethod.Post, "user/getuserbyjwt"); requestMessage.Content = new StringContent(jwtToken); requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //making the http request var response = await _httpClient.SendAsync(requestMessage); var responseStatusCode = response.StatusCode; var returnedUser = await response.Content.ReadFromJsonAsync <User>(); //returning the user if found if (returnedUser != null) { return(await Task.FromResult(returnedUser)); } else { return(null); } }
public async Task <string> FindAsync() { string token = await local.GetItemAsStringAsync(key); if (String.IsNullOrEmpty(token)) { token = await session.GetItemAsync <string>(key); } return(token); }
protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (await _storageService.ContainKeyAsync("access_token")) { string accessToken = await _storageService.GetItemAsStringAsync("access_token"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); } return(await base.SendAsync(request, cancellationToken)); }
public async Task <User> GetUserByJWTAsync() { //pulling the token from localStorage var jwtToken = await _localStorageService.GetItemAsStringAsync("jwt_token"); if (jwtToken == null) { return(null); } return(await _loginViewModel.GetUserByJWTAsync(jwtToken)); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; var authToken = await _localStorageService.GetItemAsStringAsync("authToken"); if (!string.IsNullOrEmpty(authToken)) { try { identity = new ClaimsIdentity(ParseClaimsFromJwt(authToken), "jwt"); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); await _bananaService.GetBananas(); } catch (Exception) { await _localStorageService.RemoveItemAsync("authToken"); identity = new ClaimsIdentity(); } } var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); /* * var state = new AuthenticationState(new ClaimsPrincipal()); * * if (await _localStorageService.GetItemAsync<bool>("isAuthenticated")) * { * var identity = new ClaimsIdentity( * new [] * { * new Claim(ClaimTypes.Name, "Georg") * }, "Test auth type"); * var user = new ClaimsPrincipal(identity); * state = new AuthenticationState(user); * * NotifyAuthenticationStateChanged(Task.FromResult(state)); * return state; * } * * NotifyAuthenticationStateChanged(Task.FromResult(state)); * return state; */ }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { try { //var tokenContent = await _localStorage.GetItemAsync<JwtSecurityToken>("authToken"); //if(tokenContent == null) //{ // return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); //} var savedToken = await _localStorage.GetItemAsStringAsync("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var tokenContent = _jwt.ReadJwtToken(savedToken); var expiry = tokenContent.ValidTo; if (expiry < DateTime.Now) { await _localStorage.RemoveItemAsync("authToken"); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } // Get Claims from token and Build auth user object var claims = ParseClaims(tokenContent); var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")); //return authenticated person return(new AuthenticationState(user)); } catch (Exception) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var token = await _localStorage.GetItemAsStringAsync("authToken"); if (token is null or "") { return(anonymus); } _http.DefaultRequestHeaders.Authorization = new("bearer", token); return(new(new(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType")))); }
public async Task <IReadOnlyList <Adoption> > Get() { var json = await localStorageService.GetItemAsStringAsync(storageKey); var adoptions = new List <Adoption>(); if (!string.IsNullOrEmpty(json)) { adoptions = JsonConvert.DeserializeObject <List <Adoption> >(json); } return(adoptions); }
public async Task UpdateQuantityFor(string itemId, int quantity) { var basketId = await _localStorage.GetItemAsStringAsync("_basket"); var content = new Dictionary <string, string>() { { "basketId", basketId }, { "itemId", itemId }, { "newQuantity", quantity.ToString() } }; await _httpClient.PostAsync("api/UpdateQuantity", new FormUrlEncodedContent(content)); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { Console.WriteLine("!! CustomAuthStateProvider - GetAuthenticationStateAsync"); //var login = new Login() //{ // Email = "*****@*****.**", // Password = "******" //}; //var result = await _http.PostAsJsonAsync("api/auth/login", login); //var t = await result.Content.ReadAsStringAsync(); string token = await localStorageService.GetItemAsStringAsync("token"); //if (string.IsNullOrWhiteSpace(token)) { // token = t; //} var identity = new ClaimsIdentity(); _http.DefaultRequestHeaders.Authorization = null; if (!string.IsNullOrEmpty(token)) { identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"); var expClaim = identity.Claims.First(x => x.Type == "exp").Value; Console.WriteLine(expClaim); var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expireDateTime = epoch.AddSeconds(double.Parse(expClaim)); if (expireDateTime < DateTime.UtcNow) { identity = new ClaimsIdentity(); Console.WriteLine("has expired"); } else { Console.WriteLine("token is valid"); // adding the token to all http calls _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); _dispatcher.Dispatch(new Store.SessionUseCase.LoggedInViaTokenAction()); } } var user = new ClaimsPrincipal(identity); var state = new AuthenticationState(user); var test = state.User.IsInRole("role2"); Console.WriteLine($"!! User is in role role2: {test}"); NotifyAuthenticationStateChanged(Task.FromResult(state)); return(state); }
public async Task <string> LoadFromRepositoryAsync(string key, bool Decrypt = false) { try { return(await localStorage.GetItemAsStringAsync(key)); } catch (Exception) { return(string.Empty); // Possible that device doesn't support secure storage on device. } }
public async Task Initialize() { string json = await _browserStorage.GetItemAsStringAsync("DC_Browser_Storage"); if (!String.IsNullOrWhiteSpace(json)) { Storage = JsonConvert.DeserializeObject <Dictionary <Guid, Project> >(json); } if (Storage == null) { Storage = new Dictionary <Guid, Project>(); } Initialized = true; }
private async Task <TokenInfo> GetToken() { var accessToken = await _localStorage.GetItemAsStringAsync("token"); if (!String.IsNullOrEmpty(accessToken)) { var token = new JwtSecurityToken(accessToken); if (token.ValidTo > DateTime.UtcNow.AddMinutes(-5)) { return(new TokenInfo("Bearer", accessToken, "", token.ValidTo)); } } return(null); }
public async Task <HttpRequestMessage> CreateMessageAsync(HttpMethod method, string url) { var message = new HttpRequestMessage(method, url); if (_LocalStorage != null) { string token = await _LocalStorage.GetItemAsStringAsync(ConventionalKeys.TokenStorageKey); if (!String.IsNullOrWhiteSpace(token)) { message.Headers.Authorization = new AuthenticationHeaderValue("bearer", token); } } return(message); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var savedToken = await localStorage.GetItemAsStringAsync("authToken"); if (string.IsNullOrEmpty(savedToken)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var identity = new ClaimsIdentity(universalService.ParseClaimsFromJwt(savedToken), "jwtApi"); var user = new ClaimsPrincipal(identity); return(await Task.FromResult(new AuthenticationState(user))); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var tokenString = await _localStorage.GetItemAsStringAsync("authToken"); if (string.IsNullOrWhiteSpace(tokenString)) { return(_anonymous); } var token = new JwtSecurityToken(tokenString); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", tokenString); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "jwtAuthType")))); }
public static async Task <PeerMessage> GetFromStorage(string key) { var json = await _localStorage.GetItemAsStringAsync(key); _log.LogDebug($"Getting: {json}"); if (!string.IsNullOrEmpty(json)) { var savedGuest = JsonConvert.DeserializeObject <PeerMessage>(json); _log.LogDebug($"Guest name: {savedGuest.DisplayName}"); return(savedGuest); } return(null); }
public async Task <IReadOnlyList <int> > GetBestScores() { var json = await localStorageService.GetItemAsStringAsync(storageKey); var bestScores = new List <int>(); if (!string.IsNullOrEmpty(json)) { bestScores = JsonConvert.DeserializeObject <List <int> >(json); } while (bestScores.Count < 5) { bestScores.Add(0); } return(bestScores); }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var token = await _localStorage.GetItemAsStringAsync("token"); if (!string.IsNullOrEmpty(token)) { var authUser = new ClaimsPrincipal(new ClaimsIdentity( new List <Claim>() { new Claim(ClaimTypes.Name, "admin") }, "jwt")); return(new AuthenticationState(authUser)); } return(new(new ClaimsPrincipal(new ClaimsIdentity()))); }