public async Task <IActionResult> Profile() { var token = User.Claims.First(x => x.Type == "Token").Value; int id = 0; Int32.TryParse(User.Claims.First(x => x.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Value, out id); AppUserResponse result = new AppUserResponse(); if (id == 0) { RedirectToAction("Index", "Home"); } using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); using (var response = await client.GetAsync(ServiceURL.GetURL(Config) + "Home/GetUserById/" + id.ToString())) { var content = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <AppUserResponse>(content); } } if (result == null) { return(View()); } var model = new UIAppUser { Email = result.User.Email, Id = result.User.Id, Name = result.User.Name, userClaims = result.UserClaims }; return(View(model)); }
public async Task <IActionResult> Login(UILogin model) { if (!ModelState.IsValid) { return(View(model)); } AppUserResponse result = new AppUserResponse(); using (var httpClient = new HttpClient()) { StringContent content = new StringContent( JsonConvert.SerializeObject(new Login { Email = model.Email, Password = model.Password }), System.Text.Encoding.UTF8, "application/json" ); using (var response = await httpClient.PostAsync(ServiceURL.GetURL(Config) + "Home/Login", content)) { string apiResponse = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <AppUserResponse>(apiResponse); } } if (!result.Success || result.User == null) { ModelState.AddModelError("", result.Message); return(View(model)); } var prop = new AuthenticationProperties() { IsPersistent = model.RebemberMe, }; var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, result.User.Id.ToString())); claims.Add(new Claim(ClaimTypes.Name, result.User.Email)); claims.Add(new Claim("Token", result.Token)); if (result.UserClaims != null) { result.UserClaims.ForEach(c => claims.Add(new Claim(ClaimTypes.Role, c.Value))); } var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principial = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(principial, prop); return(RedirectToAction("Index")); }