Beispiel #1
0
        public void silly_with_works()
        {
            var state = new CookieState("key").With("a", "1").With("b", "2");

            state["a"].ShouldEqual("1");
            state["b"].ShouldEqual("2");
        }
Beispiel #2
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                                      CancellationToken cancellationToken)
        {
            // Getting a cookie
            CookieHeaderValue cookie = request.Headers.GetCookies("sesstoken").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["sesstoken"];

                string token     = cookieState["token"];
                string tokenType = cookieState["token-type"];
            }

            var response = await base.SendAsync(request, cancellationToken);

            // Setting a cookie
            var pairs = new NameValueCollection();

            pairs["token"]      = "12345";
            pairs["token-type"] = "general";

            response.Headers.AddCookies(new CookieHeaderValue[]
            {
                new CookieHeaderValue("sesstoken", pairs)
                {
                    Expires = DateTimeOffset.Now.AddSeconds(30),
                    Path    = "/"
                }
            });

            return(response);
        }
Beispiel #3
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestHeaders   headers = actionContext.Request.Headers;
            IEnumerable <string> xsrfTokenList;

            if (actionContext.Request.Method == HttpMethod.Get || SkipFilterCheck(actionContext))
            {
                return;
            }

            if (!headers.TryGetValues(AppConstants.XsrfHeader, out xsrfTokenList))
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            string      tokenHeaderValue = xsrfTokenList.First();
            CookieState tokenCookie      = actionContext.Request.Headers.GetCookies().Select(c => c[AppConstants.XsrfCookie]).FirstOrDefault();

            if (tokenCookie == null)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                return;
            }

            try
            {
                AntiForgery.Validate(tokenCookie.Value, tokenHeaderValue);
            }
            catch (HttpAntiForgeryException ex)
            {
                NLogLogger.Instance.Log(ex);
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }
Beispiel #4
0
        public void parse_with_one_value()
        {
            var state = CookieState.Parse("key", "1");

            state.Name.ShouldEqual("key");
            state.Value.ShouldEqual("1");
        }
Beispiel #5
0
        public HttpResponseMessage verifyCookie()
        {
            HttpContext context   = HttpContext.Current;
            string      SessionId = "";
            string      UserId    = "";
            string      Username  = "";
            string      SubKey    = "";

            CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["session"];
                SessionId = cookieState["SessionId"];
                UserId    = cookieState["UserId"];
                Username  = cookieState["Username"];
                SubKey    = cookieState["SubKey"];
            }

            if (SubKey == (string)(context.Session["SubKey"]) & SessionId == (string)(context.Session["SessionId"]))
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "success"));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "failed"));
            }
        }
 public static DateTime?GetFirstAccessedTime(this HttpRequestMessage request)
 {
     try
     {
         if (request != null)
         {
             CookieHeaderValue cookie = request.Headers.GetCookies(FirstAccessedTimeCookieName).FirstOrDefault();
             if (cookie != null)
             {
                 CookieState cookieState = cookie[FirstAccessedTimeCookieName];
                 if (cookieState != null)
                 {
                     string   FirstAccessedTimeString = Encoding.ASCII.GetString(Convert.FromBase64String(cookieState.Value));
                     DateTime FirstAccessedTime;
                     if (DateTime.TryParse(FirstAccessedTimeString, out FirstAccessedTime))
                     {
                         return(FirstAccessedTime);
                     }
                 }
             }
         }
     }
     catch (Exception)
     {
     }
     return(null);
 }
        string GetSessionToken(HttpRequestMessage request)
        {
            CookieState sessionCookie = GetSessionCookie(request);

            if (sessionCookie == null)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden)
            }
            string token = sessionCookie.Value;

            if (string.IsNullOrEmpty(token))
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden)
            }
            ;
            return(token);
        }

        CookieState GetSessionCookie(HttpRequestMessage request)
        {
            const string sessionTokenKey    = "X-Session-Token";
            var          cookieHeaderValues = request.Headers.GetCookies(sessionTokenKey);
            var          sessionCookie      = cookieHeaderValues
                                              .Where(v => v.Expires == null || v.Expires > DateTimeOffset.Now)
                                              .SelectMany(r => r.Cookies)
                                              .FirstOrDefault(c => c.Name == sessionTokenKey);

            return(sessionCookie);
        }
        private void changeOrientaion()//?
        {
            var userCookie = Request.Headers.GetCookies("session").FirstOrDefault();

            // change to appliction
            CookieState vals = userCookie["session"];
            string      ID   = HttpContext.Current.Application[vals["username"]].ToString();

            m_Conn = new MySql.Data.MySqlClient.MySqlConnection(Database.Connect());

            m_Conn.Open(); // open connection

            m_QueryStr = "SELECT Path FROM gis.photodetails WHERE ID = '" + ID + "'";
            m_Cmd      = new MySql.Data.MySqlClient.MySqlCommand(m_QueryStr, m_Conn);

            Reader = m_Cmd.ExecuteReader();
            List <String> path = new List <String>();

            while (Reader.Read())
            {
                path.Add(Reader[0].ToString());
            }

            string localfilepath = HttpContext.Current.Server.MapPath(path[0]);

            m_Conn.Close();
            ImageResizer.ImageJob i = new ImageResizer.ImageJob(localfilepath, localfilepath, new ImageResizer.Instructions("width=3000;height=3000;format=jpg;mode=max;autorotate=true"));
            i.Build();
        }
