/// <summary>
        /// Authenticates a user and returns a JWT token serialized as JSON
        /// </summary>
        /// <param name="firstname">The first part of the username to authenticate</param>
        /// <param name="lastname">The last part of the username to authenticate</param>
        /// <param name="password">The user's password</param>
        /// <param name="minLevel">The minimum godlevel this user must be at to generate a token</param>
        /// <param name="payloadOptions">Options for the generated payload</param>
        /// <returns>JWT token string</returns>
        public JWToken Authenticate(string firstname, string lastname, string password, int minLevel, PayloadOptions payloadOptions)
        {
            UserProfileData profile = _userService.GetUserProfile(firstname, lastname, true);
            if (profile == null)
            {
                throw new AuthenticationException(AuthenticationFailureCause.UserNameNotFound);
            }

            if (profile.GodLevel < minLevel)
            {
                throw new AuthenticationException(AuthenticationFailureCause.WrongUserLevel);
            }

            var pwhash = Util.Md5Hash(Util.Md5Hash(password) + ":" + profile.PasswordSalt);
            if (!profile.PasswordHash.Equals(pwhash, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new AuthenticationException(AuthenticationFailureCause.InvalidPassword);
            }

            payloadOptions.UserId = profile.ID.ToString();
            payloadOptions.BirthDate = (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(profile.Created).ToUniversalTime();
            payloadOptions.PartnerId = profile.Partner.ToString();

            m_log.Info($"[JWTGATEWAY] Granted token for '{payloadOptions.Scope}' to user '{payloadOptions.Username}' until {payloadOptions.Exp}");

            return new JWToken(payloadOptions, m_sigUtil);
        }
Beispiel #2
0
        public JWToken(PayloadOptions payloadOptions, JWTSignatureUtil sigUtil)
        {
            Header = ValidHeader;
            Payload = payloadOptions;
            HasValidSignature = true;

            var body = EncodeBase64(Header) + "." + EncodeBase64(LitJson.JsonMapper.ToJson(payloadOptions));

            m_token = body + "." + sigUtil.Sign(body);
        }
Beispiel #3
0
        public string RESTRequestToken(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "application/json";

            if (m_authGateway == null)
            {
                m_log.Error("[JWTAUTH] Hit a bug check: the JWT gatway is not initialized... Why?");
                return JWTAuthErrors.BadAuthGateway;
            }

            if (httpRequest.ContentType != "application/json")
            {
                return JWTAuthErrors.BadJsonRead;
            }

            if (httpRequest.ContentLength <= 1)
            {
                return JWTAuthErrors.BadJsonRead;
            }

            if (!m_levelsAllowedPerScope.ContainsKey(param))
            {
                return JWTAuthErrors.BadScope;
            }

            var username = string.Empty;
            var password = string.Empty;

            try
            {
                var data = JsonMapper.ToObject(request);

                username = data["username"].ToString().Trim();
                password = data["password"].ToString();
            }
            catch (Exception)
            {
                return JWTAuthErrors.BadJsonRead;
            }

            var payload = new PayloadOptions();
            payload.Exp = DateTime.UtcNow.AddDays(1);
            payload.Scope = param;
            payload.Username = username;

            var nameSplit = Regex.Replace(username.ToLower(), @"[\s]+", " ").Split(' ');
            var firstname = nameSplit[0];
            var lastname = nameSplit.Length > 1 ? nameSplit[1] : "resident";

            try
            {
                var response = new Dictionary<string, string>
                {
                    {"token", m_authGateway.Authenticate(firstname, lastname, password, m_levelsAllowedPerScope[param], payload).ToString()}
                };

                return JsonMapper.ToJson(response);
            }
            catch (AuthenticationException ae)
            {
                m_log.Warn($"[JWTAUTH] Failed attempt to get token from {httpRequest.RemoteIPEndPoint} for user '{username}'. Error: {ae.Cause}");
                return JWTAuthErrors.AuthFailed(ae.Cause.ToString());
            }
        }