Esempio n. 1
0
        public ActionResult LogOn()
        {
            var openid   = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:

                    var command = Mapper.Map <string, EnsureUserCommand>(response.ClaimedIdentifier.OriginalString);
                    command.Execute();

                    FormsAuthentication.RedirectFromLoginPage(
                        response.ClaimedIdentifier.OriginalString, false);
                    break;

                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("OpenIdIdentifier",
                                             "Login was cancelled at the provider");
                    break;

                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("OpenIdIdentifier",
                                             "Login failed using the provided OpenID identifier");
                    break;
                }
            }

            return(View());
        }
        public ActionResult LogOnCallback(string returnUrl)
        {
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response == null)
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "No authentication response" }));
            }

            if (response.Status != AuthenticationStatus.Authenticated)
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Response status is not Authenticated" }));
            }

            var fetch = response.GetExtension <FetchResponse>();

            if (fetch == null)
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "No fetch response" }));
            }

            string email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);

            if (string.IsNullOrWhiteSpace(email))
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Response Email is empty" }));
            }


            if (!email.EndsWith(EmailSuffix))
            {
                return(RedirectToAction("Error", new { returnUrl = returnUrl, error = "Only emails ended with " + EmailSuffix + " are allowed" }));
            }

            var username = email.Substring(0, email.Length - EmailSuffix.Length);

            FormsAuthentication.SetAuthCookie(username, true);

            Session[SessionRolesKey] = new string[0];
            var user = RavenSession.Query <User>().Where(u => u.UserName == username).FirstOrDefault();

            log.Debug("User {0} found: {1}", username, user != null);

            if (user != null)
            {
                log.Dump(LogLevel.Debug, user, "RavenDB User");
                Session[SessionRolesKey] = user.Roles ?? new string[0];
            }

            if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return(Redirect(returnUrl));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
Esempio n. 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Utilities.CheckForValidSteamSession(Request.Cookies["AccessToken"]))
            {
                var openid   = new OpenIdRelyingParty();
                var response = openid.GetResponse();

                if (response != null)
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:

                        string responseURI = response.ClaimedIdentifier.ToString();

                        CreateOrRefreshSession CreateSession = new CreateOrRefreshSession();
                        CreateSession.SteamId        = responseURI.Substring(responseURI.LastIndexOf("/") + 1);
                        CreateSession.ServerPassword = Utilities.ServerPassword;

                        string     TokenWrapper = Utilities.MakePOSTRequest(Utilities.ServerDNS + "/CreateSession", CreateSession);
                        JObject    JObject      = JObject.Parse(TokenWrapper);
                        string     Token        = JObject["CreateSessionResult"].ToString();
                        HttpCookie myCookie     = new HttpCookie("AccessToken");
                        myCookie.Values.Add("AccessToken", Token);
                        myCookie.Expires = DateTime.Now.AddHours(12);
                        Response.Cookies.Add(myCookie);

                        string     SteamUserData  = SteamAPI.GetData(CreateSession.SteamId);
                        HttpCookie UserDataCookie = new HttpCookie("SteamUserData");
                        UserDataCookie.Values.Add("SteamUserData", SteamUserData);
                        UserDataCookie.Expires = DateTime.Now.AddHours(12);
                        Response.Cookies.Add(UserDataCookie);
                        SteamLoginButton.Visible = false;
                        PleaseLoginText.Visible  = false;
                        MyDecksButton.Visible    = false;
                        Response.Redirect("Default", false);

                        break;

                    case AuthenticationStatus.Canceled:
                    case AuthenticationStatus.Failed:
                    {
                        Response.Redirect("Default", false);
                    }
                    break;
                    }
                }
                else
                {
                    CreateDeckButton.CssClass = "btn btn-success mainbtn disabled";
                    MyDecksButton.CssClass    = "btn btn-primary mainbtn disabled";
                }
            }
            else
            {
                SteamLoginButton.Visible = false;
                PleaseLoginText.Visible  = false;
                MyDecksButton.Visible    = true;
            }
        }
        private void HandleYahooResponse()
        {
            using (var openid = new OpenIdRelyingParty())
            {
                var response = openid.GetResponse();
                switch (response.Status)
                {
                // If user was authenticated
                case AuthenticationStatus.Authenticated:
                    // This is where you would look for any OpenID extension responses included
                    // in the authentication assertion.
                    var fetchResponse = response.GetExtension <FetchResponse>();

                    string firstName = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First);
                    string lastName  = fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last);
                    string email     = fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "N/A";

                    AuthenticatedUser(firstName, lastName, email, email, "Yahoo");

                    break;

                // User has cancelled the OpenID Dance
                case AuthenticationStatus.Canceled:

                    break;

                // Authentication failed
                case AuthenticationStatus.Failed:

                    break;
                }
            }
        }
        public ActionResult SteamLogin()
        {
            //Steam authentication code gotten from: https://stackoverflow.com/questions/20845146/steam-login-authentication-c-sharp
            var openid   = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    // do success
                    var responseURI = response.ClaimedIdentifier.ToString();
                    Session["SteamID"] = responseURI.Split('/').Last();
                    //"http://steamcommunity.com/openid/id/76561197969877387"
                    // last part is steam user id
                    return(RedirectToAction("Friends"));

                case AuthenticationStatus.Canceled:
                case AuthenticationStatus.Failed:
                    // do fail
                    break;
                }
            }
            else
            {
                using (OpenIdRelyingParty openidd = new OpenIdRelyingParty())
                {
                    IAuthenticationRequest request = openidd.CreateRequest("http://steamcommunity.com/openid");
                    request.RedirectToProvider();
                }
            }

            return(View());
        }
        /// <summary>
        /// Authenicates a user based on the information in the HTTP request.
        /// </summary>
        /// <returns></returns>
        public override GraywulfPrincipal Authenticate()
        {
            // Get OpenID provider's response from the http context
            using (var openid = new OpenIdRelyingParty())
            {
                var response = openid.GetResponse();

                // TODO: figure out which OpenID provider sent the response
                // and associate with the right authenticator

                if (response != null)
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        return(CreatePrincipal(response));

                    case AuthenticationStatus.Canceled:
                    case AuthenticationStatus.Failed:
                        throw new System.Security.Authentication.AuthenticationException("OpenID authentication failed.", response.Exception);

                    case AuthenticationStatus.ExtensionsOnly:
                    case AuthenticationStatus.SetupRequired:
                        throw new InvalidOperationException();

                    default:
                        throw new NotImplementedException();
                    }
                }

                return(null);
            }
        }
