Exemplo n.º 1
0
        public async Task<LoginResponse> LoginAsync(LoginRequest loginRequest)
        {
            var response = await _httpClient.SendAsync<LoginResponse>(HttpMethod.Post, "api/Account/Login", loginRequest.AsJson(),
                CancellationToken.None);

            var token = response.Token.Token;

            var jwtToken = new JwtSecurityToken(token);
            var firstName = jwtToken.Claims.Where(x => x.Type == "first_name").Select(x => x.Value).FirstOrDefault();
            var lastName = jwtToken.Claims.Where(x => x.Type == "last_name").Select(x => x.Value).FirstOrDefault();

            await _localStorage.SetItemAsync("firstName", firstName);
            await _localStorage.SetItemAsync("lastName", lastName);
            await _localStorage.SetItemAsync("authToken", token);
            await _localStorage.SetItemAsync("token", response.Token.AsJson());
            await _localStorage.SetItemAsync("userId", response.UserId);
            await _localStorage.SetItemAsync("loginResult", response.Result.AsJson());

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

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

            return response;
        }