Beispiel #9
0
        /// <summary>
        ///     Ensure the XSRF (Cross Site Request Forgery) cookie matches
        /// </summary>
        /// <param name="actionContext">
        ///     The <see cref="HttpActionContext" /> representing the current web operation.
        ///     This cannot be null.
        /// </param>
        /// <param name="authTicket">The decrypted contents of the ASPX authentication token. This cannot be null.</param>
        /// <param name="cookies">The cookies.</param>
        /// <returns>
        ///     True if the token is valid, false otherwise.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        ///     actionContext
        ///     or
        ///     authTicket
        /// </exception>
        /// <exception cref="ArgumentNullException">No argument can be null.</exception>
        public static bool VerifyXsrfToken(HttpActionContext actionContext, AuthenticationToken authTicket, Collection <CookieHeaderValue> cookies)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            if (authTicket == null)
            {
                throw new ArgumentNullException("authTicket");
            }

            if (cookies == null)
            {
                throw new ArgumentNullException("cookies");
            }

            bool result;

            CookieState xsrfTokenCookie = cookies.Select(c => c[LoginConstants.Cookie.AngularDefaultXsrfCookieName]).FirstOrDefault( );

            if (xsrfTokenCookie == null || string.IsNullOrEmpty(xsrfTokenCookie.Value))
            {
                result = false;
            }
            else
            {
                string xsrfTokenFromXsrfCookie     = xsrfTokenCookie.Value;
                string xsrfTokenFromAspxAuthCookie = authTicket.XsrfToken;
                string xsrfTokenFromRequestHeader  = null;
                try
                {
                    IEnumerable <string> tokens;

                    if (actionContext.Request.Headers.TryGetValues(LoginConstants.Headers.AngularJsXsrfToken, out tokens))
                    {
                        xsrfTokenFromRequestHeader = tokens.FirstOrDefault( );
                    }
                }
                catch (Exception)
                {
                    xsrfTokenFromRequestHeader = null;
                }
                string xsrfTokenFromQueryString = GetUriQueryParameter(actionContext, LoginConstants.QueryString.XsrfToken);

                string xsrfTokenSuppliedByClientSameOriginJsCode = xsrfTokenFromRequestHeader ?? xsrfTokenFromQueryString;

                //ensure tokens are supplied and they all match
                //common possibilities:
                // - missing XSRF_TOKEN cookie: client not authenticated or tampered cookie
                // - missing X-XSRF-TOKEN HTTP Header: client not authenticated, non-AngularJS request, potential failed XSRF attach due to Same-origin policy requirements not being met: http://en.wikipedia.org/wiki/Same-origin_policy
                // - XSRF_TOKEN cookie does NOT match X-XSRF-TOKEN HTTP Header: evident failed XSRF attach by trying to supply incorrect XSRF token
                result =
                    xsrfTokenFromAspxAuthCookie != null &&
                    xsrfTokenFromAspxAuthCookie == xsrfTokenFromXsrfCookie &&
                    xsrfTokenFromAspxAuthCookie == xsrfTokenSuppliedByClientSameOriginJsCode;
            }

            return(result);
        }