Esempio n. 7
0
        public ActionResult LogOn()
        {
            var openid = new OpenIdRelyingParty();
            IAuthenticationResponse response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var user = _userRepo.FindUserByClaimedIdentifier(response.ClaimedIdentifier);
                    if (null == user)
                    {
                        user = CreateUserFromOpenIDResponse(response);
                    }
                    FormsAuthentication.RedirectFromLoginPage(user.FriendlyIdentifier, false);
                    break;

                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("loginIdentifier",
                                             "Login was cancelled at the provider");
                    break;

                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("loginIdentifier",
                                             "Login failed using the provided OpenID identifier");
                    break;
                }
            }

            return(View());
        }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var openId   = new OpenIdRelyingParty();
            var response = openId.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    StatusLabel.Text = $"Вы авторизованы под пользователем c ID {response.ClaimedIdentifier.ToString()}";
                    break;

                case AuthenticationStatus.Canceled:
                    StatusLabel.Text = $"Авторизация не удалась";
                    break;

                case AuthenticationStatus.Failed:
                    StatusLabel.Text = $"Авторизация не удалась";
                    break;
                }
            }
            else
            {
                StatusLabel.Text = $"Вы не авторизованы";
            }
        }
Esempio n. 9
0
        public string GetOpenIDResponse()
        {
            var result   = string.Empty;
            var openid   = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    result = StringToGUID(response.ClaimedIdentifier.ToString()).ToString();
                    break;

                case AuthenticationStatus.Canceled:
                    result = "Canceled at Provider";
                    break;

                case AuthenticationStatus.Failed:
                    result = response.Exception.Message;
                    break;
                }
            }

            return(result);
        }
Esempio n. 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OpenIdRelyingParty openid = this.createRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    //Here is where we get the data that comes back due to the use of our OpenID+OAuth extension.
                    //We save it into state for later use.
                    var oAuthOpenID = response.GetExtension <OAuthResponse>();
                    if (oAuthOpenID == null)
                    {
                        throw new Exception("There was a problem with the OpenID+OAuth Extension. A likely problem may be that your application's " +
                                            "realm registered with developer.myspace.com does not have a closing slash (e.g. http://localhost:9090/ is needed " +
                                            "rather than http://localhost:9090).");
                    }
                    var verifier = Request.QueryString["openid.oauth.verifier"];
                    Session["varifier"]          = verifier;
                    Session["OAuthRequestToken"] = Request.QueryString["openid.oauth.request_token"];
                    break;

                case AuthenticationStatus.Canceled:
                    break;

                case AuthenticationStatus.Failed:
                    break;
                }
            }
        }
