public async Task <IActionResult> SignIn(SigninInput signinInput) { if (!ModelState.IsValid) { return(View()); } var response = await _identityService.SignIn(signinInput); if (!response.IsSuccessful) { response.Errors.ForEach(x => { ModelState.AddModelError(string.Empty, x); }); return(View()); } return(RedirectToAction(nameof(Index), "Home")); }
public async Task <Response <bool> > SignIn(SigninInput signinInput) { var disco = await _httpClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest { Address = _serviceApiSettings.IdentityBaseUri, Policy = new DiscoveryPolicy { RequireHttps = false } }); if (disco.IsError) { throw disco.Exception; } var passwordTokenRequest = new PasswordTokenRequest { ClientId = _clientSettings.WebClientForUser.ClientId, ClientSecret = _clientSettings.WebClientForUser.ClientSecret, UserName = signinInput.Email, Password = signinInput.Password, Address = disco.TokenEndpoint }; var token = await _httpClient.RequestPasswordTokenAsync(passwordTokenRequest); if (token.IsError) { var responseContent = await token.HttpResponse.Content.ReadAsStringAsync(); var errorDto = JsonSerializer.Deserialize <ErrorDto>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return(Response <bool> .Fail(errorDto.Errors, 400)); } var userInfoRequest = new UserInfoRequest { Token = token.AccessToken, Address = disco.UserInfoEndpoint }; var userInfo = await _httpClient.GetUserInfoAsync(userInfoRequest); if (userInfo.IsError) { throw userInfo.Exception; } ClaimsIdentity claimsIdentity = new ClaimsIdentity(userInfo.Claims, CookieAuthenticationDefaults.AuthenticationScheme, "name", "role"); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authenticationProperties = new AuthenticationProperties(); authenticationProperties.StoreTokens(new List <AuthenticationToken>() { new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = token.AccessToken }, new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = token.RefreshToken }, new AuthenticationToken { Name = OpenIdConnectParameterNames.ExpiresIn, Value = DateTime.Now.AddSeconds(token.ExpiresIn).ToString("o", CultureInfo.InvariantCulture) } }); authenticationProperties.IsPersistent = signinInput.IsRemember; await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authenticationProperties); return(Response <bool> .Success(200)); }