/// <summary> /// Post a login request to the api. Stores the given user credentials in cookies and forwards any errors the api sends back. /// </summary> /// <param name="userForAuthentication">Holds info about which username and password a user tries to log in with.</param> /// <returns></returns> public async Task <AuthResponseContainer> Login(UserForAuthenticationDto userForAuthentication) { //Serializes the UserForAuthenticationDTO to a dictionary to easily be able to encode it to x-www-form-urlencoded in HttpRequestMessage body var content = JsonSerializer.Serialize(userForAuthentication); var dictionary = JsonSerializer.Deserialize <Dictionary <string, string> >(content); var req = new HttpRequestMessage(HttpMethod.Post, "/Token") { Content = new FormUrlEncodedContent(dictionary) }; var resultContainer = new AuthResponseContainer(); try { var authResult = await _client.SendAsync(req); var authContent = await authResult.Content.ReadAsStringAsync(); resultContainer = JsonSerializer.Deserialize <AuthResponseContainer>(authContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (!authResult.IsSuccessStatusCode) { return(resultContainer); } } catch { resultContainer.Errors = new Dictionary <string, string[]>(); string[] errorArray = { "There has been a network error, please check connection and try again." }; resultContainer.Errors.Add("Error", errorArray); resultContainer.Succeeded = false; return(resultContainer); } //Sets information about the user and acesstoken to local storage await _localStorage.SetItemAsync("authToken", resultContainer.Value.AcessToken); await _localStorage.SetItemAsync("userName", resultContainer.Value.UserName); await _localStorage.SetItemAsync("authorizationExpires", resultContainer.Value.Expires); // TODO: Remove code below if it is not necessary at this time. ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.UserName); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", resultContainer.Value.AcessToken); resultContainer.Succeeded = true; UpdateNavUI.Invoke(true, EventArgs.Empty); return(resultContainer); }
/// <summary> /// Removes all the login credentials stored in cookis and sets the default authorization token to be null in the http client. /// </summary> /// <returns></returns> public async Task Logout() { await _localStorage.RemoveItemAsync("authToken"); await _localStorage.RemoveItemAsync("userName"); await _localStorage.RemoveItemAsync("authorizationExpires"); // TODO: Remove code below if it is not necessary at this time. ((AuthStateProvider)_authStateProvider).NotifyUserLogout(); UpdateNavUI.Invoke(false, EventArgs.Empty); _client.DefaultRequestHeaders.Authorization = null; }