Esempio n. 11
0
        public ActionResult Login()
        {
            var openid = new OpenIdRelyingParty();
            IAuthenticationResponse response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var user = EnsureUserExists(response);
                    FormsAuthentication.RedirectFromLoginPage(
                        user.email, false);
                    break;

                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("loginIdentifier",
                                             "Login was cancelled at the provider");
                    break;

                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("loginIdentifier",
                                             "Login failed using the provided OpenID identifier");
                    break;
                }
            }

            return(View());
        }
Esempio n. 12
0
        public ActionResult Authenticate(string returnUrl)
        {
            var rp       = new OpenIdRelyingParty();
            var response = rp.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    // Make sure we have a user account for this guy.
                    string identifier = response.ClaimedIdentifier;                             // convert to string so LinqToSQL expression parsing works.
                    if (MvcApplication.DataContext.Users.FirstOrDefault(u => u.OpenIDClaimedIdentifier == identifier) == null)
                    {
                        MvcApplication.DataContext.Users.InsertOnSubmit(new User {
                            OpenIDFriendlyIdentifier = response.FriendlyIdentifierForDisplay,
                            OpenIDClaimedIdentifier  = response.ClaimedIdentifier,
                        });
                    }

                    FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                    return(this.Redirect(returnUrl ?? Url.Action("Index", "Home")));

                default:
                    ModelState.AddModelError(string.Empty, "An error occurred during login.");
                    break;
                }
            }

            return(this.View("LogOn"));
        }
Esempio n. 13
0
        /// <summary>
        /// Check if authentication succeeded after user is redirected back from the service provider.
        /// </summary>
        /// <param name="context">
        /// The context of the current request.
        /// </param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult"/> containing authentication result.
        /// </returns>
        public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context)
        {
            IAuthenticationResponse response = RelyingParty.GetResponse();

            if (response == null)
            {
                throw new InvalidOperationException(WebResources.OpenIDFailedToGetResponse);
            }

            if (response.Status == AuthenticationStatus.Authenticated)
            {
                string id = response.ClaimedIdentifier;
                string username;

                Dictionary <string, string> extraData = this.GetExtraData(response) ?? new Dictionary <string, string>();

                // try to look up username from the 'username' or 'email' property. If not found, fall back to 'friendly id'
                if (!extraData.TryGetValue("username", out username) && !extraData.TryGetValue("email", out username))
                {
                    username = response.FriendlyIdentifierForDisplay;
                }

                return(new AuthenticationResult(true, this.ProviderName, id, username, extraData));
            }

            return(AuthenticationResult.Failed);
        }
Esempio n. 14
0
    protected void HandleOpneIdProviderResponse()
    {
        OpenIdRelyingParty rp = new OpenIdRelyingParty();

        var response = rp.GetResponse();

        if (response != null)
        {
            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:

                Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
                var fetchResponse = response.GetExtension <FetchResponse>();
                Session["FetchResponse"] = fetchResponse;

                var response2 = Session["FetchResponse"] as FetchResponse;

                GetUserDetails(response2);
                break;

            case AuthenticationStatus.Canceled:
                Session["GoogleIdentifier"] = "Cancelled.";
                break;

            case AuthenticationStatus.Failed:
                Session["GoogleIdentifier"] = "Login Failed.";
                break;
            }
        }
    }
Esempio n. 15
0
        private static BaseAuthenticationInfo LocateOpenIdResponse()
        {
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var claimsResponse        = response.GetExtension <ClaimsResponse>();
                    var openIdAuthInformation = new OpenIdAuthenticationInfo();
                    openIdAuthInformation.Identifier = response.ClaimedIdentifier;
                    if (claimsResponse != null)
                    {
                        openIdAuthInformation.Email     = claimsResponse.Email;
                        openIdAuthInformation.FirstName = claimsResponse.FullName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).First();
                        if (claimsResponse.FullName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Count() > 1)
                        {
                            openIdAuthInformation.LastName = claimsResponse.FullName.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
                        }
                        openIdAuthInformation.UserName = claimsResponse.Nickname;
                    }

                    var providerName = OpenIdProviderEndPoints.GetOpenIdProviderName(response.Provider.Uri);
                    openIdAuthInformation.Provider = providerModule.GetProvider(providerName);

                    return(openIdAuthInformation);
                }
            }
            return(null);
        }
