public async Task <IActionResult> LoginParticipant(Participant participant) { try { ILoginHandler loginhandler = new LoginHandler(new bachelordbContext()); //Checks whether or not the participant is in the database var status = loginhandler.LoginParticipantDB(participant.Email, participant.Password); if (status.success) { //Create an object with userinfo about the participant. var userInfo = new UserInfo { hasAdminRights = false, hasParticipantRights = true, hasResearcherRights = false, userID = "" + status.participant.IdParticipant }; //Generates token with claims defined from the userinfo object. var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( participant.Email, AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); //Redirects to the participant homepage return(RedirectToAction("Participant", "Homepage")); } else { var err = status.errormessage; if (err == "Wrong password") { this.ModelState.AddModelError("Password", err.ToString()); } else { this.ModelState.AddModelError("Email", err.ToString()); } } return(View("Participant")); } catch (Exception) { //Handle error throw; } }
public async Task <IActionResult> Login(LoginVM model) { try { var result = _serviceFactory.AccountManagement.SignIn(model.Login, model.Password); if (!result.Success) { throw new InvalidCredentialException(result.Message); } var accessTokenResult = _tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( model.Login, AddMyClaims(result.Data.AccountId, result.Data.FirstName, result.Data.RoleName)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); return(RedirectToAction(nameof(HomeController.Index), "Home")); } catch (InvalidCredentialException ex) { ViewBag.ErrorMessage = ex.Message; ViewBag.HasError = true; } catch (Exception ex) { ViewBag.ErrorMessage = "Произошла непредвиденная ошибка"; ViewBag.HasError = true; } return(View("Index", model)); }
public async Task <IActionResult> Login(UserCredentials userCredentials, string returnUrl = null) { ViewBag.returnUrl = returnUrl; var returnTo = "/Account/Login"; // Replace this with your custom authentication logic which will // securely return the authenticated user's details including // any role specific info if (_userHelper.ValidateUser(userCredentials.Username, userCredentials.Password)) { var user = _userHelper.GetUser(userCredentials.Username); var userInfo = new UserInfo { FirstName = "Firstname", LastName = "Lastname", HasAdminRights = true, TenantId = user.TenantId }; var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( userCredentials.Username, AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); returnTo = returnUrl; } return(RedirectToLocal(returnTo)); }
public async Task <IActionResult> Login(UserCredentials userCredentials, string returnUrl = null) { ViewBag.returnUrl = returnUrl; var returnTo = "/Account/Login"; // Replace this with your custom authentication logic if (userCredentials.Username == "user1" && userCredentials.Password == "pass1") { var userInfo = new UserInfo { FirstName = "UserFName", LastName = "UserLName" }; var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( userCredentials.Username, AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); returnTo = returnUrl; } return(RedirectToLocal(returnTo)); }
public async Task <IActionResult> Login([FromBody] UserCredentials userCredentials) { // Replace this with your custom authentication logic which will // securely return the authenticated user's details including // any role specific info if (userCredentials.Username == "user1" && userCredentials.Password == "pass1") { var userInfo = new UserInfo { FirstName = "UserFName", LastName = "UserLName", HasAdminRights = true }; var accessTokenResult = jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal( userCredentials.Username, AddMyClaims(userInfo)); return(Ok(accessTokenResult.AccessToken)); } else { return(Unauthorized()); } }
public IActionResult Refresh([FromBody] RefreshTokenModel refreshToken) { try { var principal = GetPrincipalFromExpiredToken(refreshToken.Token); var username = principal.Identity.Name; var savedRefreshToken = ""; savedRefreshToken = _userService.GetUserRefreshToken(username); //retrieve the refresh token from a data store if (savedRefreshToken != refreshToken.RefreshToken) { return(Ok(new { Status = PublicResultStatusCodes.NotAuthorized })); } var newJwtToken = _jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal(username, principal.Claims); var newRefreshToken = RefreshTokenHelper.GenerateRefreshToken(); _userService.SaveUserRefreshToken(username, newRefreshToken); return(Ok(new { Status = PublicResultStatusCodes.Done, Data = new List <object> { new{ RefreshToken = newRefreshToken, Token = newJwtToken.AccessToken, ValidTokenTimeInMinutes = _token.ValidTimeInMinutes, ValidDateTimeToken = DateTime.Now.AddMinutes(_token.ValidTimeInMinutes) } } })); } catch (SecurityTokenException ex) { return(Ok(new { Status = PublicResultStatusCodes.NotAuthorized })); } }
public async Task <IActionResult> CreateAdminLogin(LoginModel model) { try { //Create an object with userinfo about the participant. var userInfo = new UserInfo { hasAdminRights = true, hasUserRights = false, userID = "" + 1 }; //Generates token with claims defined from the userinfo object. var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( "TestName", AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); RedirectToAction("Index", "HomePage"); } catch (Exception e) { Console.WriteLine(e); throw; } return(View("AdminLogin")); }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true // var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, true, lockoutOnFailure: false); //CheckPasswordSignInAsync() var userInfo = new UserInfo { FirstName = "UserFName", LastName = "UserLName", HasAdminRights = true }; var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( model.Email, AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); // returnUrl = returnUrl; // if (result.Succeeded) // { // var user = await _userManager.FindByEmailAsync(model.Email); // var ttt = await _userManager.AddClaimAsync(user, new Claim("OrganizationId","1")); // var yy = _userManager.GetClaimsAsync(user).GetAwaiter().GetResult(); //await _userManager.RemoveClaimsAsync(user, yy); //_userManager.AddToRoleAsync(, new Claim("OrganizationId", "1")); _logger.LogInformation("Użytkownik zalogowany"); return(RedirectToLocal(returnUrl)); //} //if (result.RequiresTwoFactor) //{ // return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }); //} //if (result.IsLockedOut) //{ // _logger.LogWarning("twoje konto zostało zablokowane"); // return RedirectToAction(nameof(Lockout)); //} //else //{ // ModelState.AddModelError(string.Empty, "Podany login lub hasło jest niepoprawne"); // return View(model); //} } // If we got this far, something failed, redisplay form return(View(model)); }
public CResult <string> Authenticate(UserCredentials userCredentials) { try { using (var _userManager = new UserManager()) using (var _roleManager = new RoleManager()) using (var _userRoleManager = new UserRoleManager()) { var user = _userManager.GetWithCondition( c => c.UserName == userCredentials.UserName && c.Password == userCredentials.Password).Model; var userRole = _userRoleManager.GetWithCondition(c => c.UserId == user.Id).Model; if (userRole == null) { return new CResult <string>() { Data = string.Empty, IsSucceeded = false, Message = "Role undefined" } } ; var role = _roleManager.GetWithCondition(c => c.Id == userRole.RoleId).Model; var userInfo = new UserInfo() { FirstName = user.FirstName, LastName = user.LastName, HasAdminRights = false }; var accessTokenResult = jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal( userCredentials.UserName, role.Name, AddClaims(userInfo)); return(new CResult <string>() { Data = accessTokenResult.AccessToken, Message = "Token Created", IsSucceeded = true }); } } catch (Exception ex) { return(new CResult <string>() { Data = string.Empty, IsSucceeded = false, Message = ex.Message }); } }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { var authenticationCookieName = ".AspNetCore.Cookies"; var authenticationCookieName1 = ".Token.jwt"; var cookie = context.Request.Cookies[authenticationCookieName]; var cookie1 = context.Request.Cookies[authenticationCookieName1]; // var y = secureDataFormat; var services = context.RequestServices;//.GetRequiredService<IServiceScopeFactory>().CreateScope()) if (cookie != null) { //services.GetService<IConfigurationSection>(); //Microsoft.Extensions.Configuration.IConfigurationSection appSettingsSection = services.GetRequiredService<IConfigurationSection>().GetSection("AppSettings"); //var key = Encoding.ASCII.GetBytes(services.GetRequiredService<AppSettings>().Secret); var key = Encoding.ASCII.GetBytes("OfED+KgbZ44xtu4e4+JSQWdtSgTnsuNixKy1nMVAf4Ewws8QL3IN33XusJhrz9HXmIrdy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9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx"); var validationParams = new TokenValidationParameters { ClockSkew = TimeSpan.Zero, ValidateAudience = true, //ValidAudience = Configuration["Token:Audience"], ValidAudience = "http://localhost:44330/", ValidateIssuer = true, // ValidIssuer = Configuration["Token:Issuer"], ValidIssuer = "http://localhost:44330/", // IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Token:SigningKey"])), IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuerSigningKey = true, RequireExpirationTime = true, ValidateLifetime = true }; var hostingEnvironment = services.GetRequiredService <IHostingEnvironment>(); var ticket = new JwtAuthTicketFormat(validationParams, services.GetRequiredService <IDataSerializer <AuthenticationTicket> >(), services.GetDataProtector(new[] { $"{hostingEnvironment.ApplicationName}-Auth1" })); AuthenticationTicket t = ticket.Unprotect(cookie); if (t != null) { var dt = DateTime.Now; var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); var token = jwtSecurityTokenHandler.ReadJwtToken(t.Properties.Items[".Token.jwt"]); var to = token.Claims.ToList(); var mail = to.Find(x => x.Type == ClaimTypes.Name).Value; if ((token.ValidTo.AddHours(1) - dt).TotalSeconds > 0 && (token.ValidTo.AddHours(1) - dt).TotalSeconds < 300) { var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( mail, token.Claims); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); JwtSecurityToken tt = handler.ReadToken(accessTokenResult.AccessToken) as JwtSecurityToken; await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await context.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); } //var yyyyyy = context.User?.FindFirst(ClaimTypes.GivenName).Value; } } if (true) { await next(context); return; } context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; }
public Response <LoginResponse> VerifyLogInUser(Credentials credentials) { var user = _repository.GetUserByUsername(credentials.Account); var validUsername = false; if (user != null && user.IsActive) { validUsername = true; } if (validUsername) { if (user.ExpireDate.HasValue && user.ExpireDate.Value.Date < DateTime.Now.Date) { _saveLog.LogInformation("No Login Access because Account has Expired, Account = \"" + credentials.Account + "\""); return(new Response <LoginResponse>(PublicResultStatusCodes.ExpiredAccount)); } if ((IsValidUser(credentials.Account, credentials.Password, credentials.IsFromPortal))) { _contextAccessor.HttpContext = IdentityHelper.SetIdentity(_contextAccessor.HttpContext, user); var accessTokenResult = _jwtTokenGenerator.GenerateAccessTokenWithClaimsPrincipal(credentials.Account, AddMyClaims(user)); // _logService.AddLogUserAuthorization((int)UserAuthorizationStatus.SignIn, credentials.IsFromPortal); //isChangePassword = user.ChangePasswordNeeded ? true : isChangePassword; var response = new LoginResponse { Id = user.ID, Token = accessTokenResult.AccessToken, RefreshToken = user.RefreshToken, ValidTokenTimeInMinutes = _token.ValidTimeInMinutes, ValidDateTimeToken = DateTime.Now.AddMinutes(_token.ValidTimeInMinutes), FirstLast = user.First + " " + user.Last, Username = user.Account, ChangePasswordNeeded = true }; return(new Response <LoginResponse>(PublicResultStatusCodes.Done, response)); } } PublicResultStatusCodes status; string message; _logService.AddLogFailedAuthentication(credentials.Account); if (validUsername) { status = PublicResultStatusCodes.ClientSecertNotValid; message = "User Verification failed (SecretNotValid) --account:" + credentials.Account; } else { status = PublicResultStatusCodes.ClientIdNotValid; message = "User Verification failed (ClientIdNotValid) --accountProvided:" + credentials.Account; } _saveLog.LogInformation(message); return(new Response <LoginResponse>(status)); }
public async Task <IActionResult> LoginAsAdmin(LoginModel model) { try { LoginHandler loginHandler = new LoginHandler(new bachelordbContext()); var status = loginHandler.LoginAdmin(model.Email, model.Password); if (status.success) { if (status.adminuser.IsAdmin) { //Create an object with userinfo about the user. userInfo = new UserInfo { hasAdminRights = true, hasParticipantRights = true, hasResearcherRights = false, userID = "" + status.adminuser.IdAdmin }; } else { //Create an object with userinfo about the user. userInfo = new UserInfo { hasAdminRights = false, hasParticipantRights = true, hasResearcherRights = false, userID = "" + status.adminuser.IdAdmin }; } //Generates token with claims defined from the userinfo object. var accessTokenResult = tokenGenerator.GenerateAccessTokenWithClaimsPrincipal( model.Email, AddMyClaims(userInfo)); await HttpContext.SignInAsync(accessTokenResult.ClaimsPrincipal, accessTokenResult.AuthProperties); return(RedirectToAction("Index", "HomePage")); } else { var err = status.errormessage; if (err == "Wrong password") { this.ModelState.AddModelError("Password", err.ToString()); } else { this.ModelState.AddModelError("Email", err.ToString()); } } return(View("AdminLogin")); } catch (Exception e) { Console.WriteLine(e); throw; } }