//Code to Create UserCredentials of the Organisation public string create(Admins admins) { AuthModel authModel = modelCreation.Create(admins); string confirmation = create(authModel); return(confirmation); }
//Code to Create UserCredentials of the Customer public string create(Customer customer) { AuthModel authModel = modelCreation.Create(customer); string confirmation = create(authModel); return(confirmation); }
public async Task Login(AuthModel authModel) { AuthViewModel authViewModel = new AuthViewModel(); authViewModel.Email = authModel.Email; authViewModel.Password = authModel.Password; await authViewModel.LoginUser(authModel); var viewModel = ServiceLocator.Current.GetInstance <MainNavigationViewModel>(); var typeValue = viewModel.ViewType; Type type = typeof(LoginPage); switch (typeValue) { case ViewType.LoginPage: type = typeof(LoginPage); await Navigation.PushAsync(new LoginPage()); break; case ViewType.RegisterPage: type = typeof(RegisterPage); await Navigation.PushAsync(new RegisterPage()); break; case ViewType.MainPage: type = typeof(MainPage); await Navigation.PushAsync(new MainPage()); break; } }
public bool Exists(AuthModel user) { try { using (var connection = _odsHelper.Connection()) { var sql = @" IF EXISTS ( SELECT 1 FROM AuthUsers WHERE UserName = @UserName) BEGIN SELECT CONVERT(BIT, 1) END ELSE BEGIN SELECT CONVERT(BIT, 0) END"; connection.Open(); var parameters = new DynamicParameters(); parameters.Add("@UserName", user.UserName, DbType.String, ParameterDirection.Input); return(connection.QueryFirst <bool>(sql, parameters, commandType: CommandType.Text)); } } catch (Exception ex) { _odsHelper.Logger().LogError(ex, "Error checking if user exists"); return(false); } }
public async void SalonLogin() { using (var client = new HttpClient()) { // New code: client.BaseAddress = new Uri("http://localhost:9000/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { HttpResponseMessage response = await client.GetAsync("SalonLogin"); response.EnsureSuccessStatusCode(); // Throw if not a success code. // HTTP POST var gizmo = new AuthModel() { Username = "******", Password = "******" }; response = await client.PostAsJsonAsync("SalonLogin/23", gizmo); if (response.IsSuccessStatusCode) { // Get the URI of the created resource. Uri gizmoUrl = response.Headers.Location; } } catch (HttpRequestException e) { // Handle exception. } } }
public AuthModel Login([FromBody] AccountLoginModel model) { var user = _readOnlyRepository.FirstOrDefault <Account>(x => x.Email == model.Email); if (user == null) { throw new HttpException((int)HttpStatusCode.NotFound, "User doesn't exist."); } if (!user.CheckPassword(model.Password)) { throw new HttpException((int)HttpStatusCode.Unauthorized, "Password doesn't match."); } var authModel = new AuthModel { email = user.Email, access_token = AuthRequestFactory.BuildEncryptedRequest(user.Email), role = new RoleModel { bitMask = 2, title = "admin" } }; return(authModel); }
public async Task <IActionResult> Token([FromBody] AuthModel param) { if (param == null) { return(BadRequest("Пользователь не установлен")); } var token = await _userService.Authenticate(param.login, param.password); if (token == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); } Employee emp = EmployeeService.GetEmployee(token.IdUser); // Формируем ответ var response = new { AcessToken = token.TokenAcess, RefreshToken = token.TokenRefresh, EmployeeID = emp.EmployeeId }; // Отправляем ответ return(Ok(response)); }
public async Task <IActionResult> Token(AuthModel model) { var isValid = await ApiProvider.AuthorizeAsync(model, CancellationToken.None); if (!isValid) { return(new UnauthorizedResult()); } var jwtSettings = new JwtSettings(DateTime.UtcNow); _configuration.GetSection("JwtSettings").Bind(jwtSettings); jwtSettings.Claims = GetClaims(model); var jwt = new JwtSecurityToken(jwtSettings.Issuer, jwtSettings.Audience, notBefore: jwtSettings.Now, claims: jwtSettings.Claims, expires: jwtSettings.Expires, signingCredentials: new SigningCredentials(jwtSettings.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256) ); var result = new TokenModel { Token = new JwtSecurityTokenHandler().WriteToken(jwt), Expires = jwtSettings.Expires, Login = model.Login, Type = model.AuthType }; return(new JsonResult(result)); }
public async Task Login() { string response = await _httpClient.GetStringAsync(Endpoints.BaseUrl); _csrfToken = Regex.Match(response, "csrf_token\":\"(.*?)\"").Groups[1].Value; var headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("referer", Endpoints.BaseUrl + "/"), new KeyValuePair <string, string>("X-CSRFToken", _csrfToken), new KeyValuePair <string, string>("user-agent", UserAgent), }; ResponseResult resp = await _httpClient.PostAsync(Endpoints.LoginUrl, $"username={_username}&password={_password}", headers); switch (resp.Code) { case 200: AuthModel authModel = JsonConvert.DeserializeObject <AuthModel>(resp.ResponseBody); if (authModel.authenticated) { IsLoggedIn = true; } break; case 400: //TODO challenge throw new InstagramException(); default: //TODO challenge throw new InstagramException(); } }
public void GetToken() { using (WebClient client = new WebClient()) { // POST https://accounts.google.com/o/oauth2/token HTTP/1.1 // User - Agent: google - api - dotnet - client / 1.14.0.0(gzip) // Content - Type: application / x - www - form - urlencoded // Host: accounts.google.com // Content - Length: 731 // Connection: Keep - Alive string scopesStr = string.Join("+", scopes); NameValueCollection nvc = new NameValueCollection(); nvc.Add("client_id", Settings.Default.CLIENT_WEB_ID); nvc.Add("client_secret", Settings.Default.CLIENT_WEB_SECRET); nvc.Add("code", authCode); nvc.Add("grant_type", "authorization_code"); nvc.Add("redirect_uri", "https://developers.google.com/apis-explorer/oauthWindow.html"); nvc.Add("scope", scopesStr); client.Headers.Add(HttpRequestHeader.Host, "accounts.google.com"); client.Headers.Add(HttpRequestHeader.KeepAlive, "true"); client.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded"); client.Headers.Add(HttpRequestHeader.UserAgent, "google-api-dotnet-client/1.14.0.0 (gzip)"); string result = client.UploadString("https://accounts.google.com/o/oauth2/token", "POST", ConvertNVCToString(nvc)); authData = JsonConvert.DeserializeObject <AuthModel>(result); Console.WriteLine(result); Thread.Sleep(3000); GPlusController.Instance.GetMyInfo(authData.AccessToken); } }
public async Task <ActionResult <AuthResponse> > RegisterUserAsync([FromBody] AuthModel request) { var dbUser = await _UserManager.GetAuthDetails(request.Username); if (dbUser is not null) { return(Conflict()); } var createdUser = await _UserManager.CreateAsync(new AuthModel(request.Id) { Username = request.Username, Password = request.Password }); await _RefreshTokenManager.CreateAsync(new RefreshTokenModel { Token = Guid.NewGuid().ToString(), UserId = createdUser.Id }); var response = new AuthResponse(createdUser.Id); return(Created(createdUser.Id.ToString(), response)); }
public async Task <Guid> AuthenticateUser(AuthModel authModel) { try { var users = await _context.Users.ToArrayAsync(); var user = users.Single(u => u.Username == authModel.Username); if (!PasswordTool.ValidatePassword(authModel.Password, user.Password)) { throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, "Invalid password"); } return(user.Id); } catch (HttpStatusCodeException) { throw; } catch (ArgumentNullException) { throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, "User not found"); } catch (InvalidOperationException) { throw new HttpStatusCodeException(StatusCodes.Status401Unauthorized, "User not found"); } catch (Exception e) { throw new HttpStatusCodeException(StatusCodes.Status500InternalServerError, e.Message); } }
private UserInfo GetUser(int tenantId, AuthModel memberModel) { memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim(); if (string.IsNullOrEmpty(memberModel.PasswordHash)) { memberModel.Password = (memberModel.Password ?? "").Trim(); if (!string.IsNullOrEmpty(memberModel.Password)) { memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password); } } var user = UserManager.GetUsersByPasswordHash( tenantId, memberModel.UserName, memberModel.PasswordHash); if (user == null || !UserManager.UserExists(user)) { throw new Exception("user not found"); } return(user); }
public async Task <ActionResult <dynamic> > Autentication([FromBody] AuthModel auth) { logger.LogInformation("Action Autentication :: AuthController -> execute" + DateTime.Now.ToLongTimeString()); var user = _userAppService.Login(auth.user, Encryptor.GenerateHashMd5(auth.password)); if (user == null) { var result = new ObjectResult(new { erro = "User or password incorret" }); result.StatusCode = 401; return(result); } // Gera o Token var token = TokenService.GenerateToken(new User { IdUser = user.IdUser, Hometown = user.Hometown }); // Retorna os dados return(new { token = token }); }
public void Authorize(AuthModel Model) { if (WebConfigurationManager.AppSettings["KeyStore"] == Model.Key) { FormsAuthentication.SetAuthCookie(Model.Sid, true); } }
private async Task <JsonResult> CreateAuthModel() { Claim userClaim = HttpContext.User.Claims.FirstOrDefault(a => a.Type == ClaimTypes.Name); AuthModel authModel = JsonConvert.DeserializeObject <AuthModel>(userClaim.Value); return(await ResultHandler.Success(authModel)); }
public ActionResult <AuthResultModel> Authenticate(AuthModel authModel) { User user = _userRepository.GetByEmail(authModel.Email); if (user != null) { if (user.Password == authModel.Password) { return(new AuthResultModel() { IsSuccess = true, User = new UserModel() { Id = user.Id, Name = user.Name, Email = user.Email } }); } } return(new AuthResultModel() { IsSuccess = false, User = null }); }
public async Task <ActionResult <User> > PostUser([FromBody] AuthModel auth) { var checkUser = await _context.users.FirstOrDefaultAsync(x => x.Login == auth.Login); if (checkUser != null) { return(BadRequest(new { errorText = "Такой логин уже есть." })); } var user = new User() { Login = auth.Login }; _context.users.Add(user); await _context.SaveChangesAsync(); var newUser = await _context.users.FirstOrDefaultAsync(x => x.Login == auth.Login); SHA256 hash = SHA256.Create(); var hashPass = string.Concat(hash.ComputeHash(Encoding.UTF8.GetBytes(auth.Password)).Select(x => x.ToString("X2"))); var pass = new Password() { PassWord = hashPass, UserId = newUser.Id }; _context.passwords.Add(pass); await _context.SaveChangesAsync(); return(CreatedAtAction("GetUser", new { id = newUser.Id }, newUser)); }
public ActionResult <ResponseModel> GetList() { var auth = new AuthModel(); var data = new Newtonsoft.Json.Linq.JObject(); try { auth = _context.Auth.Single(a => a.token == HttpContext.Session.GetString("token")); } catch (Exception ex) { data["msg"] = ex.Message; return(new ResponseModel { status = 404, statusText = "failure", data = data, }); } var list = _context.ToDo.Where(item => item.uuid == auth.uuid).ToList().OrderByDescending(item => item.datetime); data["list"] = (Newtonsoft.Json.Linq.JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(Newtonsoft.Json.JsonConvert.SerializeObject(list)); return(new ResponseModel { status = 200, statusText = "success", data = data }); }
public AuthModel CreateToken(string username, string password) { var identity = GetIdentity(username, password); if (identity == null) { return(null); } var now = DateTime.UtcNow; var jwt = new JwtSecurityToken( issuer: AuthConfiguaration.Issuer, audience: AuthConfiguaration.Audience, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthConfiguaration.Lifetime)), signingCredentials: new SigningCredentials(AuthConfiguaration.GetSymmetricSecurityKey, SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new AuthModel { AccessToken = encodedJwt, Username = identity.Name }; return(response); }
public static void SaveAccount(AuthModel auth) { Account account = new Account(); account.Properties.Add("Token", auth.Token); account.Properties.Add("ExpiresIn", auth.ExpiresIn); account.Properties.Add("AuthType", auth.AuthType.ToString()); account.Properties.Add("IdUser", auth.IdUser); account.Properties.Add("UserName", auth.UserName); account.Properties.Add("UserPhone", auth.UserPhone); if (auth.IdSocialNetwork == null) { auth.IdSocialNetwork = string.Empty; } account.Properties.Add("IdSocialNetwork", auth.IdSocialNetwork); try { AccountStore.Create().Save(account, _servideId); } catch (Exception e) { string exc = e.ToString(); } auth.ExpirationDate = DateTime.Now + TimeSpan.FromSeconds(Convert.ToDouble(auth.ExpiresIn)); Account = auth; }
public IActionResult AuthValid([FromBody] AuthModel model) { if (model == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } bool flag = WeChatMsgCrypt.VerifySignature(model.token, model.signature, model.timestamp, model.nonce); if (flag) { string res = @"<xml><ToUserName><![CDATA[oBtEu1ML2IqmbjIjDHw3nxQS2Acg]]></ToUserName> <FromUserName><![CDATA[gh_227cce7d299c]]></FromUserName> <CreateTime>1550501649</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[hello world]]></Content> </xml>"; string res2 = @"<xml><ToUserName><![CDATA[oBtEu1ML2IqmbjIjDHw3nxQS2Acg]]></ToUserName> <FromUserName><![CDATA[gh_227cce7d299c]]></FromUserName> <CreateTime>1550501649</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Image> <MediaId><![CDATA[yb73NMR9jo00f5bMUilUR2X__D3gceEiu0HK_JaJcZJTlw5jnCVtiIm1lw9Qy8Rc]]></MediaId> </Image> </xml>"; } return(Ok(model)); }
public static async Task <bool> ValidateLoginAsync() { AccountStore accountStore = AccountStore.Create(); Account account = accountStore.FindAccountsForService(_servideId).SingleOrDefault(); if (account != null) { bool result = await RestService.Instance.ValidateTokenAsync(account.Properties["Token"]); if (result) { Account = new AuthModel { Token = account.Properties["Token"], ExpiresIn = account.Properties["ExpiresIn"], IdUser = account.Properties["IdUser"], UserName = account.Properties["UserName"], UserPhone = account.Properties["UserPhone"], IdSocialNetwork = account.Properties["IdSocialNetwork"], AuthType = (AuthType)Enum.Parse(typeof(AuthType), account.Properties["AuthType"]), ExpirationDate = DateTime.Now + TimeSpan.FromSeconds(Convert.ToDouble(account.Properties["ExpiresIn"])) }; } return(result); } return(false); }
public AuthPasswordModel Authenticate(AuthModel user) { try { using (var connection = _odsHelper.Connection()) { var sql = @" SELECT PasswordHash ,PasswordSalt FROM AuthUsers WHERE UserName = @UserName"; connection.Open(); var parameters = new DynamicParameters(); parameters.Add("@UserName", user.UserName, DbType.String, ParameterDirection.Input); return(connection.QueryFirst <AuthPasswordModel>(sql, parameters, commandType: CommandType.Text)); } } catch (Exception ex) { _odsHelper.Logger().LogError(ex, "Error authenticating user"); return(null); } }
public async Task <AuthModel> GetTokenAsync(TokenRequestModel model) { var authModel = new AuthModel(); var user = await _userManager.FindByEmailAsync(model.Email); if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password)) { authModel.Message = "Email or Password is incorrect!"; return(authModel); } var jwtSecurityToken = await CreateJwtToken(user); var rolesList = await _userManager.GetRolesAsync(user); authModel.IsAuthenticated = true; authModel.Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken); authModel.Email = user.Email; authModel.Username = user.UserName; authModel.ExpiresOn = jwtSecurityToken.ValidTo; authModel.Roles = rolesList.ToList(); return(authModel); }
private void AuthModel_Is_With_Not_Existed_Email() { _authModel = new AuthModel() { Email = "*****@*****.**" }; }
public async Task <ActionResult> Index(AuthModel model) { // Get an instance of the Authentication class. var auth = Util.GetRestPkiClient().GetAuthentication(); // Call the Complete method with the signed nonce, the signature value, the signer, the signer // certificate's content and the security context. The call yields a Validation Results which // denotes whether the authentication was successful or not. var validationResults = await auth.CompleteAsync(model.Nonce, model.CertContent, model.Signature, Util.GetSecurityContextId()); // Check the authentication result. if (!validationResults.IsValid) { // If the authentication was not successful, we render a page showing what went wrong. return(View("Failed", validationResults)); } // At this point, you have assurance that the certificate is valid according to the // TrustArbitrator you selected when starting the authentication and that the user is indeed the // certificate's subject. Now, you'd typically query your database for a user that matches one of // the certificate's fields, such as userCert.EmailAddress or userCert.PkiBrazil.CPF (the actual // field to be used as key depends on your application's business logic) and set the user ID on // the auth cookie. For demonstration purposes, we'll set the email address directly on the // cookie as if it were the user ID. var userCert = auth.GetCertificate(); FormsAuthentication.SetAuthCookie(userCert.EmailAddress, false); // Redirect to the initial page with the user logged in. return(RedirectToAction("Index", "Home")); }
//Code to Create UserCredentials of the Organisation public string create(Organisation organisation) { AuthModel authModel = modelCreation.Create(organisation); string confirmation = create(authModel); return(confirmation); }
/// <summary> /// Constructor /// </summary> public override void OnActionExecuting(HttpActionContext context) { AuthModel authModel = new AuthModel(); JSendMessage json; var header = context.Request.Headers.SingleOrDefault(x => x.Key == "token"); bool valid, isAdmin, okDate; if (header.Value == null) { valid = false; } else { // Tokenul apartine unui admin isAdmin = authModel.VerifyAdminToken(header.Value.First()); // Tokenul este valid okDate = authModel.VerifyToken(header.Value.First()); valid = isAdmin && okDate; } if (!valid) { json = new JSendMessage("fail", "Invalid Authorization Key"); context.Response = context.Request.CreateResponse(HttpStatusCode.Forbidden, json); } }
public IActionResult Login(AuthModel authModel) { if (!ModelState.IsValid) { return(View(authModel)); } var user = _userManager.Get(authModel.UserName.Trim(), authModel.UserPassword); if (user == null) { ModelState.AddModelError("default", "User or password is incorrect"); return(View(authModel)); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Login), new Claim("Id", user.Id.ToString()) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties()); return(RedirectToActionPermanent("GetDictionary", "Dictionary")); }
public AuthModel ForgotPassword([FromBody] ForgotPasswordModel model) { Ems.SendSimpleMessage(model.Email); var user = _readOnlyRepository.FirstOrDefault<Account>(x => x.Email == model.Email); if (user == null) throw new HttpException((int)HttpStatusCode.NotFound, "User doesn't exist."); var authModel = new AuthModel { access_token = "SuperHash" }; return authModel; }
public HttpResponseMessage Post(AuthModel auth) { if (auth != null) { var student = EventRepository.Students.FirstOrDefault(_ => _.Email == auth.Username && _.Password == auth.Password); if (student != null) return Request.CreateResponse<Student>(HttpStatusCode.Created, student); } return Request.CreateErrorResponse(HttpStatusCode.NotFound,"Username and password do not match");; }
public AuthModel Login([FromBody] AccountLoginModel model) { var user = _readOnlyRepository.FirstOrDefault<Account>(x => x.Email == model.Email); if (user == null) throw new HttpException((int)HttpStatusCode.NotFound, "User doesn't exist."); if (!user.CheckPassword(model.Password)) throw new HttpException((int)HttpStatusCode.Unauthorized, "Password doesn't match."); var authModel = new AuthModel { email = user.Email, access_token = AuthRequestFactory.BuildEncryptedRequest(user.Email), role = new RoleModel { bitMask = 2, title = user.Status } }; return authModel; }