Esempio n. 16
0
        /// <summary>
        /// Action Results for Index, uses DotNetOpenAuth for creating OpenId Request with Intuit
        /// and handling response recieved.
        /// </summary>
        /// <returns></returns>
        public RedirectResult Index()
        {
            var openid_identifier = ConfigurationManager.AppSettings["openid_identifier"].ToString();;
            var response          = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    try
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openid_identifier);
                        FetchRequest           fetch   = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email));
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName));
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                    }
                    catch (ProtocolException ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                if (response.FriendlyIdentifierForDisplay == null)
                {
                    Response.Redirect("/OpenId");
                }

                // Stage 3: OpenID Provider sending assertion response, storing the response in Session object is only for demonstration purpose
                Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                FetchResponse fetch = response.GetExtension <FetchResponse>();
                if (fetch != null)
                {
                    Session["OpenIdResponse"] = "True";
                    Session["FriendlyEmail"]  = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); // emailAddresses.Count > 0 ? emailAddresses[0] : null;
                    Session["FriendlyName"]   = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); //fullNames.Count > 0 ? fullNames[0] : null;

                    //get the Oauth Access token for the user from OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.GetOauthAccessTokenForUser(Session["FriendlyEmail"].ToString(), this);
                }
            }

            string query = Request.Url.Query;

            if (!string.IsNullOrWhiteSpace(query) && query.ToLower().Contains("disconnect=true"))
            {
                Session["accessToken"]       = "dummyAccessToken";
                Session["accessTokenSecret"] = "dummyAccessTokenSecret";
                Session["Flag"] = true;
                return(Redirect("/CleanupOnDisconnect/Index"));
            }

            return(Redirect("/Home/index"));
        }
Esempio n. 17
0
        internal static string SignIn(Guid userDetailsPageId)
        {
            string errorMessage = string.Empty;

            using (var openid = new OpenIdRelyingParty())
            {
                //fix wrong URI, add PathInfo
                HttpContext.Current.RewritePath(HttpContext.Current.Request.RawUrl);
                IAuthenticationResponse response = openid.GetResponse();
                if (response == null)
                {
                    //request
                    string openIDIdentifier = HttpContext.Current.Request.Form["openid_identifier"];

                    if (!string.IsNullOrEmpty(openIDIdentifier))
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openIDIdentifier);
                        var claims = new ClaimsRequest();
                        claims.Email    = DemandLevel.Require;
                        claims.Nickname = DemandLevel.Require;
                        claims.FullName = DemandLevel.Require;
                        claims.Country  = DemandLevel.Require;
                        request.AddExtension(claims);

                        //small fix for request.RedirectToProvider();
                        string location = request.RedirectingResponse.Headers["Location"];
                        HttpContext.Current.Response.Redirect(location, false);
                    }
                }
                else
                {
                    //response
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        HandleSuccessfulSignIn(response, userDetailsPageId);
                        break;

                    case AuthenticationStatus.Canceled:
                        errorMessage = "Login was cancelled at the provider.";
                        break;

                    case AuthenticationStatus.Failed:
                        errorMessage = "Login failed at the provider.";
                        break;

                    case AuthenticationStatus.SetupRequired:
                        errorMessage = "The provider requires setup.";
                        break;

                    default:
                        errorMessage = "Login failed.";
                        break;
                    }
                }
            }
            return(errorMessage);
        }
