Exemplo n.º 1
0
        async Task <bool> ValidateToken(string token, string nonce)
        {
            var x509Str = await GetSigningCertAsync();

            var cert       = new X509Certificate2(Convert.FromBase64String(x509Str));
            var parameters = new TokenValidationParameters
            {
                ValidAudience = _urls.ClientId,
                ValidIssuers  = new List <string> {
                    _urls.BaseIdSrvUrl, "https://parcelfor.me", "https://dev.parcelfor.me"
                },
                IssuerSigningToken = new X509SecurityToken(cert)
            };

            SecurityToken jwt;
            var           principal = new JwtSecurityTokenHandler().ValidateToken(token, parameters, out jwt);

            // validate nonce
            var nonceClaim = principal.FindFirst("nonce");

            P4MHelpers.RemoveCookie(Response, "p4mNonce");
            if (!string.Equals(nonceClaim.Value, nonce, StringComparison.Ordinal))
            {
                throw new Exception("invalid nonce");
            }
            return(true);
        }
Exemplo n.º 2
0
        public ActionResult GetAccessToken()
        {
            // state should be validated here - get from cookie
            string stateFromCookie, nonceFromCookie;
            var    state = Request.Params.GetValues("state").FirstOrDefault();

            GetTempState(out stateFromCookie, out nonceFromCookie);
            P4MHelpers.RemoveCookie(Response, "p4mState");
            if (state.Equals(stateFromCookie, StringComparison.Ordinal))
            {
                var token        = Request.Params.GetValues("access_token").FirstOrDefault();
                var expiresInStr = Request.Params.GetValues("expires_in").FirstOrDefault();
                int expiresIn    = 0;
                int.TryParse(expiresInStr, out expiresIn);
                var expires = DateTime.UtcNow.AddSeconds(expiresIn);
                Response.Cookies["p4mToken"].Value = token;
                //Response.Cookies["p4mToken"].Expires = expires; only expire this when the browser is closed
                Response.Cookies["p4mTokenExpires"].Value = expires.ToString("s") + "Z";
                //Response.Cookies["p4mTokenExpires"].Expires = expires; only expire this when the browser is closed
                Response.Cookies["p4mHasAccount"].Value   = "Y";
                Response.Cookies["p4mHasAccount"].Expires = DateTime.UtcNow.AddYears(1);
                return(View("~/Views/P4M/ClosePopup.cshtml"));
            }
            // error occurred so try to recover
            Logoff(Response);
            return(View("~/Views/P4M/ClosePopupAndRefresh.cshtml"));
        }
Exemplo n.º 3
0
        public async Task <ActionResult> SignUp()
        {
            // if the user is logged in the we can save their details before redirecting to the SignUp controller
            var result = new LoginMessage();

            try
            {
                var authUser = AuthenticationManager.User;
                if (authUser == null || !authUser.Identity.IsAuthenticated)
                {
                    result.RedirectUrl = _urls.BaseIdSrvUiUrl + "signup";
                }
                else
                {
                    // user is logged in so we can send details to P4M
                    var clientToken = await P4MHelpers.GetClientTokenAsync();

                    // now create a consumer from the local user details
                    var consumer = await GetConsumerFromAppUserAsync(authUser.Identity.GetUserId());

                    // we can also save their most recent cart
                    var cart = GetMostRecentCart(authUser.Identity.GetUserName());
                    // ready to send
                    _httpClient.SetBearerToken(clientToken.AccessToken);
                    _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var registerMessage = new ConsumerAndCartMessage {
                        Consumer = consumer, Cart = cart
                    };
                    var content   = new ObjectContent <ConsumerAndCartMessage>(registerMessage, new JsonMediaTypeFormatter());
                    var apiResult = await _httpClient.PostAsync(_urls.BaseApiAddress + "registerConsumer", content);

                    // check the result
                    apiResult.EnsureSuccessStatusCode();
                    var messageString = await apiResult.Content.ReadAsStringAsync();

                    var registerResult = JsonConvert.DeserializeObject <ConsumerIdMessage>(messageString);
                    result.RedirectUrl = registerResult.RedirectUrl;
                }
            }
            catch (Exception e)
            {
                result.Error = e.Message;
                return(View("Error"));
            }
            return(Redirect(result.RedirectUrl));
        }
