コード例 #1
0
        public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
        {
            if (model.Exception != null)
                throw model.Exception;

            var client = model.AuthenticatedClient;
            var username = client.UserInformation.UserName;

            FormsAuthentication.SetAuthCookie(username, false);

            context.Response.AppendCookie(new HttpCookie("AccessToken", client.AccessToken.SecretToken)
            {
                Secure = !context.IsDebuggingEnabled,
                HttpOnly = true
            });

            var urlHelper = new UrlHelper(((MvcHandler)context.Handler).RequestContext);
            var redirectUrl = string.Format("/{0}/", username);
            var cookie = context.Request.Cookies["returnUrl"];
            if (cookie != null && urlHelper.IsLocalUrl(cookie.Value))
            {
                redirectUrl = cookie.Value;
                cookie.Expires = DateTime.Now.AddDays(-1);
                context.Response.Cookies.Add(cookie);
            }

            return new RedirectResult(redirectUrl);
        }
コード例 #2
0
        public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
        {
            if (model.Exception != null) {
                throw model.Exception;
            }

            var authInfo = model.AuthenticatedClient;
            var userInfo = authInfo.UserInformation;
            var returnUrl = RouteHelper.GetReturnUrl(model.ReturnUrl);

            var user = bus.Query(new UserViaProvider(authInfo.ProviderName, userInfo.Id));
            if(user != null) {
                state.Login(user, true);

                if(state.RegistrationStatus == RegistrationStatus.NotRegistered) {
                    return RedirectToAction("Registration", "Create");
                }

                return !string.IsNullOrEmpty(returnUrl)
                    ? new RedirectResult(returnUrl)
                    : RedirectToAction("Account");
            }

            if(!string.IsNullOrEmpty(userInfo.Email)) {
                user = bus.Query(new UserWithEmail(userInfo.Email));

                if(user != null) {
                    user.AddOAuthAccount(authInfo.ProviderName, userInfo.Id);

                    state.Login(user, true);

                    if(state.RegistrationStatus == RegistrationStatus.NotRegistered) {
                        return RedirectToAction("Registration", "Create");
                    }

                    return !string.IsNullOrEmpty(returnUrl)
                        ? new RedirectResult(returnUrl)
                        : RedirectToAction("Account");
                }
            }

            return new ViewResult {
                ViewName = "~/Views/Account/Create.cshtml",
                ViewData = new ViewDataDictionary(new CreateAccountViewModel {
                    Email = userInfo.Email,
                    Username = userInfo.UserName,
                    ReturnUrl = model.ReturnUrl,
                    ExternalLoginData = securityEncoder.SerializeOAuthProviderUserId(authInfo.ProviderName, userInfo.Id),
                    Persist = true,
                    ProviderDisplayName = authInfo.ProviderName
                })
            };
        }
 public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
 {
     return new ViewResult
     {
         ViewName = "AuthenticateCallback",
         ViewData = new ViewDataDictionary(new AuthenticateCallbackViewModel
         {
             AuthenticatedClient = model.AuthenticatedClient,
             Exception = model.Exception,
             ReturnUrl = model.ReturnUrl
         })
     };
 }
        public ActionResult AuthenticateCallback(AuthenticateCallBackInputModel inputModel)
        {
            #region Input Model Validation

            if (!ModelState.IsValid)
            {
                throw new ArgumentException(
                    "Some binding errors occured. This means at least one Request value (eg. form post or querystring parameter) provided is invalid. Generally, we need a ProviderName as a string.");
            }

            if (string.IsNullOrEmpty(inputModel.ProviderKey))
            {
                throw new ArgumentException(
                    "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. providerkey=google.");
            }

            #endregion

            var previousRedirectUrl = string.IsNullOrEmpty(_cache[SessionKeyRedirectToProviderUrl])
                                          ? "N.A."
                                          : _cache[SessionKeyRedirectToProviderUrl];
            TraceSource.TraceInformation("Previous Redirect Url: " + previousRedirectUrl);

            #region Deserialize Tokens, etc.

            // Retrieve any (previously) serialized access token stuff. (eg. public/private keys and state).
            // TODO: Check if this is an access token or an auth token thingy-thing.
            TraceSource.TraceVerbose("Retrieving (local serializaed) AccessToken, State and RedirectToUrl.");
            var state = _cache[SessionKeyState];
            var redirectToUrl = _cache[SessionKeyReturnToUrl];

            #endregion

            // Lets now start to setup the view model.
            var model = new AuthenticateCallbackData();

            #region Retrieve the User Information

            try
            {
                // Which provider did we just authenticate with?
                var provider = GetAuthenticationProvider(inputModel.ProviderKey);
                model.ProviderName = provider.Name;

                // Where do we return to, after we've authenticated?
                var callbackUri = GenerateCallbackUri(provider.Name, _configurationOptions?.BasePath);

                // Grab the user information.
                model.AuthenticatedClient = provider.AuthenticateClient(Request.QueryString, state, callbackUri);
            }
            catch (Exception exception)
            {
                TraceSource.TraceError(exception.Message);
                model.Exception = exception;
            }

            #endregion

            // Do we have an optional redirect resource? Usually a previous referer?
            if (redirectToUrl != null)
            {
                TraceSource.TraceVerbose("Found redirectToUrl: " + redirectToUrl);
                model.ReturnUrl = redirectToUrl;
            }

            // Finally! We can hand over the logic to the consumer to do whatever they want.
            TraceSource.TraceVerbose("About to execute your custom callback provider logic.");
            return _callbackProvider.Process(HttpContext, model);
        }