Esempio n. 18
0
        public ActionResult LoginOpenId(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            var response = Openid.GetResponse();

            ActionResult loginOpenId;

            if (UserSubmittingIdentifier(response, out loginOpenId))
            {
                return(loginOpenId);
            }

            // Stage 3: OpenID Provider sending assertion response
            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:
                var username = response.FriendlyIdentifierForDisplay;
                Session["FriendlyIdentifier"] = username;

                //Check OpenID user exists on DB
                if (_accountBusinessLogic.ValidateOpendIdUser(username, TenantManager.CurrentTenancy))
                {
                    //login it with selected user
                    this.SignIn(username, false, TenantManager.CurrentTenancy);

                    ActionResult redirectToRoute;
                    if (this.LoginPostValidations(out redirectToRoute))
                    {
                        return(redirectToRoute);
                    }
                }
                else     //register user with more data about him first time he login with opendid
                {
                    ActionResult registerOpenIdAction;
                    bool         isSuperAdminTenancy;
                    return(this.CheckSuperAdminTenancy(out registerOpenIdAction, out isSuperAdminTenancy)
                            ? registerOpenIdAction
                            : this.RedirectToAction("RegisterOpenId", "Account"));
                }

                return(this.RedirectAfterLogin(returnUrl));

            case AuthenticationStatus.Canceled:
                this.ViewData["Message"]      = "Canceled at provider";
                Session["FriendlyIdentifier"] = null;
                Session["Invitation"]         = null;
                return(this.View("Login"));

            case AuthenticationStatus.Failed:
                Session["FriendlyIdentifier"] = null;
                Session["Invitation"]         = null;
                this.ViewData["Message"]      = response.Exception.Message;
                return(this.View("Login"));
            }

            return(new EmptyResult());
        }
Esempio n. 19
0
        public ActionResult Authenticate(string returnUrl)
        {
            var response = OpenId.GetResponse();

            if (response == null)
            {
                Identifier identifier;

                if (Identifier.TryParse(Request.Form["openid_identifier"], out identifier))
                {
                    try
                    {
                        var request = OpenId.CreateRequest(identifier);
                        return(request.RedirectingResponse.AsActionResultMvc5());
                    }
                    catch (ProtocolException protocolException)
                    {
                        TempData["Flash"] = protocolException.Message;
                        return(RedirectToAction("SignIn"));
                    }
                }

                TempData["Flash"] = "Invalid identifier.";
                return(RedirectToAction("SignIn"));
            }

            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:
                // Find user with claimed identifier. If null, redirect to /users/new
                var user = _userRepository.GetByClaimedIdentifier(response.ClaimedIdentifier);

                if (user == null)
                {
                    Session.Add("ClaimedIdentifier", response.ClaimedIdentifier);
                    return(RedirectToAction("New"));
                }

                FormsAuthentication.SetAuthCookie(user.Id.ToString(), true);

                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return(Redirect(returnUrl));
                }

                return(RedirectToAction("Index", "Home"));

            case AuthenticationStatus.Canceled:
                TempData["Flash"] = "Canceled at provider.";
                return(RedirectToAction("SignIn"));

            case AuthenticationStatus.Failed:
                TempData["Flash"] = response.Exception.Message;
                return(RedirectToAction("SignIn"));
            }

            return(HttpNotFound());
        }
Esempio n. 20
0
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier

                return(oAuthRequest());
                //} else {
                //    ViewData["Message"] = "Invalid identifier";
                //    return View("Login");
                //}
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                    string username = Session["FriendlyIdentifier"].ToString().Split('/')[2];
                    Session["username"] = username;     //parsed out from server and path (i.e. //server/user/johnsmi)
                    Ticker.Data.User user = new Ticker.Data.FoxTickerEntities().Users.FirstOrDefault(u => u.Username == username);
                    FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                    Session["UserID"] = user.UserID;

                    if ((bool)user.Inactive)
                    {
                        System.Web.Security.FormsAuthentication.SignOut();
                        return(RedirectToAction("Index", "Home"));
                    }
                    else if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    break;

                case AuthenticationStatus.Canceled:
                    //ViewData["Message"] = "Canceled at provider";
                    //return View("Login");
                    return(oAuthRequest());

                case AuthenticationStatus.Failed:
                    //ViewData["Message"] = response.Exception.Message;
                    //return View("Login");
                    return(oAuthRequest());
                }
            }
            return(new EmptyResult());
        }
Esempio n. 21
0
        public LogInResult GetUser()
        {
            LogInResult             logInResult    = new LogInResult();
            IAuthenticationResponse openIdResponse = openId.GetResponse();

            if (openIdResponse.IsSuccessful())
            {
                logInResult = ResponseIntoUser(openIdResponse);
            }
            return(logInResult);
        }
Esempio n. 22
0
        public IAuthResult GetResult(IAuthProviderDefinition def)
        {
            if (!(def is OpenIdProvider))
            {
                return(null);
            }

            var r = _openid.GetResponse(HttpContext.Request);

            return(r == null || r.Status != AuthenticationStatus.Authenticated ? null : new OpenIdAuthResult(r));
        }
