private async void ProcessRequest(IRequestAuthenticationMessage request) { Settings.IValues values = _settingsProvider.GetValues(); AuthenticationRequest authenticationRequest = new AuthenticationRequest { password = request.Password, email = request.EMail }; string serializedRequest = authenticationRequest.ToJson(); HttpContent content = new StringContent(serializedRequest, System.Text.Encoding.UTF8, "application/json"); HttpClient client = new HttpClient(); var response = await client.PostAsync(values.AuthenticationEndpoint, content); string result = await response.Content.ReadAsStringAsync(); AuthenticationResponse authenticationResponse = JsonSerializer.DeserializeFromString<AuthenticationResponse>(result); if (authenticationResponse.GetUserAuthTokenResult != null) { _messageMediator.Publish(new AuthenticationResponseMessage(authenticationResponse.GetUserAuthTokenResult.AccountId, authenticationResponse.GetUserAuthTokenResult.UserAuthToken)); } else { _messageMediator.Publish(new AuthenticationResponseMessage(authenticationResponse.ErrorCode, authenticationResponse.Message, authenticationResponse.Source)); } }
public WebClient GetApiWebClient(string baseUri, string username, string password) { if (apiWebClient == null || apiWebClient.BaseAddress != baseUri || apiWebClientAuth.Item1 != username || apiWebClientAuth.Item2 != password) { apiWebClient = null; var client = new WebClientEx(); client.BaseAddress = baseUri; var auth = new AuthenticationRequest { Username = username, Password = password }; try { string authResponse = this.ExecuteOnJsonServiceClient(client, auth); apiWebClient = client; apiWebClientAuth = new Tuple<string, string>(username, password); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Authentication is failed."); } } return apiWebClient; }
public void Create_New_User_Test() { var user = new User() { FirstName = "Joe", LastName = "Henss", UserName = "******", Password = Hasher.Hash("password"), PasswordSecurityQuestion = "Mother's maiden name", PasswordSecurityAnswer = "Hamilton" }; var authenticationProvider = new AuthenticationService(); var saveUserRequest = new SaveUserRequest() { User = user }; var saveUserResponse = authenticationProvider.SaveUser(saveUserRequest); Assert.IsNotNull(saveUserResponse); Assert.AreEqual(ResponseStatus.Success, saveUserResponse.Status); var authenticateUserRequest = new AuthenticationRequest() { UserName = user.UserName, Password = user.Password }; var authenticationResponse = authenticationProvider.AuthenticateUser(authenticateUserRequest); Assert.IsNotNull(authenticationResponse); Assert.AreEqual(ResponseStatus.Success, authenticationResponse.Status); }
public async Task<Token> Login(AuthenticationRequest request) { HttpResponseMessage httpResp = apiCom.executePostAPI("Security/Login", JsonConvert.SerializeObject(request)); if (httpResp.IsSuccessStatusCode) { string responseBodyAsText = await httpResp.Content.ReadAsStringAsync(); Token token = JsonConvert.DeserializeObject<Token>(responseBodyAsText); return token; } else { return null; } }
public void Authenticate(string userName, string password) { var url = Config.Url + Constants.LOGIN_URI; var payload = new AuthenticationRequest { PostUserLogin = new PostUserLogin { Login = userName, Password = password } }; var response = InternalPostRequest(url, payload, false); var userResponse = JsonConvert.DeserializeObject(response, typeof (AuthenticationResponse)) as AuthenticationResponse; if (userResponse != null) { ProfileId = userResponse.UserLogin.State.ExtractId(Constants.LOGIN_URI); } }
public override void Authenticate(AuthenticationRequest request, AuthenticationResponse response) { // Keystone tokens (in the simplest case) do not carry any detailed // information about the identity of the user. For this reason, // every token needs to be validated by calling the Keystone service. // To avoid doing this, we need to cache tokens. // Look for a token in the request headers var tokenID = request.Headers[settings.AuthTokenHeader]; if (tokenID == null) { // Try to take header from the query string tokenID = request.QueryString[settings.AuthTokenParameter]; } if (tokenID != null) { Token token; // Check if the resolved token is already in the cache if (!tokenCache.TryGetValue(tokenID, out token)) { // Need to validate token against Keystone var ksclient = settings.CreateClient(); token = new Token() { ID = tokenID }; // Keystone doesn't return the user along with // the token, so let's retrieve it now. // TODO: this part might need modifications // if we also accept trusts token.User = ksclient.GetUser(token); tokenCache.TryAdd(token.ID, token); } settings.UpdateAuthenticationResponse(response, token, IsMasterAuthority); } }
public void login(string keyspace, string username, string password) { client.set_keyspace(keyspace); AuthenticationRequest authrequst = new AuthenticationRequest(); Dictionary <string, string> credentials = new Dictionary <string, string>(); credentials.Add(username, password); authrequst.Credentials = credentials; try { client.login(authrequst); } catch (AuthenticationException e) { //To-do handle thirift auth exception with our own auth exception throw; } }
public void Authenticate(string userName, string password) { var url = Config.Url + Constants.LOGIN_URI; var payload = new AuthenticationRequest { PostUserLogin = new PostUserLogin { Login = userName, Password = password } }; var response = InternalPostRequest(url, payload, false); var userResponse = JsonConvert.DeserializeObject(response, typeof(AuthenticationResponse)) as AuthenticationResponse; if (userResponse != null) { ProfileId = userResponse.UserLogin.State.ExtractId(Constants.LOGIN_URI); } }
public void RegistrarMatricula(int idPrograma, int idUsuario, AuthenticationRequest autenticacao) { matriculaProgramaBM = new BMMatriculaPrograma(); Usuario usuario = (new BMUsuario()).ObterPorId(idUsuario); MatriculaPrograma matriculaPrograma = new MatriculaPrograma() { Programa = (new BMPrograma()).ObterPorId(idPrograma), Usuario = usuario, NivelOcupacional = (new BMNivelOcupacional()).ObterPorID(usuario.NivelOcupacional.ID), UF = (new BMUf()).ObterPorId(usuario.UF.ID), Auditoria = new Auditoria(autenticacao.Login), StatusMatricula = enumStatusMatricula.Inscrito, ID = 0, DataInicio = DateTime.Now }; matriculaProgramaBM.RegistrarMatricula(matriculaPrograma); }
public async Task <ActionResult <AuthenticationResponse> > Authenticate(AuthenticationRequest authenticationRequest) { try { var response = await _authenticationService.AuthenticateAsync(authenticationRequest, RepositoryManager.UserRepository); return(Ok(response)); } catch (AuthenticationException authException) { return(BadRequest(authException.ErrorMessage)); } catch (Exception err) { LogException(err); return(Problem()); } }
public void AuthenticateSuccessfulReturnsToken() { var mockRepository = new MockRepository(MockBehavior.Strict); var user = new User(Guid.NewGuid()); user.Create("user", "password"); var userService = mockRepository.Create <IUserService>(); userService.Setup(x => x.Authenticate(It.IsAny <string>(), It.IsAny <string>())).Returns(ServiceResult <User> .Ok(user)); var jwtConfig = mockRepository.Create <IJwtTokenConfigurationProvider>(); jwtConfig.SetupGet(x => x.Issuer).Returns("TestIssuer"); jwtConfig.SetupGet(x => x.Audience).Returns("TestAudience"); var signingKey = new SymmetricSecurityKey(new HMACSHA256().Key); jwtConfig.SetupGet(x => x.Key).Returns(signingKey); var controller = new AuthenticationController(userService.Object, jwtConfig.Object); var request = new AuthenticationRequest() { UserName = "******", Password = "******" }; var response = controller.Authenticate(request); var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters() { IssuerSigningKey = signingKey, ValidAudience = "TestAudience", ValidIssuer = "TestIssuer" }; tokenHandler.ValidateToken(response.Value.Token, validationParameters, out var token); token.ValidTo.Should().BeCloseTo(DateTime.UtcNow.AddHours(1), 5000); mockRepository.Verify(); }
public ActionResult <AuthenticationResponse> Authenticate([FromBody] AuthenticationRequest request) { var result = _UserService.Authenticate(request.UserName, request.Password); if (!result.Successful) { return(Forbid()); } var user = result.Result; // Create claims list for the user var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); claims.Add(new Claim(ClaimTypes.Name, user.UserName)); if (user.Administator) { claims.Add(new Claim(ClaimTypes.Role, Role.Administrator)); } // Authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor { Issuer = _JwtTokenConfigurationProvider.Issuer, Audience = _JwtTokenConfigurationProvider.Audience, Expires = DateTime.UtcNow.AddHours(1), IssuedAt = DateTime.UtcNow, Subject = new ClaimsIdentity(claims), SigningCredentials = new SigningCredentials(_JwtTokenConfigurationProvider.Key, SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var response = new AuthenticationResponse() { Token = tokenHandler.WriteToken(token) }; return(response); }
public Trilha RegistrarMatriculatrilha(int pID_Usuario, int pID_TrilhaNivel, AuthenticationRequest autenticacao) { Usuario usuario = new BMUsuario().ObterPorId(pID_Usuario); TrilhaNivel trilhaNivel = new BMTrilhaNivel().ObterPorID(pID_TrilhaNivel); if (ExisteNiveltrilhaPendente(trilhaNivel, usuario)) { throw new Exception("Nível da Trilha bloqueado."); } UsuarioTrilha userTrilha = new UsuarioTrilha() { DataInicio = DateTime.Now, DataLimite = DateTime.Now.AddDays(trilhaNivel.QuantidadeDiasPrazo).Date, NivelOcupacional = usuario.NivelOcupacional, Uf = usuario.UF, TrilhaNivel = trilhaNivel, Usuario = usuario, StatusMatricula = enumStatusMatricula.Inscrito, Auditoria = new Auditoria(autenticacao.Login), AcessoBloqueado = false }; if (ValidarMatriculaAtivaExistente(userTrilha)) { throw new AcademicoException("Usuário já Matriculado na trilha."); } usuarioTrilhaBM = new BMUsuarioTrilha(); usuarioTrilhaBM.Salvar(userTrilha); try { // Enviar Email new ManterUsuarioTrilha().EnviarEmailBoasVindas(userTrilha); } catch { //TODO: CRIAR LOG DE ERROS NO SISTEMA (29/03/2016) } return(trilhaNivel.Trilha); }
public enumOperacao AlternarTagInteresse(int IdUsuario, int IdTag, AuthenticationRequest autenticacao) { BMUsuarioTag bmUsuarioTag = new BMUsuarioTag(); enumOperacao?EnumOperacao = null; try { bool usuarioTemATag = bmUsuarioTag.VerificarSeUsuarioPossuiTag(IdUsuario, IdTag); if (usuarioTemATag) { bmUsuarioTag.Excluir(IdUsuario, IdTag); EnumOperacao = enumOperacao.Exclusao; } else { usuarioTagBM = new BMUsuarioTag(); UsuarioTag usuarioTag = new UsuarioTag() { ID = 0, Auditoria = new Auditoria(autenticacao.Login), DataValidade = null, Adicionado = true }; usuarioTag.Tag = new Tag(); usuarioTag.Tag.ID = IdTag; usuarioTag.Usuario = new Usuario(); usuarioTag.Usuario.ID = IdUsuario; usuarioTagBM.Salvar(usuarioTag); EnumOperacao = enumOperacao.Inclusao; } } catch (Exception ex) { ErroUtil.Instancia.TratarErro(ex); } return(EnumOperacao.Value); }
public ActionResult <string> Post(AuthenticationRequest authRequest, [FromServices] IJwtSigningEncodingKey signingEncodingKey, [FromServices] IJwtEncryptingEncodingKey encryptingEncodingKey) { // 1. Проверяем данные пользователя из запроса. // ... var identity = GetIdentity(authRequest.Name, authRequest.Password); if (identity == null) { Response.StatusCode = 400; Response.WriteAsync("Invalid username or password.").GetAwaiter().GetResult(); return(null); } else { // 2. Создаем утверждения для токена. var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, authRequest.Name) }; // 3. Генерируем JWT. var tokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken token = tokenHandler.CreateJwtSecurityToken( issuer: "DemoApp", audience: "DemoAppClient", subject: new ClaimsIdentity(claims), notBefore: DateTime.Now, expires: DateTime.Now.AddMinutes(5), issuedAt: DateTime.Now, signingCredentials: new SigningCredentials( signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm), encryptingCredentials: new EncryptingCredentials( encryptingEncodingKey.GetKey(), encryptingEncodingKey.SigningAlgorithm, encryptingEncodingKey.EncryptingAlgorithm)); var jwtToken = tokenHandler.WriteToken(token); return(jwtToken); } }
public async Task <AuthenticationResponse> AuthenticateAsync(AuthenticationRequest request) { var user = await _userManager.FindByIdAsync(request.Id); if (user == null) { _logger.LogWarning($"[{nameof(AuthenticateAsync)}] User '{request.Id}' not found."); throw new AuthenticationServiceUnauthorizedException(); } if (!user.IsEnabled) { _logger.LogWarning($"[{nameof(AuthenticateAsync)}] User '{user.Id}' is disabled."); throw new AuthenticationServiceForbiddenException(); } if (!await _userManager.VerifyUserTokenAsync(user, Options.OtpProvider, Options.OtpPurpose, request.Token)) { _logger.LogWarning($"[{nameof(AuthenticateAsync)}] User '{user.Id}' one-time-password token '{request.Token}' verification failed."); throw new AuthenticationServiceForbiddenException(); } var refreshToken = await AuthenticationResponse.GenerateRefreshTokenAsync(); user.RefreshTokens.Add(new RefreshToken { ExpiresUtc = DateTime.UtcNow.Add(Options.BearerRefreshTokenLifespan), Token = refreshToken }); var result = await _userManager.UpdateAsync(user); _logger.LogInformation($"[{nameof(AuthenticateAsync)}] Added refresh token '{refreshToken}' for user '{user.Id}'. Success: '{result.Succeeded}'."); // This ensures the OTP cannot be used again. result = await _userManager.UpdateSecurityStampAsync(user); _logger.LogInformation($"[{nameof(AuthenticateAsync)}] Updated security stamp for user '{user.Id}'. Success: '{result.Succeeded}'."); return(new AuthenticationResponse { AccessToken = GetAccessTokenForUser(user), RefreshToken = refreshToken }); }
public async Task <AuthenticationResponse> AuthenticateAsync(AuthenticationRequest model, IUserRepository userRepository) { var user = (await userRepository.FindAsync(u => u.Email == model.Email )).FirstOrDefault(); if (user != null) { var passwordIsCorrect = BCrypt.Net.BCrypt.Verify(model.Password, user.Password); if (passwordIsCorrect) { var authenticationResponse = new AuthenticationResponse { Token = GenerateJwtToken(user.Id.ToString(), user.UserSecret), Username = user.Username, DisplayName = user.DisplayName, FirstName = user.FirstName, LastName = user.LastName, SpotifyUsername = user.SpotifyUsername, SpotifyMarket = user.SpotifyMarket }; return(authenticationResponse); } else { throw new AuthenticationException ( "Invalid login", "No user found with the provided login details" ); } } else { throw new AuthenticationException ( "Invalid login", "No user found with the provided login details" ); } }
public async Task <bool> AuthenticateUser(string userName, string deviceResponse) { if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(deviceResponse)) { return(false); } User user = await FindUserByUsername(userName); if (user == null) { return(false); } AuthenticateResponse authenticateResponse = AuthenticateResponse.FromJson <AuthenticateResponse>(deviceResponse); Device device = user.DeviceRegistrations.FirstOrDefault(f => f.KeyHandle.SequenceEqual(authenticateResponse.KeyHandle.Base64StringToByteArray())); if (device == null || user.AuthenticationRequest == null) { return(false); } // User will have a authentication request for each device they have registered so get the one that matches the device key handle AuthenticationRequest authenticationRequest = user.AuthenticationRequest.First(f => f.KeyHandle.Equals(authenticateResponse.KeyHandle)); DeviceRegistration registration = new DeviceRegistration(device.KeyHandle, device.PublicKey, device.AttestationCert, Convert.ToUInt32(device.Counter)); StartedAuthentication authentication = new StartedAuthentication(authenticationRequest.Challenge, authenticationRequest.AppId, authenticationRequest.KeyHandle); Core.Crypto.U2F.FinishAuthentication(authentication, authenticateResponse, registration); await _signInManager.SignInAsync(user, new AuthenticationProperties(), "U2F"); user.AuthenticationRequest.Clear(); user.UpdatedOn = DateTime.Now; device.Counter = Convert.ToInt32(registration.Counter); device.UpdatedOn = DateTime.Now; int result = await _dataContext.SaveChangesAsync(); return(result > 0); }
public async Task <ActionResult <AuthenticationResult> > Authenticate( [FromBody] AuthenticationRequest request, CancellationToken ct) { var result = await this.authNFlow.TryAuthenticateUsingUserNameAndPasswordAsync( request.UserName, request.Password, request.IncludeRefreshToken, request.ClientApplicationId, request.ConcurrencyStamp, ct) .ConfigureAwait(true); if (result is null) { return(this.Unauthorized()); } return(result); }
public override void SetUp() { base.SetUp(); var rp = CreateRelyingParty(true); Identifier identifier = this.GetMockIdentifier(ProtocolVersion.V20); this.authReq = (AuthenticationRequest)rp.CreateRequestAsync(identifier, RPRealmUri, RPUri).Result; this.sreg = new ClaimsRequest { Nickname = DemandLevel.Request, FullName = DemandLevel.Request, BirthDate = DemandLevel.Request, Email = DemandLevel.Require, Country = DemandLevel.Request, PostalCode = DemandLevel.Request, Gender = DemandLevel.Request, Language = DemandLevel.Request, TimeZone = DemandLevel.Request, }; }
public async Task <IUser> Authenticate(AuthenticationRequest request) { IUser user = await Find(request.Username); if (null == user) { throw new SecurityException("invalid credentials"); } request.DistinguishedName = user.DistinguishedName; // TODO: make async using (LdapConnection ldap = new LdapConnection()) { ldap.SecureSocketLayer = configuration["Ldap:SecureSocketLayer"].Parse <bool>(); ldap.Connect(configuration["Ldap:Host"], configuration["Ldap:Port"].Parse <int>()); ldap.Bind(request.DistinguishedName, request.Password); } return(user); }
public async Task <IHttpActionResult> Authenticate(AuthenticationRequest request) { if (request == null || string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password)) { return(BadRequest("Username and password are required")); } var result = await ClientLoginService.LoginAsync(new LoginService.LoginRequest() { Username = request.Username, Password = request.Password }); if (result.Status != LoginService.AuthenticationStatus.Success) { return(Unauthorized()); } return(Ok(result)); }
public IHttpActionResult Authenticate([FromBody] AuthenticationRequest authenticationRequest) { var response = _authenticationService.Authenticate(authenticationRequest); if (response == null) { return(BadRequest("Username or password is incorrect")); } // var x = Json<AuthenticationResponse>(response); // return Ok(x); // Newtonsoft.Json.JsonConvert() /* var j = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; * var jj = JsonConvert.SerializeObject(response, Formatting.Indented, j);*/ //return Json(response, JsonRequestBehavior.AllowGet); return(Ok(response)); }
public async Task <IActionResult> Authentication([FromBody] AuthenticationRequest request) { var user = await _sender.Send(new CreateUserCommand { Id = request.UserId, CommandId = Guid.NewGuid() }); var privileges = user.UserAccessGroups .Where(ag => user.UserOrganizations.Select(uo => uo.Organization).Contains(ag.AccessGroup.Organization)) .Select(agu => agu.AccessGroup.Privilege); return(Ok(new Dictionary <string, string> { { $"{nameof(Domain.User)}.{nameof(Domain.User.Id)}", user.Id.ToString() }, { $"{nameof(Domain.Privilege)}", privileges.ToString() } })); }
public AuthenticationResponse Login(AuthenticationRequest request) { // Get user from database var user = userRepository.GetByEmailAndPassword(request.Email, request.Parola); if (user == null) { return(null); } // Generate JWT Token var token = GenerateJwtToken(user); return(new AuthenticationResponse { Id = user.Id, Email = user.Email, Token = token }); }
public async Task <IActionResult> Authenticate(AuthenticationRequest authenticationRequest) { if (ModelState.IsValid) { var result = _accountService.AccountAuthenticate(authenticationRequest); ConfigService.SetAuthentication(result.Data); if (result.Data.IsVerified) { ConfigService.SetAuthentication(result.Data); return(RedirectToAction("Dashboardd", "Dashboard")); } else { TempData["ErrorMessage"] = "UserName either Password is Incorrect"; return(View(authenticationRequest)); } } TempData["SuccessMessage"] = "Successfully Loged In"; return(View(authenticationRequest)); }
public async Task Authenticate_ThrowError_InvalidPassword() { try { var req = new AuthenticationRequest() { UserName = "******", Password = "******" }; var l = await _userService.GetAllAsync(); var user = await _userService.Login(req); Assert.IsNotNull(user); } catch (Exception ex) { Assert.AreEqual(ex.Message, "Le mot de passe est invalide"); } }
/// <summary> /// User Authenticate /// </summary> /// <param name="model">AuthenticateRequest type model</param> /// <returns>JWT Token and user details</returns> public AuthenticationResponse Authenticate(AuthenticationRequest model) { // IEnumerable<Customer> cus = user.GetAll(); IEnumerable <Customer> cus = iuser.GetAll(); byte[] passToHash = System.Text.Encoding.UTF8.GetBytes(model.Password); // call password encrpted method string encryptedPassword = Shared.shared.Hash(passToHash); // get encripted password var userL = cus.SingleOrDefault(x => x.Email == model.Username && x.Password == encryptedPassword); // return null if user not found if (userL == null) { return(null); } // authentication successful so generate jwt token var token = generateJwtToken(userL); return(new AuthenticationResponse(userL, token)); }
public HttpResponseMessage Authorize( [FromUri] AuthenticationRequest authRequest) { if (authRequest.ClientId != _clientKey) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } var oResponse = new JObject(); oResponse.Add(new JProperty("code", "abcdef")); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent( oResponse.ToString(), Encoding.UTF8, "application/json"); return(response); }
public AuthenticationRequest GenerateToken(AuthenticationRequest request) { var user = FetchUser(request.User.Username); if (user == null) { _logger.LogMsg("Incorrect username attempt", new AuthenticationModel { Username = request.User.Username, Ip = request.Ip }); return(null); } // Encrypt the token with the end users public key. If they're able to decrypt it we know they're valid request.Token = Cryptide.Instance.Encrypt(GenerateToken(request.User.Username), user.VendorPublicKey); _logger.LogMsg("Created token for user", new AuthenticationModel { Username = request.User.Username, Ip = request.Ip }); return(request); }
public void Serializable() { OpenIdProvider provider = this.CreateProvider(); CheckIdRequest immediateRequest = new CheckIdRequest(Protocol.Default.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate); immediateRequest.Realm = RPRealmUri; immediateRequest.ReturnTo = RPUri; immediateRequest.LocalIdentifier = "http://somebody"; AuthenticationRequest request = new AuthenticationRequest(provider, immediateRequest); MemoryStream ms = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, request); ms.Position = 0; var req2 = (AuthenticationRequest)formatter.Deserialize(ms); Assert.That(req2, Is.Not.Null); }
public async Task <AuthenticationResponse> AuthenticateTeacher(string username, string password) { UriBuilder builder = new UriBuilder(ApiConstants.BaseApiUrl) { Path = ApiConstants.BaseApiUriPart + ApiConstants.AuthenticateEndpoint }; AuthenticationRequest authenticationRequest = new AuthenticationRequest() { Username = username, Password = password }; var authenticationResponse = await _genericRepository.PostAsync <AuthenticationRequest, AuthenticationResponse>(builder.ToString(), authenticationRequest); var teacher = authenticationResponse.Teacher; await Cache.InsertObject(CacheNameConstants.TeacherById + teacher.Id, teacher, DateTimeOffset.Now.AddSeconds(20)); return(authenticationResponse); }
public async Task <ActionResult <AuthenticationResponse> > AuthenticateJWT(AuthenticationRequest authenticationRequest) { string token = string.Empty; //checking if the user exists in the database authenticationRequest.Password = Utility.Encrypt(authenticationRequest.Password); User loggedInUser = await _context.Users .Where(u => u.EmailAddress == authenticationRequest.EmailAddress && u.Password == authenticationRequest.Password) .FirstOrDefaultAsync(); if (loggedInUser != null) { //generating the token token = GenerateJwtToken(loggedInUser); } return(await Task.FromResult(new AuthenticationResponse() { Token = token })); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticationRequest authenticationRequest) { var res = await _userService.AuthenticateUser(authenticationRequest); if (res.IsSuccessful) { var token = CreateToken(res.UserId, res.Username); return(Ok(new ClientAuthenticationResponse { IsSuccessful = true, Token = token })); } return(Unauthorized(new ClientAuthenticationResponse { Message = res.Message })); }
public async Task <IActionResult> Post([FromBody] AuthenticationRequest user) { if (string.IsNullOrEmpty(user.username)) { ModelState.AddModelError("username", "Username is required."); } if (string.IsNullOrEmpty(user.password)) { ModelState.AddModelError("password", "Password is required."); } if (ModelState.ErrorCount > 0) { _logger.LogDebug("Authentication failed for user: {0}", string.IsNullOrEmpty(user.username) ? "<unknown>" : user.username); return(BadRequest(ModelState)); } var result = await _signInManager.PasswordSignInAsync(user.username, user.password, false, false); if (!result.Succeeded) { _logger.LogDebug("Authentication failed for user: {0}", string.IsNullOrEmpty(user.username) ? "<unknown>" : user.username); ModelState.AddModelError("error", "Authentication failed, please reconfirm your username and password."); return(BadRequest(ModelState)); } _logger.LogDebug("Authentication successful for user: {0}", user.username); var cookie = Crypto.EncryptStringAES(string.Format("{0}:{1}:{2}", user.username, user.password, Guid.NewGuid()), _config["PMNoAuthHash"], _config["PMNoAuthKey"]); var cookieOptions = new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = true }; Response.Cookies.Append("DQM-User", cookie, cookieOptions); return(Ok()); }
private async Task <LoginRequest> GetLoginRequestAsync(TParty party, AuthenticationRequest authenticationRequest) { var loginRequest = new LoginRequest { DownPartyLink = new DownPartySessionLink { SupportSingleLogout = !string.IsNullOrWhiteSpace(party.Client?.FrontChannelLogoutUri), Id = party.Id, Type = party.Type } }; loginRequest.LoginAction = !authenticationRequest.Prompt.IsNullOrWhiteSpace() && authenticationRequest.Prompt.Contains(IdentityConstants.AuthorizationServerPrompt.None) ? LoginAction.ReadSession : LoginAction.ReadSessionOrLogin; if (authenticationRequest.MaxAge.HasValue) { loginRequest.MaxAge = authenticationRequest.MaxAge.Value; } if (!authenticationRequest.IdTokenHint.IsNullOrEmpty()) { var claimsPrincipal = await jwtDownLogic.ValidatePartyClientTokenAsync(party.Client as TClient, authenticationRequest.IdTokenHint, validateLifetime : false); if (claimsPrincipal == null) { throw new OAuthRequestException("Invalid id token hint.") { RouteBinding = RouteBinding, Error = IdentityConstants.ResponseErrors.InvalidRequest }; } loginRequest.UserId = claimsPrincipal.FindFirst(JwtClaimTypes.Subject).Value; } if (!authenticationRequest.LoginHint.IsNullOrEmpty()) { loginRequest.UserId = authenticationRequest.LoginHint; } if (!authenticationRequest.AcrValues.IsNullOrWhiteSpace()) { loginRequest.Acr = authenticationRequest.AcrValues.ToSpaceList(); } return(loginRequest); }
public Token Login(AuthenticationRequest AuthenticationRequest) { UserProfile up = _repUser.Get(filter: u => u.EmailId == AuthenticationRequest.email).FirstOrDefault(); if (null == up) { _domainModelResponse.addResponse("Login", MessageCodes.ErrDoesnotExist, "User : "******"Login", MessageCodes.ErrValidationFailed, "Password mismatch."); throw _domainModelResponse; } return InternalCreateToken(up); }
/// <summary> /// Process Saml2 sigin Request /// </summary> /// <param name="ip"></param> /// <param name="request"></param> /// <returns></returns> private ActionResult ProcessSaml2SignIn(IdentityProvider ip, SignInRequestMessage request) { if (ip.Enabled) { var saml2ProtocolSerializer = new Saml2ProtocolSerializer(); var protocolBinding = ProtocolBindings.HttpRedirect; HttpBindingSerializer httpBindingSerializer = new HttpRedirectBindingSerializer(saml2ProtocolSerializer); var authenticationRequest = new AuthenticationRequest { Issuer = new Microsoft.IdentityModel.Tokens.Saml2.Saml2NameIdentifier(request.Realm.TrimEnd('/'), new Uri(ip.WSFederationEndpoint)), Destination = new Uri(ip.WSFederationEndpoint) }; //Provide Service provider default signin home page - hardcoded for testing purpose var messageContainer = new MessageContainer(authenticationRequest, new ProtocolEndpoint(protocolBinding, new Uri(ip.WSFederationEndpoint + "/signon.ashx"))); var httpMessage = httpBindingSerializer.Serialize(messageContainer); httpBindingSerializer.WriteHttpMessage(new HttpResponseWrapper(System.Web.HttpContext.Current.Response), httpMessage); ControllerContext.HttpContext.ApplicationInstance.CompleteRequest(); } return View("Error"); }
public override AuthenticationResponse VerifyPassword(AuthenticationRequest request) { // User needs to be authenticated in the scope of a project (tenant). // Since a tenant with the same name is generated for each user in keystone, we // use the username as project name. var project = new Keystone.Project() { Domain = new Keystone.Domain() { Name = settings.Domain.ToLowerInvariant() }, Name = request.Username.ToLowerInvariant() }; // Verify user password in Keystone, we don't use // Graywulf password in this case var token = KeystoneClient.Authenticate(settings.Domain.ToLowerInvariant(), request.Username.ToLowerInvariant(), request.Password, project); // Find user details in keystone token.User = GetKeystoneUser(request.Username); // Create a response, this sets necessary response headers var response = new AuthenticationResponse(request); settings.UpdateAuthenticationResponse(response, token, true); // Load user from the graywulf registry. This call will create the user // if necessary because authority is set to master LoadOrCreateUser(response.Principal.Identity); return response; }
public DomainModelResponse ResetPassword(AuthenticationRequest AuthenticationRequest, string newPassword, bool resetByAdmin) { return _domainModelResponse; }
/// <summary> /// Gets the incoming OpenID request if there is one, or null if none was detected. /// </summary> /// <param name="httpRequestInfo">The incoming HTTP request to extract the message from.</param> /// <returns> /// The request that the hosting Provider should process and then transmit the response for. /// Null if no valid OpenID request was detected in the given HTTP request. /// </returns> /// <remarks> /// Requests may be infrastructural to OpenID and allow auto-responses, or they may /// be authentication requests where the Provider site has to make decisions based /// on its own user database and policies. /// </remarks> /// <exception cref="ProtocolException">Thrown if the incoming message is recognized /// but deviates from the protocol specification irrecoverably.</exception> public IRequest GetRequest(HttpRequestInfo httpRequestInfo) { Contract.Requires<ArgumentNullException>(httpRequestInfo != null); IDirectedProtocolMessage incomingMessage = null; try { incomingMessage = this.Channel.ReadFromRequest(httpRequestInfo); if (incomingMessage == null) { // If the incoming request does not resemble an OpenID message at all, // it's probably a user who just navigated to this URL, and we should // just return null so the host can display a message to the user. if (httpRequestInfo.HttpMethod == "GET" && !httpRequestInfo.UrlBeforeRewriting.QueryStringContainPrefixedParameters(Protocol.Default.openid.Prefix)) { return null; } ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } IRequest result = null; var checkIdMessage = incomingMessage as CheckIdRequest; if (checkIdMessage != null) { result = new AuthenticationRequest(this, checkIdMessage); } if (result == null) { var extensionOnlyRequest = incomingMessage as SignedResponseRequest; if (extensionOnlyRequest != null) { result = new AnonymousRequest(this, extensionOnlyRequest); } } if (result == null) { var checkAuthMessage = incomingMessage as CheckAuthenticationRequest; if (checkAuthMessage != null) { result = new AutoResponsiveRequest(incomingMessage, new CheckAuthenticationResponse(checkAuthMessage, this), this.SecuritySettings); } } if (result == null) { var associateMessage = incomingMessage as AssociateRequest; if (associateMessage != null) { result = new AutoResponsiveRequest(incomingMessage, associateMessage.CreateResponse(this.AssociationStore, this.SecuritySettings), this.SecuritySettings); } } if (result != null) { foreach (var behavior in this.Behaviors) { if (behavior.OnIncomingRequest(result)) { // This behavior matched this request. break; } } return result; } throw ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } catch (ProtocolException ex) { IRequest errorResponse = this.GetErrorResponse(ex, httpRequestInfo, incomingMessage); if (errorResponse == null) { throw; } return errorResponse; } }
private static AuthenticationResponse createAuthenticationRequest(ISecurityService securityService, string username, string password, string domain) { UserNamePasswordCredentials credentials = createCredentials(username, password, domain); AuthenticationRequest authenticationRequest = new AuthenticationRequest(credentials); return securityService.Authenticate(authenticationRequest); }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } MvcApplication.userName = null; MvcApplication.userEmail = null; MvcApplication.userRole = null; MvcApplication.courses.Clear(); AuthenticationRequest ar = new AuthenticationRequest(); ar.email = model.Email; ar.password = model.Password; Token token = _secCom.Login(ar).Result; if(token != null) //Authenticated { MvcApplication.IsAuthenticated = true; MvcApplication.userName = token.user.firstName + " " + token.user.lastName; MvcApplication.userEmail = token.user.emailId; if(token.user.UserCourseDetails.Count == 1) { UserCourseDetail ugr = token.user.UserCourseDetails.FirstOrDefault(); if(ugr.RoleCode == "Teacher" || ugr.RoleCode == "TA") return RedirectToAction("UnregisteredTeacher", "Course"); else if(ugr.RoleCode == "Admin") return RedirectToAction("Admin", "Home"); else return RedirectToAction("Student", "Course"); } else //User is registered in a course { UserCourseDetail ugr = token.user.UserCourseDetails.FirstOrDefault(); MvcApplication.userRole = ugr.RoleCode; foreach (UserCourseDetail ucd in token.user.UserCourseDetails) { if (!ucd.courseCode.Equals("default", StringComparison.OrdinalIgnoreCase)) { MvcApplication.courses.Add(ucd.courseCode, ucd.CourseName); MvcApplication.courseDescription.Add(ucd.courseCode, ucd.CourseDescription); } } if (ugr.RoleCode == "Teacher" || ugr.RoleCode == "TA") return RedirectToAction("Teacher", "Course"); else { return RedirectToAction("Student", "Course"); } } } else { ModelState.AddModelError("", "Invalid login attempt."); return View(model); } //var result = //// This doesn't count login failures towards account lockout //// To enable password failures to trigger account lockout, change to shouldLockout: true //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); //switch (result) //{ // case SignInStatus.Success: // return RedirectToLocal(returnUrl); // case SignInStatus.LockedOut: // return View("Lockout"); // case SignInStatus.RequiresVerification: // return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); // case SignInStatus.Failure: // default: // ModelState.AddModelError("", "Invalid login attempt."); // return View(model); //} }
/// <summary> /// Gets the incoming OpenID request if there is one, or null if none was detected. /// </summary> /// <param name="request">The incoming HTTP request to extract the message from.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The request that the hosting Provider should process and then transmit the response for. /// Null if no valid OpenID request was detected in the given HTTP request. /// </returns> /// <exception cref="ProtocolException">Thrown if the incoming message is recognized /// but deviates from the protocol specification irrecoverably.</exception> /// <remarks> /// Requests may be infrastructural to OpenID and allow auto-responses, or they may /// be authentication requests where the Provider site has to make decisions based /// on its own user database and policies. /// </remarks> public async Task<IRequest> GetRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(request, "request"); IDirectedProtocolMessage incomingMessage = null; try { incomingMessage = await this.Channel.ReadFromRequestAsync(request, cancellationToken); if (incomingMessage == null) { // If the incoming request does not resemble an OpenID message at all, // it's probably a user who just navigated to this URL, and we should // just return null so the host can display a message to the user. if (request.Method == HttpMethod.Get && !request.RequestUri.QueryStringContainPrefixedParameters(Protocol.Default.openid.Prefix)) { return null; } ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } IRequest result = null; var checkIdMessage = incomingMessage as CheckIdRequest; if (checkIdMessage != null) { result = new AuthenticationRequest(this, checkIdMessage); } if (result == null) { var extensionOnlyRequest = incomingMessage as SignedResponseRequest; if (extensionOnlyRequest != null) { result = new AnonymousRequest(this, extensionOnlyRequest); } } if (result == null) { var checkAuthMessage = incomingMessage as CheckAuthenticationRequest; if (checkAuthMessage != null) { result = new AutoResponsiveRequest(incomingMessage, new CheckAuthenticationResponseProvider(checkAuthMessage, this), this.SecuritySettings); } } if (result == null) { var associateMessage = incomingMessage as IAssociateRequestProvider; if (associateMessage != null) { result = new AutoResponsiveRequest(incomingMessage, AssociateRequestProviderTools.CreateResponse(associateMessage, this.AssociationStore, this.SecuritySettings), this.SecuritySettings); } } if (result != null) { foreach (var behavior in this.Behaviors) { if (await behavior.OnIncomingRequestAsync(result, cancellationToken)) { // This behavior matched this request. break; } } return result; } throw ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } catch (ProtocolException ex) { IRequest errorResponse = this.GetErrorResponse(ex, request, incomingMessage); if (errorResponse == null) { throw; } return errorResponse; } }