예제 #1
0
        public IActionResult Login([FromBody] UsernameAndPassword creds)
        {
            var response = logins.SingleOrDefault(m => m.UserName == creds.UserName && m.Password == creds.Password);

            if (response == null)
            {
                return(null);
            }
            else
            {
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
                var tokenDescriptor = new SecurityTokenDescriptor {
                    Subject = new System.Security.Claims.ClaimsIdentity(new Claim[] {
                        new Claim(ClaimTypes.Name, creds.UserName.ToString()),
                        new Claim(ClaimTypes.Version, "v1")
                    }),
                    Expires            = DateTime.UtcNow.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var  tok  = tokenHandler.CreateToken(tokenDescriptor);
                User user = new User();
                user.UserName = creds.UserName;
                user.token    = tokenHandler.WriteToken(tok);
                //return  Ok(new {message ="Successful login!!"+ user } );
                return(Ok(user.token));
            }
        }
예제 #2
0
        public IEnumerable <UsernameAndPassword> signUp(UsernameAndPassword creds)
        {
            using (SqlConnection con = new SqlConnection(constr));
            SqlCommand cmd = new SqlCommand("spAddEmployee", con);

            cmd.CommandType = CommandType.StoredProcedure;
        }
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>The bound value.</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string username = controllerContext.RequestContext.HttpContext.Request["username"];
            string password = controllerContext.RequestContext.HttpContext.Request["password"];
            var    creds    = new UsernameAndPassword(username, password);

            return(creds);
        }
예제 #4
0
        /// <summary>
        /// Authenticates the user.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns>AuthenticatedUser.</returns>
        public AuthenticatedUser AuthenticateUser(UsernameAndPassword args)
        {
            var single = _database.Single <User, object>("User_GetOwnerPasswordByUsername", new { args.Username }, _database.AutoPopulate <User>);

            bool isValid = ValidatePassword(args, single);

            return(isValid ? new AuthenticatedUser {
                Username = single.Username
            } : null);
        }
 public IActionResult SigninPassword([FromBody] UsernameAndPassword uap)
 {
     return(Json(new SigninResult
     {
         Exp = DateTime.UtcNow.AddDays(7)
               .Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Seconds,
         Id = 1,
         Type = uap.Phone.EndsWith('1') ? "student" : "teacher",
         Name = "张三"
     }));
 }
        public void AttemptLogin(string username, string password, IStoredCredentialsRepository repo)
        {
            var credentials = new UsernameAndPassword {
                Username = username,
                Password = password
            };

            var authenticationService = GetAuthenticationService(repo);

            authenticationResult = authenticationService.Authenticate(credentials);
        }
예제 #7
0
        public async Task <IActionResult> RegisterPassword([FromBody] UsernameAndPassword uap)
        {
            try
            {
                var user = await _loginService.SignUpPhoneAsync(new UserInfo { Phone = uap.Phone, Password = uap.Password });

                return(Json(CreateSigninResult(user)));
            }
            catch (PhoneAlreadyExistsException)
            {
                return(StatusCode(409, new { msg = "手机已注册" }));
            }
        }
예제 #8
0
        /// <summary>
        /// Validates the password.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <param name="single">The single.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        private bool ValidatePassword(UsernameAndPassword args, User single)
        {
            bool isValid = false;

            if (single != null)
            {
                try
                {
                    isValid = _crypto.IsMatch(args.Password, single.Password);
                }
                catch
                {
                    isValid = false;
                }
            }
            return(isValid);
        }
예제 #9
0
        public async Task <IActionResult> SigninPassword([FromBody] UsernameAndPassword uap)
        {
            try
            {
                var user = await _loginService.SignInPhoneAsync(new UserInfo { Phone = uap.Phone, Password = uap.Password });

                //await HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal());
                return(Json(CreateSigninResult(user)));
            }
            catch (PasswordErrorException)
            {
                return(StatusCode(401, new { msg = "用户名或密码错误" }));
            }
            catch (UserNotFoundException)
            {
                return(StatusCode(404, new { msg = "用户不存在" }));
            }
        }
예제 #10
0
        //<----defines the authenticate logic---->
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            HttpRequestMessage        request        = context.Request;
            AuthenticationHeaderValue authentication = request.Headers.Authorization;

            if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase))
            {
                string enUsernameAndPassword = authentication.Parameter;
                if (enUsernameAndPassword != null)
                {
                    try
                    {
                        // Convert 64-base encoding credential to binary
                        Encoding encoding = Encoding.GetEncoding("ISO-8859-1");
                        string   UsernameAndPassword;
                        UsernameAndPassword = encoding.GetString(Convert.FromBase64String(enUsernameAndPassword));
                        int     seperator = UsernameAndPassword.IndexOf(':');
                        string  username  = UsernameAndPassword.Substring(0, seperator);
                        string  password  = UsernameAndPassword.Substring(seperator + 1);
                        Resumes resumes   = new Resumes();
                        // if username is Tom, password is 123, authenticate. Otherwise, unauthenticate.
                        if (await resumes.checkIndent(username, password) != null)
                        {
                            var claims = new List <Claim>()
                            {
                                new Claim(ClaimTypes.Name, username)
                            };
                            var id        = new ClaimsIdentity(claims, "Basic");
                            var principal = new ClaimsPrincipal(new[] { id });
                            context.Principal = principal;
                        }
                    }
                    catch (FormatException)
                    {
                        HttpContext.Current.Response.StatusCode = 401;
                    }
                }
            }
            else
            {
                context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
            }
        }
 public IActionResult RegisterPassword([FromBody] UsernameAndPassword uap)
 {
     return(Json(new SigninResult()));
 }
예제 #12
0
 public IActionResult Signup([FromBody] UsernameAndPassword creds)
 {
     // _logindetail.Add(creds);
     return(Ok());
 }
예제 #13
0
        public ActionResult Index(UsernameAndPassword usernameAndPassword)
        {
            var success = Redirect(string.Format("/{0}", usernameAndPassword.Username));

            return(Form(usernameAndPassword, success));
        }