Esempio n. 23
0
        private void CheckGoogleOpenID()
        {
            try
            {
                var openid   = new OpenIdRelyingParty();
                var response = openid.GetResponse();

                if (response != null)
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:

                        var id = GlobalUtil.StringToGUID(response.ClaimedIdentifier.ToString());
                        if (id == Guid.Empty)
                        {
                            lblErrMessage.Text = CommonMessages.ERROR_INVALID_GOOGLE_IDENTIFIER;
                            return;
                        }
                        var fetch = response.GetExtension <FetchResponse>();
                        if (fetch != null)
                        {
                            LogInUser(fetch.GetAttributeValue(WellKnownAttributes.Contact.Email), id);
                        }
                        else
                        {
                            lblErrMessage.Text = CommonMessages.ERROR_GOOGLE_ACCOUNT_NOT_FOUND;
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                        lblErrMessage.Text = CommonMessages.MSG_GOOGLE_AUTHENTICATION_CANCELED;
                        break;

                    case AuthenticationStatus.Failed:
                        lblErrMessage.Text = CommonMessages.MSG_GOOGLE_AUTHENTICATION_FAILED;
                        break;
                    }
                }
                else
                {
                    var request = openid.CreateRequest(System.Configuration.ConfigurationManager.AppSettings["GoogleOpenIDPath"].ToString(), new DotNetOpenAuth.OpenId.Realm(System.Configuration.ConfigurationManager.AppSettings["Domain"].ToString()));
                    var fetch   = new FetchRequest();
                    fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                    request.Mode = DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate;
                    request.AddExtension(fetch);
                    request.RedirectToProvider();
                }
            }
            catch (Exception ex)
            {
                lblErrMessage.Text = (new GlobalErrorLogsBLL()).LogGlobalError(ex, "TMS - LogIn - CheckGoogleOpenID");
            }
        }
Esempio n. 24
0
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try {
                        IAuthenticationRequest req = BuildOpenIdRequest(Request.Form["openid_identifier"]);

                        return(req.RedirectingResponse.AsActionResult());
                    } catch (ProtocolException ex) {
                        ViewData["Message"] = ex.Message;
                        return(View("Login"));
                    }
                }
                else
                {
                    ViewData["Message"] = "Invalid identifier";
                    return(View("Login"));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:

                    ConsumeOpenIdResponse(response);

                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }

                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return(View("Login"));

                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return(View("Login"));
                }
            }
            return(new EmptyResult());
        }
Esempio n. 25
0
        //
        // Get: /Authentication/Login/openid
        public ActionResult Authenticate()
        {
            using (var relayingParty = new OpenIdRelyingParty())
            {
                var response = relayingParty.GetResponse();

                if (response == null)
                {
                    // Stage 2: user submitting Identifier
                    var openId = Request.Form["openId"];
                    relayingParty.CreateRequest(openId).RedirectToProvider();

                    throw new Exception("Never gets here");
                }

                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var claimedIdentifier = response.ClaimedIdentifier;
                    var user = Users.FindByOpenId(claimedIdentifier);
                    if (user != null)
                    {
                        // login
                        return(RedirectFromLoginPage(user));
                    }

                    // register
                    var username = response.FriendlyIdentifierForDisplay;
                    user = new User
                    {
                        Name       = username,
                        OpenId     = claimedIdentifier,
                        Reputation = 1,
                        SignupDate = DateTime.Now
                    };
                    Users.Save(user);
                    return(RedirectFromLoginPage(user));

                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    // todo
                    return(View("Login"));

                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    // todo
                    return(View("Login"));

                default:
                    throw new Exception("Unknown status");
                }
            }
        }
