Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static UmbracoAuthToken GenerateUserAuthToken(UmbracoAuthToken authToken)
        {
            //Date Time
            var dateCreated = DateTime.UtcNow;

            var dateCreatedToString = dateCreated.ToString("u");
            //this probably should be allowed to be configurable but keeping it simple and reasonable for now
            var dateExpires         = dateCreated.Add(TimeSpan.FromMinutes(60));
            var dateExpiresTostring = dateExpires.ToString("u");

            //Create JSON payload for JWT token
            var payload = new Dictionary <string, object>()
            {
                { "identity_id", authToken.IdentityId },
                { "identity_type", authToken.IdentityType },
                { "date_created", dateCreatedToString },
                { "date_expires", dateExpiresTostring }
            };

            //Encode the JWT token with JSON payload, algorithm & our secret in constant
            var encodedToken = JsonWebToken.Encode(payload, _secretKey, JwtHashAlgorithm.HS256);

            //Return same object we passed in (Now with Date Created & Token properties updated)
            authToken.DateCreated = dateCreated;
            authToken.DateExpires = dateExpires;
            authToken.AuthToken   = encodedToken;

            //Return the updated object
            return(authToken);
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="jwtToken"></param>
        /// <returns></returns>
        public static UmbracoAuthToken DecodeUserAuthToken(string jwtToken)
        {
            //Object to return
            var userAuth = new UmbracoAuthToken();

            //Decode & verify token was signed with our secret
            var jsonPayload = JsonWebToken.DecodeToObject(jwtToken, _secretKey) as IDictionary <string, object>;

            //Just the presence of the token & being deserialised with correct SECRET key is a good sign
            if (jsonPayload != null)
            {
                //Do DateTime conversion from u type back into DateTime object
                DateTime dateCreated;
                DateTime dateExpires;
                DateTime.TryParseExact(jsonPayload["date_created"].ToString(), "u", null, DateTimeStyles.AdjustToUniversal, out dateCreated);
                DateTime.TryParseExact(jsonPayload["date_expires"].ToString(), "u", null, DateTimeStyles.AdjustToUniversal, out dateExpires);

                //Get the details of the user from the JWT payload
                userAuth.IdentityId   = Convert.ToInt32(jsonPayload["identity_id"]);
                userAuth.IdentityType = jsonPayload["identity_type"].ToString();
                userAuth.DateCreated  = dateCreated;
                userAuth.DateExpires  = dateExpires;
                userAuth.AuthToken    = jwtToken;
            }

            //Return the object
            return(userAuth);
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static bool IsTokenValid(UmbracoAuthToken authToken)
        {
            //Let's verify that this token is not expired
            if (authToken.DateExpires < DateTime.UtcNow)
            {
                return(false);
            }

            //Let's verify the token we have
            //Is what we have in the DB matching on the UserID as lookup

            //Try & find record in DB on UserID
            var lookupRecord = GetAuthToken(authToken.IdentityId);

            //If we find a record in DB
            if (lookupRecord != null)
            {
                //Lets verify the token we have is the same on the DB record
                //May not match as the user may have saved the password & caused a new token to be

                return(authToken.AuthToken == lookupRecord.AuthToken);
            }

            //No record found in the DB - so return false
            return(false);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Insert a new Auth Token into the custom DB table OR
        /// Update just the auth token if we find a record for the backoffice user already
        /// </summary>
        /// <param name="authToken"></param>
        public static void InsertAuthToken(UmbracoAuthToken authToken)
        {
            using (var scope = Current.ScopeProvider.CreateScope())
            {
                //Just to be 100% sure for data sanity that a record for the user does not exist already
                var existingRecord = GetAuthToken(authToken.IdentityId);

                //Insert new record if no item exists already
                if (existingRecord == null)
                {
                    //Getting issues with insert & ID being 0 causing a conflict
                    scope.Database.Insert(authToken);
                }
                else
                {
                    //Update the existing record
                    existingRecord.AuthToken   = authToken.AuthToken;
                    existingRecord.DateCreated = authToken.DateCreated;

                    //Save the existing record we found
                    scope.Database.Save(existingRecord);
                }

                //Always complete scope
                scope.Complete();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtToken"></param>
        /// <returns></returns>
        public static UmbracoAuthToken DecodeUserAuthToken(string jwtToken)
        {
            //Object to return
            var userAuth = new UmbracoAuthToken();

            //Decode & verify token was signed with our secret
            var jsonPayload = JsonWebToken.DecodeToObject(jwtToken, _secretKey) as IDictionary<string, object>;

            //Just the presence of the token & being deserialised with correct SECRET key is a good sign
            if (jsonPayload != null)
            {
                //Do DateTime conversion from u type back into DateTime object
                DateTime dateCreated;
                DateTime.TryParseExact(jsonPayload["date_created"].ToString(), "u", null, DateTimeStyles.AdjustToUniversal, out dateCreated);

                //Get the details of the user from the JWT payload
                userAuth.IdentityId = Convert.ToInt32(jsonPayload["identity_id"]);
                userAuth.IdentityType = jsonPayload["identity_type"].ToString();
                userAuth.DateCreated = dateCreated;
                userAuth.AuthToken = jwtToken;
            }

            //Return the object
            return userAuth;
        }
        public string Authorise(AuthCredentials auth)
        {
            //Verify user is valid credentials
            var isValidAuth = Security.ValidateBackOfficeCredentials(auth.Username, auth.Password);

            //Are credentials correct?
            if (isValidAuth)
            {
                //Get the backoffice user from username
                var user = ApplicationContext.Services.UserService.GetByUsername(auth.Username);

                //Check if we have an Auth Token for user
                var hasAuthToken = UserAuthTokenDbHelper.GetAuthToken(user.Id);

                //If the token already exists
                if (hasAuthToken != null)
                {
                    //Lets just return it in the request
                    return hasAuthToken.AuthToken;
                }

                //Else user has no token yet - so let's create one
                //Generate AuthToken DB object
                var newToken = new UmbracoAuthToken();
                newToken.IdentityId = user.Id;
                newToken.IdentityType = IdentityAuthType.User.ToString();

                //Generate a new token for the user
                var authToken = UmbracoAuthTokenFactory.GenerateUserAuthToken(newToken);

                //We insert authToken as opposed to newToken
                //As authToken now has DateTime & JWT token string on it now

                //Store in DB (inserts or updates existing)
                UserAuthTokenDbHelper.InsertAuthToken(authToken);

                //Return the JWT token as the response
                //This means valid login & client in our case mobile app stores token in local storage
                return authToken.AuthToken;
            }

            //Throw unauthorised HTTP error
            var httpUnauthorised = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            throw new HttpResponseException(httpUnauthorised);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static bool IsTokenValid(UmbracoAuthToken authToken)
        {
            //Let's verify the token we have
            //Is what we have in the DB matching on the UserID as lookup

            //Try & find record in DB on UserID
            var lookupRecord = GetAuthToken(authToken.IdentityId);

            //If we find a record in DB
            if (lookupRecord != null)
            {
                //Lets verify the token we have is the same on the DB record
                //May not match as the user may have saved the password & caused a new token to be generated
                return authToken.AuthToken == lookupRecord.AuthToken;
            }

            //No record found in the DB - so return false
            return false;
        }
        /// <summary>
        /// Insert a new Auth Token into the custom DB table OR
        /// Update just the auth token if we find a record for the backoffice user already
        /// </summary>
        /// <param name="authToken"></param>
        public static void InsertAuthToken(UmbracoAuthToken authToken)
        {
            //Just to be 100% sure for data sanity that a record for the user does not exist already
            var existingRecord = GetAuthToken(authToken.IdentityId);

            //Insert new record if no item exists already
            if (existingRecord == null)
            {
                //Getting issues with insert & ID being 0 causing a conflict
                Database.Insert(authToken);
            }
            else
            {
                //Update the existing record
                existingRecord.AuthToken = authToken.AuthToken;
                existingRecord.DateCreated = authToken.DateCreated;

                //Save the existing record we found
                Database.Save(existingRecord);
            }
        }
        /// <summary>
        /// Insert a new Auth Token into the custom DB table OR
        /// Update just the auth token if we find a record for the backoffice user already
        /// </summary>
        /// <param name="authToken"></param>
        public static void InsertAuthToken(UmbracoAuthToken authToken)
        {
            //Just to be 100% sure for data sanity that a record for the user does not exist already
            var existingRecord = GetAuthToken(authToken.IdentityId);

            //Insert new record if no item exists already
            if (existingRecord == null)
            {
                //Getting issues with insert & ID being 0 causing a conflict
                Database.Insert(authToken);
            }
            else
            {
                //Update the existing record
                existingRecord.AuthToken   = authToken.AuthToken;
                existingRecord.DateCreated = authToken.DateCreated;

                //Save the existing record we found
                Database.Save(existingRecord);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MemberService_Saving(IMemberService sender, SaveEventArgs<IMember> e)
        {
            //Saved entites (Could be more than one member saved. Very unlikely?)
            var member = e.SavedEntities.FirstOrDefault();

            //Found a member that has been saved
            if (member != null)
            {
                //Check if the password property (RawPasswordValue) is dirty aka has beeen changed
                var passIsDirty = member.IsPropertyDirty("RawPasswordValue");

                //Password has been changed
                if (passIsDirty)
                {
                    //Check if user already has token in DB (token created on first login/auth to API)
                    var hasAuthToken = UserAuthTokenDbHelper.GetAuthToken(member.Id);

                    //invalidate token (Only if token exists in DB)
                    //We have found an existing token
                    if (hasAuthToken != null)
                    {
                        //Generate AuthToken DB object
                        var newToken = new UmbracoAuthToken();
                        newToken.IdentityId = member.Id;
                        newToken.IdentityType = IdentityAuthType.Member.ToString();

                        //Generate a new token for the user
                        var authToken = UmbracoAuthTokenFactory.GenerateUserAuthToken(newToken);

                        //NOTE: We insert authToken as opposed to newToken
                        //As authToken now has DateTime & JWT token string on it now

                        //Store in DB (inserts or updates existing)
                        UserAuthTokenDbHelper.InsertAuthToken(authToken);
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static UmbracoAuthToken GenerateUserAuthToken(UmbracoAuthToken authToken)
        {
            //Date Time
            var dateCreated = DateTime.UtcNow;
            var dateCreatedToString = dateCreated.ToString("u");

            //Create JSON payload for JWT token
            var payload = new Dictionary<string, object>() {
                { "identity_id", authToken.IdentityId },
                { "identity_type", authToken.IdentityType },
                { "date_created", dateCreatedToString }
            };

            //Encode the JWT token with JSON payload, algorithm & our secret in constant
            var encodedToken = JsonWebToken.Encode(payload, _secretKey, JwtHashAlgorithm.HS256);

            //Return same object we passed in (Now with Date Created & Token properties updated)
            authToken.DateCreated = dateCreated;
            authToken.AuthToken = encodedToken;

            //Return the updated object
            return authToken;
        }
Exemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="authToken"></param>
        /// <returns></returns>
        public static UmbracoAuthToken GenerateUserAuthToken(UmbracoAuthToken authToken)
        {
            //Date Time
            var dateCreated         = DateTime.UtcNow;
            var dateCreatedToString = dateCreated.ToString("u");

            //Create JSON payload for JWT token
            var payload = new Dictionary <string, object>()
            {
                { "identity_id", authToken.IdentityId },
                { "identity_type", authToken.IdentityType },
                { "date_created", dateCreatedToString }
            };

            //Encode the JWT token with JSON payload, algorithm & our secret in constant
            var encodedToken = JsonWebToken.Encode(payload, _secretKey, JwtHashAlgorithm.HS256);

            //Return same object we passed in (Now with Date Created & Token properties updated)
            authToken.DateCreated = dateCreated;
            authToken.AuthToken   = encodedToken;

            //Return the updated object
            return(authToken);
        }