Exemplo n.º 4
0
        //private string ParsedJwt(string token)
        //{
        //    if (!token.Contains("."))
        //    {
        //        return token;
        //    }

        //    var parts = token.Split('.');
        //    var part = Encoding.UTF8.GetString(Base64Url.Decode(parts[1]));

        //    var jwt = JObject.Parse(part);
        //    return jwt.ToString();
        //}

        public static void Logoff(HttpResponseBase response)
        {
            // clear the local P4M cookies
            P4MHelpers.RemoveCookie(response, "p4mToken");
            P4MHelpers.RemoveCookie(response, "p4mTokenExpires");
            P4MHelpers.RemoveCookie(response, "p4mAvatarUrl");
            P4MHelpers.RemoveCookie(response, "p4mGivenName");
            P4MHelpers.RemoveCookie(response, "p4mLocalLogin");
            P4MHelpers.RemoveCookie(response, "p4mState");
            P4MHelpers.RemoveCookie(response, "p4mNonce");
            P4MHelpers.RemoveCookie(response, "p4mOfferCartRestore");
            P4MHelpers.RemoveCookie(response, "p4mLocale");
            P4MHelpers.RemoveCookie(response, "p4mConsumer");
            P4MHelpers.RemoveCookie(response, "p4mPrefAddress");
            P4MHelpers.RemoveCookie(response, "p4mCart");
            P4MHelpers.RemoveCookie(response, "p4mCartAddress");
            P4MHelpers.RemoveCookie(response, "gfsCheckoutToken");
        }
Exemplo n.º 5
0
        async Task <bool> GetGuestTokenAsync()
        {
            // consumer is unknown so if we're in exclusive mode we need a guest token to access the P4M API
            var clientToken = await P4MHelpers.GetClientTokenAsync();

            _httpClient.SetBearerToken(clientToken.AccessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var locale = Request.Cookies["p4mLocale"].Value;
            var result = await _httpClient.GetAsync($"{_p4mConsts.BaseApiAddress}guestAccessToken/{locale}");

            var messageString = await result.Content.ReadAsStringAsync();

            var message = JsonConvert.DeserializeObject <TokenMessage>(messageString);

            if (message.Success)
            {
                Response.Cookies["p4mToken"].Value = message.Token;
                //Response.Cookies["p4mTokenType"].Value = "Guest";
            }
            return(message.Success);
        }
Exemplo n.º 6
0
        public async Task <ActionResult> CheckEmail(string email, string name)
        {
            // this is triggered in guest mode when a consumer enters their email address
            // this endpoint should be loaded in a popup window
            // first we check with P4M for their status:
            // - if known and confirmed, unknown, we close the popup immediately and continue as guest
            // - if known but not confirmed we redirect them to the sign up server to ask them to confirm their email
            try
            {
                var clientToken = await P4MHelpers.GetClientTokenAsync();

                // ready to check
                _httpClient.SetBearerToken(clientToken.AccessToken);
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var apiResult = await _httpClient.GetAsync($"{_urls.BaseIdSrvUrl}/consumerStatus/{email}");

                // check the result
                apiResult.EnsureSuccessStatusCode();
                var messageString = await apiResult.Content.ReadAsStringAsync();

                var statusResult = JsonConvert.DeserializeObject <ConsumerStatusMessage>(messageString);
                if (!statusResult.Success)
                {
                    throw new Exception(statusResult.Error);
                }
                if (statusResult.IsGuest)
                {
                    var host = Uri.EscapeDataString("http://localhost:3000/");
                    return(Redirect($"{_urls.BaseIdSrvUiUrl}confirmGuest?id={statusResult.UserId}&email={email}&name={name}&host={host}"));
                }
                else
                {
                    return(View("~/Views/P4M/ClosePopup.cshtml"));
                }
            }
            catch (Exception e)
            {
                return(View("Error"));
            }
        }