Esempio n. 26
0
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();

            if (response == null)
            {
                Identifier id;
                if (Identifier.TryParse(Request.Form[OpenIDTextBox], out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(Request.Form[OpenIDTextBox]);
                        return(request.RedirectingResponse.AsActionResult());
                    }
                    catch (ProtocolException)
                    {
                        ShowMessage((L)"Error using remote login. Use local credentials or try again later.", HtmlMessageType.Warning);
                        return(View("login", new LocalLoginModel()));
                    }
                }

                ShowMessage((L)"Invalid identifier.", HtmlMessageType.Error);
                return(View("login", new LocalLoginModel()));
            }

            //Let us check the response
            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:
                if (RemoteAuthProvider.Authenticate(response.ClaimedIdentifier, false))
                {
                    UserContext = DependencyResolver.Current.GetService <UserContext>();
                    return(AfterSuccessfulLogin(new LocalLoginModel
                    {
                        Username = response.ClaimedIdentifier
                    }));
                }
                else
                {
                    TempData["OpenID"] = response.ClaimedIdentifier;
                    return(RedirectToAction("register"));
                }

            case AuthenticationStatus.Canceled:
                ShowMessage((L)"Login request was canceled.", HtmlMessageType.Warning);
                return(View("login", new LocalLoginModel()));

            case AuthenticationStatus.Failed:
                ShowMessage((L)"Login request failed.", HtmlMessageType.Warning);
                return(View("login", new LocalLoginModel()));
            }

            return(new EmptyResult());
        }
Esempio n. 27
0
        public string GetEmail()
        {
            string email = "";

            try
            {
                OpenIdRelyingParty rp = new OpenIdRelyingParty();
                string             sessionid;
                if (Session[SessionKeys.Identifier] != null)
                {
                    sessionid = Convert.ToString(Session[SessionKeys.Identifier]);
                }
                var r = rp.GetResponse();

                if (r != null)
                {
                    switch (r.Status)
                    {
                    case AuthenticationStatus.Authenticated:

                        // this works for Yahoo and google
                        var    fetch     = r.GetExtension <FetchResponse>();
                        var    response2 = fetch as FetchResponse;
                        string fullName;
                        email     = response2.GetAttributeValue(WellKnownAttributes.Contact.Email);
                        FirstName = response2.GetAttributeValue(WellKnownAttributes.Name.First);
                        LastName  = response2.GetAttributeValue(WellKnownAttributes.Name.Last);
                        fullName  = response2.GetAttributeValue(WellKnownAttributes.Name.FullName);

                        if (fullName != null)
                        {
                            string[] name = fullName.Split(' ');
                            FirstName = name[0];
                            LastName  = name[1];
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                        lblAlertMsg.Text = "Cancelled.";
                        break;

                    case AuthenticationStatus.Failed:
                        lblAlertMsg.Text = "Login Failed.";
                        break;
                    }
                }
                Session.Remove(SessionKeys.ServiceProvider);
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
            return(email);
        }
        private static readonly OpenIdRelyingParty s_relyingParty = new OpenIdRelyingParty(); //thread-safe

        public ActionResult Index()
        {
            var response = s_relyingParty.GetResponse();

            if (response == null) //Stage 1 - user unauthenticated => redirect to Steam Login page
            {
                return(CreateOpenIdRedirectingResponse());
            }

            //Stage 2 - user completed authentication => redirect back to HLTBS
            return(CreateHltbsRedirectionResponse(response));
        }
Esempio n. 29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.openIdBox.Focus();

            // For debugging/testing, we allow remote clearing of all associations...
            // NOT a good idea on a production site.
            if (Request.QueryString["clearAssociations"] == "1")
            {
                Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore");

                // Force a redirect now to prevent the user from logging in while associations
                // are constantly being cleared.
                UriBuilder builder = new UriBuilder(Request.Url);
                builder.Query = null;
                Response.Redirect(builder.Uri.AbsoluteUri);
            }

            OpenIdRelyingParty openid = this.createRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    // This is where you would look for any OpenID extension responses included
                    // in the authentication assertion.
                    var claimsResponse = response.GetExtension <ClaimsResponse>();
                    State.ProfileFields = claimsResponse;

                    // Store off the "friendly" username to display -- NOT for username lookup
                    State.FriendlyLoginName = response.FriendlyIdentifierForDisplay;

                    // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
                    // with the OpenID Claimed Identifier as their username.
                    FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
                    break;

                case AuthenticationStatus.Canceled:
                    this.loginCanceledLabel.Visible = true;
                    break;

                case AuthenticationStatus.Failed:
                    this.loginFailedLabel.Visible = true;
                    break;

                    // We don't need to handle SetupRequired because we're not setting
                    // IAuthenticationRequest.Mode to immediate mode.
                    ////case AuthenticationStatus.SetupRequired:
                    ////    break;
                }
            }
        }
        public OpenIdUser GetUser()
        {
            OpenIdUser user = null;
            IAuthenticationResponse openIdResponse = openId.GetResponse();

            if (openIdResponse.IsSuccessful())
            {
                user = ResponseIntoUser(openIdResponse);
            }

            return(user);
        }