public async Task CheckAndRetrieveSessionAsync() { // TODO: Once we have a JWT working, then all we really need to do is pull the token from the store and decode that, as well // as checking token expiry etc. var state = await _localStorage.GetItem <bool>("isloggedin"); if (state == true) { _isLoggedIn = true; } var loginName = await _localStorage.GetItem <string>("loginName"); if (!String.IsNullOrEmpty(loginName)) { _loginName = loginName; } var emailAddress = await _localStorage.GetItem <string>("emailAddress"); if (!String.IsNullOrEmpty(emailAddress)) { _emailAddress = emailAddress; } var displayName = await _localStorage.GetItem <string>("displayName"); if (!String.IsNullOrEmpty(displayName)) { _displayName = displayName; } }
public async Task Initialise() { int done = 10; while (done-- > 0) { if (ComponentContext.IsConnected) { try { await LocalisationHelper.BuildLocalCulture(); await LocalisationHelper.BuildLocalTimeZone(); Console.WriteLine($"reading GitterKey from storage - {done} attempts left"); SetApiKey(await LocalStorage.GetItem <string>("GitterKey")); break; } catch (Exception e) { Console.WriteLine(e); } } else { Console.WriteLine("Waiting for connection..."); } await Task.Delay(1000); } initialised = true; }
/// <inheritdoc/> public async Task <bool> IsInRoles(string[] roles) { if (roles == null || !roles.Any()) { return(false); } var authData = await _localStorage.GetItem <AuthData>(LocalStorageConstants.AuthData); if (authData == null) { return(false); } return(authData !.Roles.Any(_ => roles.Contains(_))); }
public async Task <ServiceResult <T> > SendAuthDeleteRequestAsync <T>(string uri) { var accessToken = await _localStorageService.GetItem <string>("accessToken"); var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Delete, RequestUri = new Uri(uri), Headers = { { "Authorization", $"Bearer {accessToken}" }, { "Accept", "application/json" } } }; return(await SendRequest <T>(httpRequestMessage)); }
private async Task SetAuthorizationHeader() { if (!_httpClient.DefaultRequestHeaders.Contains("Authorization")) { var token = await _localStorage.GetItem <string>("authToken"); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } }
public async Task Initialize() { var token = await _storageService.GetItem <string>("token"); if (!string.IsNullOrWhiteSpace(token)) { userClaims = new UserClaims(token); IsAuthenticated = true; } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var token = await _localStorage.GetItem <string>("Token"); if (string.IsNullOrWhiteSpace(token)) { return(_anonymous); } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(JwtParser.ParseClaimsFromJwt(token), "jwtAuthType")))); }
//helpers methods private async Task <HttpResponseMessage> SendRequest(HttpRequestMessage request) { // add jwt auth header if user is logged in var user = await _localStorageService.GetItem <AuthenticateResponse>("user"); if (user != null) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token); } return(await _http.SendAsync(request)); }
private async Task SetAuth() { if (!HttpClient.DefaultRequestHeaders.Contains("Authorization")) { var token = await LocalStorage.GetItem <string>("authToken"); if (!string.IsNullOrEmpty(token)) { HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } } }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var authToken = await _localStorage.GetItem <string>(LocalStorageConstants.AuthToken); if (!string.IsNullOrWhiteSpace(authToken)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authToken); } request.Headers.AcceptLanguage.Clear(); request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en")); return(await base.SendAsync(request, cancellationToken)); }
public async Task Initialize() { User = await _localStorageService.GetItem <User>("user"); if (User != null) { await _orderService.UpdMyActiveOrder(); // Initialize web sockets connection await _webSocketService.InitializeWebSocketsAsync(User.Id); } }
public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var savedToken = await _localStorage.GetItem("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt")))); }
public MainServiceLayer(ILocalStorageService localStorage, IHttpService httpService, MatchServiceIndexedDb matchServiceIndexDb) { _localStorage = localStorage; _httpService = httpService; _matchServiceIndexDb = matchServiceIndexDb; Task t3 = Task.Run(async() => { var model = _localStorage.GetItem <ClientSetting>(CommonVariables.ClientSettingsKey); Offline = model?.OfflineMode ?? false; _init = true; var openResult = await matchServiceIndexDb.OpenIndexedDb(); }); }
public async Task Initialize() { User = await _localStorageService.GetItem <User>("user"); // Initialize web sockets connection if (User != null) { await _orderService.UpdMyActiveOrder(); await _webSocketService.InitializeWebSocketsAsync(User.Id); // Order foundActiveOrder = await _orderService.GetActiveOrder(); // Console.WriteLine($"foundActiveOrder: {JsonConvert.SerializeObject(foundActiveOrder)}"); } }
// helper methods private async Task <T> sendRequest <T>(HttpRequestMessage request) { string bearer = await _localStorageService.GetItem <string>(StaticValues.BEARER); request.Headers.Add(StaticValues.Authorization, StaticValues.BEARER + " " + bearer); //request.Headers.Add(StaticValues.APP_CORS, "*"); // add basic auth header if user is logged in and request is to the api url var user = await _localStorageService.GetItem <User>(StaticValues.USERLS); var isApiUrl = !request.RequestUri.IsAbsoluteUri; if (user != null && isApiUrl) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", user.AuthData); } using var response = await _httpClient.SendAsync(request); // auto logout on 401 response if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("logout"); return(default);
private async Task <T> SendRequest <T>(HttpRequestMessage request) { var user = await _localStorageService.GetItem <User>("user"); var isApiUrl = !request.RequestUri.IsAbsoluteUri; if (user != null && isApiUrl) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token); } using var response = await _httpClient.SendAsync(request); if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("logout"); return(default);
public async Task Initialize() { var loggedUser = _localStorageService.GetItem <ShooterContract>(userKey); if (loggedUser == null) { return; } var secret = await _localStorageService.DecodeSecret(loggedUser.Username, authCode); if (string.IsNullOrEmpty(secret)) { return; } var userParams = secret.DecodeBase64().Split(":"); await Login(userParams[0], userParams[1]); }
private async Task <T> SendRequest <T>(HttpRequestMessage request) { var isApiUrl = !request.RequestUri.IsAbsoluteUri; var auth = await _localStorageService.GetItem <Auth>("auth"); if (isApiUrl && auth != null) { request.Headers.Add("Role", auth.RoleType.ToString()); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", auth.AuthData); } var response = await _httpClient.SendAsync(request); // auto logout on 401 response if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("logout"); return(default);
// helper methods private async Task <T> SendRequestAsync <T>(HttpRequestMessage request) { // add jwt auth header if user is logged in and request is to the api url var token = await _localStorageService.GetItem <LoginResult>("token"); var isApiUrl = !request.RequestUri.IsAbsoluteUri; if (token != null && isApiUrl) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken); } using var response = await _httpClient.SendAsync(request); // auto logout on 401 response if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("logout"); return(default);
private async Task <T> sendRequest <T>(HttpRequestMessage request) { // add basic auth header if user is logged in and request is to the api url var user = await _localStorageService.GetItem <TokenModel>("tokenModel"); var isApiUrl = !request.RequestUri.IsAbsoluteUri; if (user != null && isApiUrl) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", user.Token); } using var response = await _httpClient.SendAsync(request); // auto logout on 401 response if (response.StatusCode == HttpStatusCode.Unauthorized) { _navigationManager.NavigateTo("logout"); return(default);
public async Task Initialise() { int done = 10; while (done-- > 0) { if (ComponentContext.IsConnected) { try { await LocalisationHelper.BuildLocalCulture(); await LocalisationHelper.BuildLocalTimeZone(); Console.WriteLine($"reading GitterKey from storage - {done} attempts left"); SetApiKey(await LocalStorage.GetItem <string>("GitterKey")); break; } catch { } } await Task.Delay(1000); } if (HasApiKey) { initialised = true; } else { var currentUri = UriHelper.GetAbsoluteUri(); var baseUri = UriHelper.GetBaseUri(); var currentPage = UriHelper.ToBaseRelativePath(baseUri, currentUri); if (!currentPage.Equals(LOGINPAGE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(currentPage)) { UriHelper.NavigateTo(LOGINPAGE); } } }
/// <inheritdoc/> public override async Task <AuthenticationState> GetAuthenticationStateAsync() { var savedToken = await _localStorage.GetItem <string>(LocalStorageConstants.AuthToken); if (string.IsNullOrWhiteSpace(savedToken)) { return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } var parsedClaims = ParseClaimsFromJwt(savedToken); var expire = Convert.ToInt64(parsedClaims.First(_ => _.Type.Contains("exp")).Value); var expireDateTime = (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(expire); if (expireDateTime < DateTime.UtcNow) { MarkUserAsLoggedOut(); return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()))); } return(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt")))); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // array in local storage for registered users var usersKey = "blazor-registration-login-example-users"; var users = await _localStorageService.GetItem <List <UserRecord> >(usersKey) ?? new List <UserRecord>(); var method = request.Method; var path = request.RequestUri.AbsolutePath; return(await handleRoute()); async Task <HttpResponseMessage> handleRoute() { if (path == "/users/authenticate" && method == HttpMethod.Post) { return(await authenticate()); } if (path == "/users/register" && method == HttpMethod.Post) { return(await register()); } if (path == "/users" && method == HttpMethod.Get) { return(await getUsers()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Get) { return(await getUserById()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Put) { return(await updateUser()); } if (Regex.Match(path, @"\/users\/\d+$").Success&& method == HttpMethod.Delete) { return(await deleteUser()); } // pass through any requests not handled above return(await base.SendAsync(request, cancellationToken)); } // route functions async Task <HttpResponseMessage> authenticate() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Login>(bodyJson); var user = users.FirstOrDefault(x => x.Username == body.Username && x.Password == body.Password); if (user == null) { return(await error("Username or password is incorrect")); } return(await ok(new { Id = user.Id.ToString(), Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Token = "fake-jwt-token" })); } async Task <HttpResponseMessage> register() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <AddUser>(bodyJson); if (users.Any(x => x.Username == body.Username)) { return(await error($"Username '{body.Username}' is already taken")); } var user = new UserRecord { Id = users.Count > 0 ? users.Max(x => x.Id) + 1 : 1, Username = body.Username, Password = body.Password, FirstName = body.FirstName, LastName = body.LastName }; users.Add(user); await _localStorageService.SetItem(usersKey, users); return(await ok()); } async Task <HttpResponseMessage> getUsers() { if (!isLoggedIn()) { return(await unauthorized()); } return(await ok(users.Select(x => basicDetails(x)))); } async Task <HttpResponseMessage> getUserById() { if (!isLoggedIn()) { return(await unauthorized()); } var user = users.FirstOrDefault(x => x.Id == idFromPath()); return(await ok(basicDetails(user))); } async Task <HttpResponseMessage> updateUser() { if (!isLoggedIn()) { return(await unauthorized()); } var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <EditUser>(bodyJson); var user = users.FirstOrDefault(x => x.Id == idFromPath()); // if username changed check it isn't already taken if (user.Username != body.Username && users.Any(x => x.Username == body.Username)) { return(await error($"Username '{body.Username}' is already taken")); } // only update password if entered if (!string.IsNullOrWhiteSpace(body.Password)) { user.Password = body.Password; } // update and save user user.Username = body.Username; user.FirstName = body.FirstName; user.LastName = body.LastName; await _localStorageService.SetItem(usersKey, users); return(await ok()); } async Task <HttpResponseMessage> deleteUser() { if (!isLoggedIn()) { return(await unauthorized()); } users.RemoveAll(x => x.Id == idFromPath()); await _localStorageService.SetItem(usersKey, users); return(await ok()); } // helper functions async Task <HttpResponseMessage> ok(object body = null) { return(await jsonResponse(HttpStatusCode.OK, body ?? new {})); } async Task <HttpResponseMessage> error(string message) { return(await jsonResponse(HttpStatusCode.BadRequest, new { message })); } async Task <HttpResponseMessage> unauthorized() { return(await jsonResponse(HttpStatusCode.Unauthorized, new { message = "Unauthorized" })); } async Task <HttpResponseMessage> jsonResponse(HttpStatusCode statusCode, object content) { var response = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json") }; // delay to simulate real api call await Task.Delay(500); return(response); } bool isLoggedIn() { return(request.Headers.Authorization?.Parameter == "fake-jwt-token"); } int idFromPath() { return(int.Parse(path.Split('/').Last())); } dynamic basicDetails(UserRecord user) { return(new { Id = user.Id.ToString(), Username = user.Username, FirstName = user.FirstName, LastName = user.LastName }); } }
public async Task <bool> IsAuthorizedAsync() { var accessToken = await _localStorageService.GetItem <string>("accessToken"); return(!string.IsNullOrEmpty(accessToken)); }
public async Task Initialize() { Client = await _localStorageService.GetItem <Clients>(_ClientKey); }
public async Task <dynamic> GetUserLogon() { return(await _storage.GetItem("USER")); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // array in local storage for registered Clients var ClientsKey = "ClientsXPTO"; var Clients = await _localStorageService.GetItem <List <ClientRecord> >(ClientsKey) ?? new List <ClientRecord>(); var method = request.Method; var path = request.RequestUri.AbsolutePath; return(await handleRoute()); async Task <HttpResponseMessage> handleRoute() { if (path == "/api/clients/authenticate" && method == HttpMethod.Post) { return(await authenticate()); } if (path == "/api/clients/register" && method == HttpMethod.Post) { return(await register()); } if (path == "/api/clients" && method == HttpMethod.Get) { return(await getClients()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Get) { return(await getClientById()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Put) { return(await updateClient()); } if (Regex.Match(path, @"\/api/clients\/\d+$").Success&& method == HttpMethod.Delete) { return(await deleteClient()); } // pass through any requests not handled above return(await base.SendAsync(request, cancellationToken)); } // route functions async Task <HttpResponseMessage> authenticate() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); var Client = Clients.FirstOrDefault(x => x.Email == body.Email && x.Password == body.Password); if (Client == null) { return(await error("Email or password is incorrect")); } return(await ok(new { Id = Client.Id.ToString(), Username = Client.Username, Email = Client.Email, FullName = Client.FullName, BillingAddress = Client.BillingAddress, ShippingAddress = Client.ShippingAddress, Country = Client.Country, Phone = Client.Phone, Token = "fake-jwt-token" })); } async Task <HttpResponseMessage> register() { var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); if (Clients.Any(x => x.Email == body.Email)) { return(await error($"Client email '{body.Email}' is already taken")); } var Client = new ClientRecord { Id = (Clients.Count() > 0) ? Clients.Max(x => x.Id) + 1 : 1, Username = body.Username, Email = body.Email, Password = body.Password, FullName = body.FullName, BillingAddress = body.BillingAddress, ShippingAddress = body.ShippingAddress, Country = body.Country, Phone = body.Phone }; Clients.Add(Client); await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } async Task <HttpResponseMessage> getClients() { if (!isLoggedIn()) { return(await unauthorized()); } return(await ok(Clients.Select(x => basicDetails(x)))); } async Task <HttpResponseMessage> getClientById() { if (!isLoggedIn()) { return(await unauthorized()); } var Client = Clients.FirstOrDefault(x => x.Id == idFromPath()); return(await ok(basicDetails(Client))); } async Task <HttpResponseMessage> updateClient() { if (!isLoggedIn()) { return(await unauthorized()); } var bodyJson = await request.Content.ReadAsStringAsync(); var body = JsonSerializer.Deserialize <Clients>(bodyJson); var Client = Clients.FirstOrDefault(x => x.Id == idFromPath()); // if Clientname changed check it isn't already taken if (Client.Email != body.Email && Clients.Any(x => x.Email == body.Email)) { return(await error($"Client email '{body.Email}' is already taken")); } // only update password if entered if (!string.IsNullOrWhiteSpace(body.Password)) { Client.Password = body.Password; } // update and save Client Client.Email = body.Email; Client.Username = body.Username; Client.FullName = body.FullName; Client.BillingAddress = body.BillingAddress; Client.ShippingAddress = body.ShippingAddress; Client.Country = body.Country; Client.Phone = body.Phone; await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } async Task <HttpResponseMessage> deleteClient() { if (!isLoggedIn()) { return(await unauthorized()); } Clients.RemoveAll(x => x.Id == idFromPath()); await _localStorageService.SetItem(ClientsKey, Clients); return(await ok()); } // helper functions async Task <HttpResponseMessage> ok(object body = null) { return(await jsonResponse(HttpStatusCode.OK, body ?? new { })); } async Task <HttpResponseMessage> error(string message) { return(await jsonResponse(HttpStatusCode.BadRequest, new { message })); } async Task <HttpResponseMessage> unauthorized() { return(await jsonResponse(HttpStatusCode.Unauthorized, new { message = "Unauthorized" })); } async Task <HttpResponseMessage> jsonResponse(HttpStatusCode statusCode, object content) { var response = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json") }; // delay to simulate real api call await Task.Delay(500); return(response); } bool isLoggedIn() { return(request.Headers.Authorization?.Parameter == "fake-jwt-token"); } int idFromPath() { return(int.Parse(path.Split('/').Last())); } dynamic basicDetails(ClientRecord Client) { return(new { Id = Client.Id.ToString(), Username = Client.Username, Email = Client.Email, Password = Client.Password, FullName = Client.FullName, BillingAddress = Client.BillingAddress, ShippingAddress = Client.ShippingAddress, Country = Client.Country, Phone = Client.Phone }); } }
public async Task Initialize() { User = await _localStorageService.GetItem <User>(_userKey); }
public async Task Initialize() { User = await _localStorageService.GetItem <AuthenticateResponse>("user"); }
public Task <string> GetAccessTokenAsync() => _localStorage.GetItem <string>("authToken");