Beispiel #10
0
        public IState<string> CookieState(string cookieName, TimeSpan timeToLive, bool httpOnly, bool supportP3P)
        {
            var cookieState = new CookieState(ContextLocator, cookieName, timeToLive, httpOnly, supportP3P);

            // We also want a context item cache for the cookie value, so that it can be read on the same request context as when it was set
            var wrapper = new ContextItemStateWrapper<string>(ContextLocator, "cookieCache." + cookieName, cookieState);
            return wrapper;
        }
Beispiel #11
0
        public void parse_with_multiple_values()
        {
            var state = CookieState.Parse("key", "a=1");

            state.Name.ShouldEqual("key");
            state.Value.ShouldBeNull();

            state["a"].ShouldEqual("1");
        }
Beispiel #12
0
        protected override KeyValuePair <string, string> GetCookie(string key)
        {
            CookieState cookie = this._request.GetCookie(key);

            if (cookie == null)
            {
                return(new KeyValuePair <string, string>());
            }
            return(new KeyValuePair <string, string>(cookie.Name, cookie.Value));
        }
Beispiel #13
0
        public string ReadCookie(string key)
        {
            CookieHeaderValue cookie = Request.Headers.GetCookies(key).FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie[key];
                return(cookieState.Value);
            }
            return(null);
        }
Beispiel #14
0
        public void parse_with_multiple_values_2()
        {
            var state = CookieState.Parse("key", "a=1&b=2&c=3");

            state.Name.ShouldBe("key");
            state.Value.ShouldBeNull();

            state["a"].ShouldBe("1");
            state["b"].ShouldBe("2");
            state["c"].ShouldBe("3");
        }
        string GetSessionToken(HttpRequestMessage request)
        {
            const string sessionTokenkey = "X-Session-Token";
            Collection <CookieHeaderValue> cookieHeaderValues = request.Headers.GetCookies(sessionTokenkey);
            CookieState sessionCookie = cookieHeaderValues
                                        .Where(chv => chv.Expires == null || chv.Expires > DateTimeOffset.Now)
                                        .SelectMany(chv => chv.Cookies)
                                        .FirstOrDefault(c => c.Name == sessionTokenkey);
            string token = sessionCookie?.Value;

            return(string.IsNullOrEmpty(token) ? null : token);
        }
Beispiel #16
0
        public HttpResponseMessage GetImage(string imageName)
        {
            CookieHeaderValue cookie      = Request.Headers.GetCookies("DisplayResolution").FirstOrDefault();
            CookieState       cookieState = cookie["DisplayResolution"];

            int resolutionHeight = Convert.ToInt32(cookieState["DisplayResolutionHeight"]);
            int resolutionWidth  = Convert.ToInt32(cookieState["DisplayResolutionWidth"]);

            byte[] image = ImageService.GetImageByName(imageName, resolutionHeight, resolutionWidth);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new ByteArrayContent(image);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");

            return(response);
        }
Beispiel #17
0
        public IHttpActionResult GetValueCookie()
        {
            var      resp = new HttpResponseMessage();
            myCookie cook = new myCookie();

            CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["session"];
                cook.SessionId    = cookieState["sid"];
                cook.SessionToken = cookieState["token"];
                cook.Theme        = cookieState["theme"];
            }
            return(Ok(cook));
        }