コード例 #5
0
        public ActionResult AuthenticateCallback(AuthenticateCallBackInputModel inputModel)
        {
            #region Input Model Validation

            if (!ModelState.IsValid)
            {
                throw new ArgumentException(
                          "Some binding errors occured. This means at least one Request value (eg. form post or querystring parameter) provided is invalid. Generally, we need a ProviderName as a string.");
            }

            if (string.IsNullOrEmpty(inputModel.ProviderKey))
            {
                throw new ArgumentException(
                          "ProviderKey value missing. You need to supply a valid provider key so we know where to redirect the user Eg. providerkey=google.");
            }

            #endregion

            var previousRedirectUrl = string.IsNullOrEmpty((string)Session[SessionKeyRedirectToProviderUrl])
                                          ? "N.A."
                                          : (string)Session[SessionKeyRedirectToProviderUrl];
            TraceSource.TraceInformation("Previous Redirect Url: " + previousRedirectUrl);

            #region Deserialize Tokens, etc.

            // Retrieve any (previously) serialized access token stuff. (eg. public/private keys and state).
            // TODO: Check if this is an access token or an auth token thingy-thing.
            TraceSource.TraceVerbose("Retrieving (local serializaed) AccessToken, State and RedirectToUrl.");
            var state         = Session[SessionKeyState] as string;
            var redirectToUrl = Session[SessionKeyReturnToUrl] as string;

            #endregion

            // Lets now start to setup the view model.
            var model = new AuthenticateCallbackData();

            #region Retrieve the User Information

            try
            {
                // Which provider did we just authenticate with?
                var provider = GetAuthenticationProvider(inputModel.ProviderKey);

                // Where do we return to, after we've authenticated?
                var callbackUri = GenerateCallbackUri(provider.Name);

                // Grab the user information.
                model.AuthenticatedClient = provider.AuthenticateClient(Request.QueryString, state, callbackUri);
            }
            catch (Exception exception)
            {
                TraceSource.TraceError(exception.Message);
                model.Exception = exception;
            }

            #endregion

            // Do we have an optional redirect resource? Usually a previous referer?
            if (redirectToUrl != null)
            {
                TraceSource.TraceVerbose("Found redirectToUrl: " + redirectToUrl);
                model.ReturnUrl = redirectToUrl;
            }

            // Finally! We can hand over the logic to the consumer to do whatever they want.
            TraceSource.TraceVerbose("About to execute your custom callback provider logic.");
            return(_callbackProvider.Process(HttpContext, model));
        }
コード例 #6
0
        public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
        {
            using (var db = new UsersContext())
            {
                var userId = WebSecurity.GetUserId(HttpContext.Current.User.Identity.Name);
                var user = db.UserProfiles.First(u => u.UserId == userId);
                user.BasecampCredentials = user.BasecampCredentials ?? new BasecampCredentials();
                user.BasecampCredentials.AccessToken = model.AuthenticatedClient.AccessToken.PublicToken;
                user.BasecampCredentials.RefreshToken = model.AuthenticatedClient.AccessToken.SecretToken;

                db.SaveChanges();
            }

            var route = new RouteValueDictionary()
            {
                {"action", "Manage"},
                {"controller", "Account"}
            };
            return new RedirectToRouteResult(route);
            return new ContentResult
            {
                Content = model.AuthenticatedClient.UserInformation.Name
            };
            return new ViewResult
            {
                ViewName = "Home",
                ViewData = new ViewDataDictionary(new AuthenticateCallbackViewModel
                {
                    AuthenticatedClient = model.AuthenticatedClient,
                    Exception = model.Exception,
                    ReturnUrl = model.ReturnUrl
                })
            };
        }