Exemple #1
0
        public async Task SignsUpOkOnValidData(string nickname, string password)
        {
            var token = await authenticationService.SignUp(nickname, password);

            Assert.NotNull(token);
            Assert.NotNull(JwtTool.DecodeToken(token));
        }
        // jwt

        public bool Login()
        {
            var dictionary = new Dictionary <string, object> {
                { "UserId", 123 },
            };

            JwtTool.Encode(dictionary, JwtTool.secret);
            return(true);
        }
Exemple #3
0
        // Given id and password, authenticate the user
        public static bool Authenticate(HttpContext context)
        {
            bool authenticated = false;

            // get user id and password
            string id            = WebTools.Get(context, "id");
            string password      = WebTools.Get(context, "password");
            string navigation_id = WebTools.GetNavigationId(context);

            if (string.IsNullOrEmpty(id) == false && string.IsNullOrEmpty(navigation_id) == false)
            {
                // find user with matching id and password
                var db    = (SQL)context.Items["db"];
                var param = new Dictionary <string, object>();
                param["id"] = id; param["navigation_id"] = navigation_id;
                var users = db.Query(
                    "SELECT * FROM core_user WHERE id = @id AND navigation_id = @navigation_id"
                    , param);

                if (users != null && users.Count() == 1)
                {
                    var user = users.First();

                    bool valid = false;
                    // if password is DBNull and also empty then pass
                    if (user.Get("password") is DBNull || string.IsNullOrEmpty($"{user.Get("password")}"))
                    {
                        valid = true;
                    }

                    // Verify the password
                    else if (SecurePasswordHasher.Verify(password, $"{user.Get("password")}"))
                    {
                        valid = true;
                    }

                    if (valid)
                    {
                        // create a new token
                        var token = JwtTool.CreateToken(
                            context
                            , $"{user["id"]}"
                            , $"{user["name"]}"
                            , RolesOfUser(context, $"{user["_id"]}")
                            );

                        RefreshHeader(context, token);
                        // is authenticated
                        authenticated = true;
                    }
                }
            }

            return(authenticated);
        }
Exemple #4
0
        public void UseToken(string token)
        {
            var jwt = JwtTool.DecodeToken(token);

            var userId = jwt.Claims
                         .Where(x => x.Type == ClaimsIdentity.DefaultNameClaimType)
                         .Select(x => int.Parse(x.Value))
                         .First();

            UserId = userId;
        }
Exemple #5
0
        public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation)
        {
            IEnumerable <string> headers;

            if (actionContext.Request.Headers.TryGetValues("token", out headers))
            {
                var loginName = JwtTool.Decode(JwtTool.secret, headers.First())["LoginName"].ToString();
                var id        = (int)JwtTool.Decode(JwtTool.secret, headers.First())["Id"];
                (actionContext.ControllerContext.Controller as ApiController).User = new ApplicationUser(id, loginName);
                return(await continuation());
            }
            return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
        }
Exemple #6
0
        public IHttpActionResult Login(UserLoginViewModel userLoginViewModel)
        {
            var payload = new Dictionary <string, object>
            {
                { "userId", "123" },
                { "LoginName", userLoginViewModel.LoginName }
            };

            return(Ok(new ResponseData()
            {
                Data = JwtTool.Encode(payload, JwtTool.secret)
            }));
        }
Exemple #7
0
        public async Task <string> SignIn(string nickname, string password)
        {
            await using var context = dbContextFactory.Create();

            var user = await context.Users
                       .Where(x => x.Nickname == nickname)
                       .FirstOrDefaultAsync();

            if (user == null)
            {
                throw new DatesException("No such user was found");
            }

            if (Hash(password) != user.PasswordHash)
            {
                throw new DatesException("Incorrect password");
            }

            return(JwtTool.IssueToken(user.Id));
        }
Exemple #8
0
        public async Task <string> SignUp(string nickname, string password)
        {
            if (string.IsNullOrWhiteSpace(nickname))
            {
                throw new DatesException("Invalid nickname");
            }

            if (string.IsNullOrWhiteSpace(password) || password.Length < 8)
            {
                throw new DatesException("Invalid password");
            }

            await using var context     = dbContextFactory.Create();
            await using var transaction = await context.Database.BeginTransactionAsync();

            var userExists = await context.Users
                             .Where(x => x.Nickname == nickname)
                             .AnyAsync();

            if (userExists)
            {
                throw new DatesException("User already exists");
            }

            var user = new User
            {
                Nickname     = nickname,
                PasswordHash = Hash(password)
            };

            context.Users.Add(user);

            await context.SaveChangesAsync();

            await transaction.CommitAsync();

            return(JwtTool.IssueToken(user.Id));
        }
Exemple #9
0
        public static bool IsAuthenticated(HttpContext context)
        {
            bool authenticated = false;

            // do the JWT toekn thingy
            string token = null;

            if (context.Request.Headers.ContainsKey("Authorization"))
            {
                token = context.Request.Headers["Authorization"];
                token = token.Replace("Bearer ", "");
            }

            // if headers not given check cooikes - only if it is get and file download
            else if (
                context.Request.Cookies.ContainsKey("Authorization") &&
                context.Request.Method == "GET")
            {
                token = context.Request.Cookies["Authorization"];
                token = token.Replace("Bearer ", "");
            }

            else if (
                context.Request.Query.ContainsKey("Bearer") &&
                context.Request.Method == "GET")
            {
                token = context.Request.Query["Bearer"];
            }


            if (string.IsNullOrEmpty(token) == false)
            {
                try
                {
                    // decoded token will be saved as token in the res.locals
                    var decodedToken = JwtTool.Verify(token, $"{context.Items["secret"]}");
                    context.Items["token"] = decodedToken;
                    if (decodedToken != null)
                    {
                        // if authentication is expiring soon then issue a new token
                        // if half of the time is passed then renew
                        var exp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                        exp = exp.AddSeconds((Int64)decodedToken["exp"]);

                        if (exp < DateTime.Now.AddDays(-1))
                        {
                            // new token
                            var newToken = JwtTool.CreateToken(
                                context
                                , $"{decodedToken["unique_name"]}"
                                , $"{decodedToken["nameid"]}"
                                , (string[])decodedToken["roles"]
                                );
                        }

                        RefreshHeader(context, token);

                        // authenticated
                        authenticated = true;
                    }
                }
                catch
                {
                    authenticated = false;
                }
            }

            return(authenticated);
        }
Exemple #10
0
 public GMClient(string deviceId, Brand brand, string clientId, string clientSecret) : base(deviceId, brand)
 {
     _clientId = clientId;
     _jwtTool  = new JwtTool(clientSecret);
 }
Exemple #11
0
        public string GetUserInfo()
        {
            var username = JwtTool.ValideLogined(ControllerContext.Request.Headers);

            return("用户名" + username);
        }