Beispiel #18
0
        /// <summary>
        /// 的到web api 中的cookie
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public UserInfo GetCurrentUser(System.Net.Http.HttpRequestMessage Request)
        {
            UserInfo          userInfo = new UserInfo();
            CookieHeaderValue cookie   = Request.Headers.GetCookies("session").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["session"];
                var         password    = cookieState["password"];
                var         mobilePhone = cookieState["mobilePhone"];
                //得到用户的
                if (!string.IsNullOrEmpty(mobilePhone))
                {
                    userInfo = db.UserInfoes.Where(item => item.MobileTelphoneNumber.Equals(mobilePhone)).FirstOrDefault();
                }
            }
            return(userInfo);
        }
Beispiel #19
0
        public string TestRead()
        {
            string sessionId    = "";
            string sessionToken = "";
            string theme        = "";

            CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["session"];

                sessionId    = cookieState["user"];
                sessionToken = cookieState["username"];
                theme        = cookieState["id"];
            }
            return(sessionId + sessionToken + theme);
        }
        private static bool Validate(CookieState cookie, string token)
        {
            var cookieValue = cookie != null ? cookie.Value : null;

            try
            {
                AntiForgery.Validate(cookieValue, token);
            }
            catch (Exception ex)
            {
                ElmahExceptionLogger.DefaultLog(new Exception(
                                                    string.Format("Failed validation using cookie[{0}] and token[{1}]", cookieValue, token)
                                                    , ex));
                return(false);
            }

            return(true);
        }
Beispiel #21
0
 private static string GetCookieStateValue(this CookieState cs)
 {
     if (cs.Value != null)
     {
         return(cs.Value);
     }
     if (cs.Values != null && cs.Values.Count > 0)
     {
         var pairs = new List <string>();
         foreach (string key in cs.Values.Keys)
         {
             pairs.Add(key + "=" + cs.Values[key]);
         }
         return(string.Join(";", pairs));
     }
     else
     {
         return(cs.Value);
     }
 }
Beispiel #22
0
        string GetSessionToken(HttpRequestMessage request)
        {
            const string sessionCookieKey = "X-Session-Token";
            Collection <CookieHeaderValue> cookieHeaderValues = request.Headers.GetCookies(sessionCookieKey);
            //Cookie:key=value;key=value; key可以重复
            //Cookie:key=value;key=value; 可以有多个Cookie
            CookieState sessionCookie = cookieHeaderValues
//                .Where(chv => chv.Expires == null || chv.Expires > DateTimeOffset.Now)
                                        .SelectMany(chv => chv.Cookies)
                                        .FirstOrDefault(c => c.Name == sessionCookieKey);

            if (sessionCookie == null)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }
            string sessionCookieValue = sessionCookie.Value;

            if (string.IsNullOrEmpty(sessionCookieValue))
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }
            return(sessionCookieValue);
        }
        public void should_construct_structed_cookies()
        {
            // Warning: the structured cookie are not part of international
            // standard.

            var request = new HttpRequestMessage();

            request.Headers.Add("Cookie", new[] { "key1=subkey1=v1&subkey2=v2;key2=value2" });

            Collection <CookieHeaderValue> cookieHeaderValues = request.Headers.GetCookies();
            CookieHeaderValue        cookieHeaderValue        = cookieHeaderValues.Single();
            Collection <CookieState> cookieStates             = cookieHeaderValue.Cookies;

            Assert.Equal(2, cookieStates.Count);
            CookieHeaderValue chvWithKey1 = request.Headers.GetCookies("key1").Single();

            CookieState         cookieKey1   = chvWithKey1.Cookies.Single(c => c.Name.Equals("key1"));
            NameValueCollection subKeyValues = cookieKey1.Values;

            Assert.Equal(2, subKeyValues.Count);
            Assert.Equal("v1", subKeyValues["subkey1"]);
            Assert.Equal("v2", subKeyValues["subkey2"]);
        }
Beispiel #24
0
        public HttpResponseMessage Logout()
        {
            CookieHeaderValue   cookie   = Request.Headers.GetCookies("refreshTokenData").FirstOrDefault();
            HttpResponseMessage response = new HttpResponseMessage();
            ResponseFormat      responseData;
            string c_series = "";
            string t_series = "";

            if (cookie != null)
            {
                CookieState cookieState = cookie["refreshTokenData"];
                t_series = cookieState["tokenIdentifier"];
                var temp  = int.Parse(t_series);
                var token = db.REFRESH_TOKEN.Find(temp);
                if (token != null)
                {
                    db.REFRESH_TOKEN.Remove(token);
                    db.SaveChanges();
                }

                //cookie.Expires = DateTime.Now.AddDays(-10);
                //response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                response.Headers.Add("set-cookie", $"refreshTokenData=1; path=/; SameSite=None; Secure; max-age=-1");
                response.StatusCode = HttpStatusCode.OK;
                responseData        = ResponseFormat.Success;
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = "No cookie found";
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Beispiel #25
0
        /// <summary>
        ///     Indicates whether the specified control is authorized.
        /// </summary>
        /// <param name="actionContext">The context.</param>
        /// <returns>
        ///     true if the control is authorized; otherwise, false.
        /// </returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null || actionContext.Request == null)
            {
                // This is intentionally an ArgumentNullException instead of a WebArgumentNullException because
                // this should never be called with a null actionContext by ASP.NET WebAPI.
                throw new ArgumentNullException("actionContext");
            }

            //
            // Integration Test Authorization
            // if we are in integrated testing mode and a test token has been provided, use it. If it fails, pretend it never happened.
            // Otherwise perform a normal test.
            //
            if (TestAuthorization.IsEnabled)
            {
                var authorizationHeader = HttpContext.Current.Request.Headers.Get("Authorization");
                if (!string.IsNullOrEmpty(authorizationHeader))
                {
                    long   tenantId;
                    long   providerId;
                    string userName;
                    if (TestAuthorization.Instance.TryGetIdentifier(authorizationHeader, out tenantId, out providerId, out userName))
                    {
                        var testRequestContextData = Factory.IdentityProviderRequestContextCache.GetRequestContextData(tenantId, providerId, userName, false);
                        RequestContext.SetContext(testRequestContextData);
                        return(true);
                    }
                }
                // fall back to usual login
            }

            Collection <CookieHeaderValue> cookies = actionContext.Request.Headers.GetCookies( );

            //
            // Normal authorization
            //
            CookieState aspxAuthCookie = cookies.Select(c => c[FormsAuthentication.FormsCookieName]).FirstOrDefault( );

            if (aspxAuthCookie == null)
            {
                throw new InvalidCredentialException(AuthenticationCookieMissingMessage);
            }

            string ticketData = aspxAuthCookie.Value;

            if (string.IsNullOrEmpty(ticketData))
            {
                throw new InvalidCredentialException(AuthenticationCookieInvalidMessage);
            }

            FormsAuthenticationTicket authenticationTicket;

            try
            {
                authenticationTicket = FormsAuthentication.Decrypt(ticketData);
            }
            catch (Exception ex)
            {
                EventLog.Application.WriteError("Error decrypting authentication ticket. " + ex.Message);
                throw new InvalidCredentialException(UserAccountValidator.InvalidUserNameOrPasswordMessage, ex);
            }
            if (authenticationTicket == null)
            {
                throw new InvalidCredentialException(UserAccountValidator.InvalidUserNameOrPasswordMessage);
            }

            /////
            // Check whether the ticket has expired.
            /////
            if (authenticationTicket.Expired)
            {
                throw new AuthenticationTokenExpiredException( );
            }

            // Get the encrypted cookie payload
            AuthenticationToken authTicket;

            try
            {
                using (var input = new StringReader(authenticationTicket.UserData))
                {
                    authTicket = JSON.Deserialize <AuthenticationToken>(input);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidCredentialException(AuthenticationCookieInvalidMessage, ex);
            }
            if (authTicket == null)
            {
                throw new InvalidCredentialException(AuthenticationCookieInvalidMessage);
            }

            // Prevent XSRF attacks
            bool noXsrfCheck =
                actionContext.ActionDescriptor.GetCustomAttributes <NoXsrfCheckAttribute>( ).Count > 0 ||
                actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <NoXsrfCheckAttribute>( ).Count > 0;

            if (!noXsrfCheck &&
                !CookieHelper.VerifyXsrfToken(actionContext, authTicket, cookies))
            {
                EventLog.Application.WriteWarning($"Invalid XSRF token detected. Headers:\n{actionContext?.Request?.Headers}");
                throw new XsrfValidationException( );
            }

            RequestContextData requestContextData = Factory.IdentityProviderRequestContextCache.GetRequestContextData(authTicket.TenantId,
                                                                                                                      authTicket.IdentityProviderId, authTicket.IdentityProviderUserName, false);

            if (requestContextData == null)
            {
                throw new InvalidCredentialException(UserAccountValidator.InvalidUserNameOrPasswordMessage);
            }

            if (authTicket.UserAccountId != requestContextData.Identity.Id)
            {
                throw new InvalidCredentialException(UserAccountValidator.InvalidUserNameOrPasswordMessage);
            }

            RequestContext.SetContext(requestContextData);

            /////
            // Don't extend the cookie timeout for challenge requests for the native identity provider
            /////
            if (actionContext.Request.RequestUri.LocalPath.ToLowerInvariant() == ChallengeRequestUri &&
                authTicket.IdentityProviderId == WellKnownAliases.CurrentTenant.ReadiNowIdentityProviderInstance)
            {
                return(true);
            }

            /////
            // Sliding window expiry.
            // Note* If the Web page is accessed before half of the expiration time passes, the ticket expiration
            // time will not be reset. As per http://support.microsoft.com/kb/910443/en-gb
            /////
            if (DateTime.Now <= authenticationTicket.Expiration.AddMinutes(-(LoginConstants.Cookie.Timeout / 2)))
            {
                return(true);
            }

            /////
            // Do not require the caller to have access to the authentication entities e.g. Open ID provider.
            /////
            using (new SecurityBypassContext( ))
            {
                CookieHelper.CreateAuthenticationAndXsrfCookies(authTicket.TenantId, authTicket.IdentityProviderId, authTicket.IdentityProviderUserName, authTicket.UserAccountId, authTicket.Persist, authTicket.XsrfToken);
            }

            return(true);
        }
Beispiel #26
0
        public HttpResponseMessage Refresh()
        {
            string c_refreshToken        = "";
            string c_series              = "";
            string t_series              = "";
            HttpResponseMessage response = new HttpResponseMessage();
            ResponseFormat      responseData;

            CookieHeaderValue cookie = Request.Headers.GetCookies("refreshTokenData").FirstOrDefault();

            if (cookie != null)
            {
                CookieState cookieState = cookie["refreshTokenData"];
                c_refreshToken = cookieState["refreshToken"];
                c_series       = cookieState["seriesIdentifier"];
                t_series       = cookieState["tokenIdentifier"];
                var dbUser = db.USERs.Find(int.Parse(c_series));

                if (dbUser != null)
                {
                    //look for token
                    var temp = int.Parse(t_series);
                    //var a = WebUtility.UrlDecode(c_refreshToken);
                    var a       = Base64UrlEncoder.Decode(c_refreshToken);
                    var dbToken = dbUser.REFRESH_TOKEN.Where(c => c.ID == temp).FirstOrDefault();
                    if (dbToken != null)
                    {
                        if (c_refreshToken == dbToken.Token)
                        {
                            var user = AutoMapper.Mapper.Map <User>(dbUser);
                            //grab a new jwt token
                            var JwtToken = JwtTokenManager.GenerateJwtToken(user);
                            //grab a new refresh token
                            var RefreshToken = JwtTokenManager.GenerateRefreshToken();
                            //store new value for token
                            dbToken.Token = RefreshToken;
                            db.SaveChanges();
                            //response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={dbToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");
                            response.Headers.Add("set-cookie", $"refreshTokenData=refreshToken={RefreshToken}&seriesIdentifier={dbUser.ID}&tokenIdentifier={dbToken.ID}; path=/; SameSite=None; Secure; max-age=2592000");
                            //build response data
                            responseData = ResponseFormat.Success;

                            if (dbUser.Avatar != null)
                            {
                                responseData.data = new
                                {
                                    user = new
                                    {
                                        id        = user.ID,
                                        username  = user.Username,
                                        firstName = user.FirstName,
                                        lastName  = user.LastName,
                                        jwt       = JwtToken,
                                        group     = dbUser.GROUP.ID,
                                        avatar    = $"{StaticStrings.ServerHost}avatar?fileName={dbUser.Avatar}"
                                    }
                                };
                            }
                            else
                            {
                                responseData.data = new
                                {
                                    user = new
                                    {
                                        id        = user.ID,
                                        username  = user.Username,
                                        firstName = user.FirstName,
                                        lastName  = user.LastName,
                                        jwt       = JwtToken,
                                        group     = dbUser.GROUP.ID,
                                        avatar    = ""
                                    }
                                };
                            }

                            response.StatusCode = HttpStatusCode.OK;
                        }
                        else
                        {
                            response.StatusCode  = HttpStatusCode.Unauthorized;
                            responseData         = ResponseFormat.Fail;
                            responseData.message = "Cookie Invalid";
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = "Cookie Invalid";
                    }
                }
                else
                {
                    response.StatusCode  = HttpStatusCode.NotFound;
                    responseData         = ResponseFormat.Fail;
                    responseData.message = "Not a valid user";
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = "No cookie found";
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }
Beispiel #27
0
        private static bool ParseCookieSegment(CookieHeaderValue instance, string segment)
        {
            var nameValueSeparator = new char[] { '=' };

            if (string.IsNullOrWhiteSpace(segment))
            {
                return(true);
            }
            string[] nameValuePair = segment.Split(nameValueSeparator, 2);
            if ((nameValuePair.Length < 1) || string.IsNullOrWhiteSpace(nameValuePair[0]))
            {
                return(false);
            }
            string a = nameValuePair[0].Trim();

            if (string.Equals(a, "expires", StringComparison.OrdinalIgnoreCase))
            {
                DateTimeOffset offset;
                if (TryParseDate(GetSegmentValue(nameValuePair, null), out offset))
                {
                    instance.Expires = new DateTimeOffset?(offset);
                    return(true);
                }
                return(false);
            }
            if (string.Equals(a, "max-age", StringComparison.OrdinalIgnoreCase))
            {
                int num;
                if (TryParseInt32(GetSegmentValue(nameValuePair, null), out num))
                {
                    instance.MaxAge = new TimeSpan(0, 0, num);
                    return(true);
                }
                return(false);
            }
            if (string.Equals(a, "domain", StringComparison.OrdinalIgnoreCase))
            {
                instance.Domain = GetSegmentValue(nameValuePair, null);
                return(true);
            }
            if (string.Equals(a, "path", StringComparison.OrdinalIgnoreCase))
            {
                instance.Path = GetSegmentValue(nameValuePair, "/");
                return(true);
            }
            if (string.Equals(a, "secure", StringComparison.OrdinalIgnoreCase))
            {
                if (!string.IsNullOrWhiteSpace(GetSegmentValue(nameValuePair, null)))
                {
                    return(false);
                }
                instance.Secure = true;
                return(true);
            }
            if (string.Equals(a, "httponly", StringComparison.OrdinalIgnoreCase))
            {
                if (!string.IsNullOrWhiteSpace(GetSegmentValue(nameValuePair, null)))
                {
                    return(false);
                }
                instance.HttpOnly = true;
                return(true);
            }
            string segmentValue = GetSegmentValue(nameValuePair, null);

            try
            {
                NameValueCollection values = new FormDataCollection(segmentValue).ReadAsNameValueCollection();
                CookieState         item   = new CookieState(a, values);
                instance.Cookies.Add(item);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #28
0
        private void roundtrips(string name, string text)
        {
            var state = CookieState.Parse(name, text);

            state.ToString().ShouldEqual(name + "=" + text);
        }