public string CreateRequest(string userSuppliedIdentifier, string realm, string returnToUrl)
        {
            OpenIdRelyingParty rp       = new OpenIdRelyingParty(null);
            UserAgentResponse  response = rp.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl)).RedirectingResponse;

            return(response.DirectUriRequest.AbsoluteUri);
        }
        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());
        }
Esempio n. 3
0
        protected void loginButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return; // don't login if custom validation failed.
            }
            try
            {
                using (OpenIdRelyingParty openid = this.createRelyingParty())
                {
                    IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text);
                    // Here is where we add the OpenID+OAuth Extension
                    request.AddExtension(new OAuthRequest(Constants.ConsumerKey));

                    // Send your visitor to their Provider for authentication.
                    request.RedirectToProvider();
                }
            }
            catch (ProtocolException ex)
            {
                // The user probably entered an Identifier that
                // was not a valid OpenID endpoint.
                this.openidValidator.Text    = ex.Message;
                this.openidValidator.IsValid = false;
            }
            catch (WebException ex)
            {
                // The user probably entered an Identifier that
                // was not a valid OpenID endpoint.
                this.openidValidator.Text    = ex.Message;
                this.openidValidator.IsValid = false;
            }
        }
        public string CreateRequest(string userSuppliedIdentifier, string realm, string returnToUrl)
        {
            OpenIdRelyingParty rp       = new OpenIdRelyingParty(null, null, null);
            Response           response = (Response)rp.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl)).RedirectingResponse;

            return(response.IndirectMessageAsRequestUri.AbsoluteUri);
        }
Esempio n. 5
0
        protected void beginButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return;                 // don't login if custom validation failed.
            }
            try {
                using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) {
                    var request = rp.CreateRequest(this.openIdBox.Text);
                    request.IsExtensionOnly = true;

                    // This is where you would add any OpenID extensions you wanted
                    // to include in the request.
                    request.AddExtension(new ClaimsRequest {
                        Email      = DemandLevel.Request,
                        Country    = DemandLevel.Request,
                        Gender     = DemandLevel.Require,
                        PostalCode = DemandLevel.Require,
                        TimeZone   = DemandLevel.Require,
                    });

                    request.RedirectToProvider();
                }
            } catch (ProtocolException ex) {
                // The user probably entered an Identifier that
                // was not a valid OpenID endpoint.
                this.openidValidator.Text    = ex.Message;
                this.openidValidator.IsValid = false;
            }
        }
Esempio n. 6
0
        public ActionResult LogOn(string loginIdentifier)
        {
            if (!Identifier.IsValid(loginIdentifier))
            {
                ModelState.AddModelError("loginIdentifier",
                                         "The specified login identifier is invalid");
                return(View());
            }
            else
            {
                var openid = new OpenIdRelyingParty();
                IAuthenticationRequest request = openid.CreateRequest(
                    Identifier.Parse(loginIdentifier));

                // Require some additional data
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetch.Attributes.AddOptional(WellKnownAttributes.Name.Alias);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                request.AddExtension(fetch);

                var returnUrl = Request.QueryString["returnUrl"] != null
                                    ? Request.QueryString["returnUrl"]
                                    : Url.Action("Index", "Home");
                request.AddCallbackArguments("returnUrl", returnUrl);

                return(request.RedirectingResponse.AsActionResult());
            }
        }
Esempio n. 7
0
        public ActionResult OpenIdLogin(string openidIdentifier)
        {
            if (!Identifier.IsValid(openidIdentifier))
            {
                ModelState.AddModelError("loginIdentifier",
                                         "The specified login identifier is invalid");

                return(View("LogOn"));
            }
            else
            {
                var openid = new OpenIdRelyingParty();
                IAuthenticationRequest request = openid.CreateRequest(
                    Identifier.Parse(openidIdentifier));

                // Require some additional data
                request.AddExtension(new ClaimsRequest
                {
                    Email    = DemandLevel.Require,
                    FullName = DemandLevel.Request
                });

                return(request.RedirectingResponse.AsActionResult());
            }
        }
Esempio n. 8
0
    protected void loginButton_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;                        // don't login if custom validation failed.
        }
        OpenIdRelyingParty openid = createRelyingParty();

        try {
            IAuthenticationRequest request = openid.CreateRequest(openIdBox.Text);
            // This is where you would add any OpenID extensions you wanted
            // to include in the authentication request.
            // request.AddExtension(someExtensionRequestInstance);

            // Send your visitor to their Provider for authentication.
            request.RedirectToProvider();
        } catch (OpenIdException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            openidValidator.Text    = ex.Message;
            openidValidator.IsValid = false;
        } catch (WebException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            openidValidator.Text    = ex.Message;
            openidValidator.IsValid = false;
        }
    }
Esempio n. 9
0
        protected void PerformGoogleAuthentication()
        {
            using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
            {
                //Set up the callback URL
                Uri callbackUrl = new Uri(
                    String.Format("{0}{1}{2}{3}?{4}=true",
                                  (Request.IsSecureConnection) ? "https://" : "http://",
                                  Request.Url.Host,
                                  (Request.Url.IsDefaultPort) ?
                                  String.Empty : String.Concat(":", Request.Url.Port),
                                  Page.ResolveUrl(AUTHENTICATION_ENDPOINT),
                                  CALLBACK_PARAMETER
                                  ));

                //Set up request object for Google Authentication
                IAuthenticationRequest request =
                    openid.CreateRequest(GOOGLE_OAUTH_ENDPOINT,
                                         DotNetOpenAuth.OpenId.Realm.AutoDetect, callbackUrl);


                //Let's tell Google, what we want to have from the user:
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                request.AddExtension(fetch);

                //Redirect to Google Authentication
                request.RedirectToProvider();
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Make the request to the OpenID provider.
        /// </summary>
        /// <param name="openid_identifier">Identifier to send the request to.</param>
        /// <returns></returns>
        private ActionResult SendRequestToOpenIdProvider(string identifier)
        {
            Identifier id;

            if (Identifier.TryParse(identifier, out id))
            {
                try
                {
                    IAuthenticationRequest request = openId.CreateRequest(Identifier.Parse(identifier));

                    // Next we have to specify which data we want
                    request.AddExtension(new ClaimsRequest
                    {
                        Email    = DemandLevel.Require,
                        Nickname = DemandLevel.Require,
                        FullName = DemandLevel.Request
                    });

                    // Finally we'll make a request to the OpenID provider
                    return(request.RedirectingResponse.AsActionResult());
                }
                catch (ProtocolException e)
                {
                    ModelState.AddModelError("openid_identifier", e);
                }
            }
            else
            {
                ModelState.AddModelError("openid_identifier", "Invalid identifier");
            }

            return(View());
        }
Esempio n. 11
0
 private void CreateOpenIDRequestAndRedirect(string openIdUrl)
 {
     try
     {
         using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
         {
             IAuthenticationRequest request = openid.CreateRequest(openIdUrl);
             // This is where you would add any OpenID extensions you wanted
             // to include in the authentication request.
             request.AddExtension(new ClaimsRequest
             {
                 //Country = DemandLevel.Request,
                 //Email = DemandLevel.Request,
                 //Gender = DemandLevel.Require,
                 //PostalCode = DemandLevel.Require,
                 //TimeZone = DemandLevel.Require,
             });                          // Send your visitor to their Provider for authentication.
             request.RedirectToProvider();
         }
     }
     catch (ProtocolException ex)
     {
         // The user probably entered an Identifier that
         // was not a valid OpenID endpoint.
         this.openidValidator.Text    = ex.Message;
         this.openidValidator.IsValid = false;
     }
 }
Esempio n. 12
0
        private IAuthenticationRequest GetGoogleRequest()
        {
            // Google requires that the realm and consumer key be equal,
            // so we constrain the realm to match the realm in the web.config file.
            // This does mean that the return_to URL must also fall under the key,
            // which means this sample will only work on a public web site
            // that is properly registered with Google.
            // We will customize the realm to use http or https based on what the
            // return_to URL will be (which will be this page).
            Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + Global.GoogleTokenManager.ConsumerKey + "/";
            IAuthenticationRequest authReq = relyingParty.CreateRequest(GoogleOPIdentifier, realm);

            // Prepare the OAuth extension
            string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Contacts);

            Global.GoogleWebConsumer.AttachAuthorizationRequest(authReq, scope);

            // We also want the user's email address
            var fetch = new FetchRequest();

            fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            authReq.AddExtension(fetch);

            return(authReq);
        }
Esempio n. 13
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            Identifier id;

            if (!Identifier.TryParse(model.OpenIdProvider, out id))
            {
                ModelState.AddModelError("OpenId", "Invalid Open Id");
                return(View(model));
            }

            try
            {
                var authRequest = openid.CreateRequest(id);

                authRequest.AddCallbackArguments("rememberMe", model.RememberMe.ToString());

                OpenIdUserData.AddClaimsRequest(authRequest);

                return(authRequest.RedirectingResponse.AsActionResultMvc5());
            }
            catch (ProtocolException ex)
            {
                ModelState.AddModelError("err", ex.Message);
                return(View(model));
            }
        }
Esempio n. 14
0
        public ActionResult OpenID(string openid_identifier)
        {
            var openid = new OpenIdRelyingParty();
            IAuthenticationRequest request = openid.CreateRequest(Identifier.Parse(openid_identifier));

            return(request.RedirectingResponse.AsActionResult());
        }
Esempio n. 15
0
        public IAuthenticationRequest CreateRequest(string realmUrl, string returnUrl)
        {
            if (!Uri.IsWellFormedUriString(realmUrl, UriKind.Relative))
            {
                throw new ArgumentException("Value is not a well formed relative uri string", "realmUrl");
            }

            if (!Uri.IsWellFormedUriString(returnUrl, UriKind.Relative))
            {
                throw new ArgumentException("Value is not a well formed relative uri string", "returnUrl");
            }

            IAuthenticationRequest request;

            var baseUri = new Uri(_request.Url, "/");

            var realmUri = new Uri(baseUri, realmUrl);

            var returnToUri = new Uri(baseUri, returnUrl);

            using (var openIdRelyingParty = new OpenIdRelyingParty())
            {
                request = openIdRelyingParty.CreateRequest(Identifier.Parse("https://www.google.com/accounts/o8/id"), new Realm(realmUri), returnToUri);
            }

            request.AddExtension(new ClaimsRequest
            {
                Email = DemandLevel.Require
            });

            return(request);
        }
        private ActionResult RedirectToSteamOpenID(string login, string referer, OpenIdRelyingParty openid)
        {
            IAuthenticationRequest request = null;
            int tries = 3;

            while (request == null && tries > 0)
            {
                try
                {
                    tries--;
                    request = openid.CreateRequest(Identifier.Parse("https://steamcommunity.com/openid/"));
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Steam openid CreateRequest has failed: {0}", ex);
                }
            }
            if (request == null)
            {
                return(Content("Steam OpenID service is offline, cannot authorize, please try again later."));
            }
            if (!string.IsNullOrEmpty(referer))
            {
                request.SetCallbackArgument("referer", referer);
            }
            return(request.RedirectingResponse.AsActionResultMvc5());
        }
Esempio n. 17
0
    protected void cmdLoginOpenId_Click(object sender, EventArgs e)
    {
        try {
            using (OpenIdRelyingParty openid = new OpenIdRelyingParty()) {
                var realm     = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + "/";
                var return_to = Request.Url.StripQueryArgumentsWithPrefix("auto-redirect-openid");

                if (!string.IsNullOrEmpty(txtReferrer.Value) && !return_to.Query.Contains("referrer"))
                {
                    return_to = new Uri(return_to.ToString() + (string.IsNullOrEmpty(return_to.Query) ? "?" : "&") + "referrer=" + HttpUtility.UrlEncode(txtReferrer.Value));
                }

                IAuthenticationRequest request = openid.CreateRequest(Configuration.OpenIdProvider, realm, return_to);

                var fetch = new FetchRequest();
                fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                request.AddExtension(fetch);

                // Send your visitor to their Provider for authentication.
                request.RedirectToProvider();
            }
        } catch (ProtocolException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            lblMessage.Text = Utils.FormatException(ex);
        }
    }
Esempio n. 18
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. 19
0
        protected void add_Click(object sender, System.EventArgs e)
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            // validate base entries Captcha and Comment
            Page.Validate("Base");
            bool baseValid = Page.IsValid;

            // check the openid controls
            Page.Validate("OpenId");
            bool openIdValid = Page.IsValid;

            // check the classic controls Name and Email
            Page.Validate("Classic");
            bool classicValid = Page.IsValid;

            if (baseValid && openIdValid)
            {
                if (String.IsNullOrEmpty(openid_identifier.Text) == false && openid_identifier.Text != "Click to Sign In")
                {
                    Session["pendingComment"] = comment.Text;
                    Session["pendingEntryId"] = ViewState["entryId"].ToString().ToUpper();
                    OpenIdRelyingParty openid = new OpenIdRelyingParty();
                    try
                    {
                        IAuthenticationRequest req         = openid.CreateRequest(openid_identifier.Text);
                        ClaimsRequest          sregRequest = new ClaimsRequest();
                        sregRequest.Email    = DemandLevel.Require;
                        sregRequest.Nickname = DemandLevel.Require;
                        sregRequest.FullName = DemandLevel.Request;
                        req.AddExtension(sregRequest);

                        // Also add AX request explicitly so we can request first and last name individually.
                        FetchRequest axRequest = new FetchRequest();
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        req.AddExtension(axRequest);

                        SaveCookies();
                        req.RedirectToProvider();
                        return;
                    }
                    catch (UriFormatException ue) //They've entered something that's not a URI!
                    {
                        requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, "ERROR: " + openid_identifier.Text + " is not a valid URL. " + ue.Message, ""));
                    }
                }
            }

            if (baseValid && classicValid)
            {
                //Why isn't Page.Validate("Normal") working? It returns false. Hm.
                if (!String.IsNullOrEmpty(name.Text.Trim()))
                {
                    SaveCookies();
                    AddNewComment(name.Text, email.Text, homepage.Text, comment.Text, ViewState["entryId"].ToString().ToUpper(), /* openid */ false);
                }
            }
        }
        public void Provider()
        {
            OpenIdRelyingParty     rp      = new OpenIdRelyingParty(null, null, null);
            Identifier             id      = TestSupport.GetMockIdentifier(TestSupport.Scenarios.AutoApproval, ProtocolVersion.V20);
            IAuthenticationRequest request = rp.CreateRequest(id, realm, returnTo);

            Assert.IsNotNull(request.Provider);
        }
Esempio n. 21
0
 protected void Authorize()
 {
     using (OpenIdRelyingParty openId = new OpenIdRelyingParty())
     {
         IAuthenticationRequest request = openId.CreateRequest("http://steamcommunity.com/openid");
         request.RedirectToProvider();
     }
 }
Esempio n. 22
0
 public void RedirectToProvider(string providerUri)
 {
     using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
     {
         var request = openid.CreateRequest(providerUri);
         request.RedirectToProvider();
     }
 }
Esempio n. 23
0
        public void Execute(AuthenticateInputModel inputModel)
        {
            var party = new OpenIdRelyingParty();

            var request = party.CreateRequest(inputModel.GetIdentifier());

            request.RedirectToProvider();
        }
Esempio n. 24
0
 protected void SteamLogin(object sender, EventArgs e)
 {
     using (OpenIdRelyingParty openidd = new OpenIdRelyingParty())
     {
         IAuthenticationRequest request = openidd.CreateRequest("http://steamcommunity.com/openid");
         request.RedirectToProvider();
     }
 }
Esempio n. 25
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. 26
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());
        }
        public virtual ActionResult OpenIdLogin(string openid_identifier)
        {
            bool rememberMe           = false;
            OpenIdRelyingParty openid = new OpenIdRelyingParty();

            // Stage 1: display login form to user
            if (openid.Response == null && Request.HttpMethod != "POST")
            {
                return(View("Login"));
            }
            else
            if (openid.Response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    openid.CreateRequest(openid_identifier).RedirectToProvider();
                }
                else
                {
                    ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.InvalidIdentifierSpecified);
                    ViewData["openid_identifier"] = openid_identifier;
                    return(View("Login"));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (openid.Response.Status)
                {
                case AuthenticationStatus.Authenticated:

                    // Associate openid identity to user account and login
                    var userName = AssociateOpenIdIdentityToUserName(openid.Response.ClaimedIdentifier);
                    if (string.IsNullOrEmpty(userName))
                    {
                        ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.AssociationFailure);
                        ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                        return(View("Login"));
                    }
                    FormsAuthentication.RedirectFromLoginPage(userName, rememberMe);
                    break;

                case AuthenticationStatus.Canceled:
                    ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.CanceledAtProvider);
                    ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                    return(View("Login"));

                case AuthenticationStatus.Failed:
                    ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.UnknownFailure + openid.Response.Exception.Message);
                    ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                    return(View("Login"));
                }
            }

            return(View("Login"));
        }
        private static ActionResult CreateOpenIdRedirectingResponse()
        {
            SiteEventSource.Log.CreateAuthenticationRequestStart();
            var authenticationRequest = s_relyingParty.CreateRequest(SteamOpenIdProviderIdentifier);

            SiteEventSource.Log.CreateAuthenticationRequestStop();

            return(authenticationRequest.RedirectingResponse.AsActionResultMvc5());
        }
Esempio n. 29
0
        public void UriTest()
        {
            OpenIdRelyingParty     rp       = TestSupport.CreateRelyingParty(null);
            Identifier             id       = MockHttpRequest.RegisterMockXrdsResponse("/Discovery/xrdsdiscovery/xrds20.xml");
            IAuthenticationRequest request  = rp.CreateRequest(id, TestSupport.Realm, TestSupport.ReturnTo);
            IProviderEndpoint      provider = request.Provider;

            Assert.AreEqual(new Uri("http://a/b"), provider.Uri);
        }
Esempio n. 30
0
        public ActionResult OpenId(LoginModel model)
        {
            Identifier id;

            if (Identifier.TryParse(model.OpenID_Identifier, out id))
            {
                try
                {
                    model.Config = _services.Config.Current;
                    var openId = new OpenIdRelyingParty();
                    returnToUrl = new Uri(Url.Action("OpenIdCallback", "Authentication", new { ReturnUrl = model.ReturnUrl }, Request.Url.Scheme), UriKind.Absolute);
                    // hack for google oauth2
                    if (model.OpenID_Identifier.Contains("google"))
                    {
                        client = new GoogleOAuth2Client(model.Config.ClientId, model.Config.ClientSecret);
                        client.RequestAuthentication(this.HttpContext, returnToUrl);
                        GoogleOAuth2Client.RewriteRequest();
                        return(Redirect(returnToUrl.ToString()));
                    }
                    else
                    {
                        var request = openId.CreateRequest(id, Realm.AutoDetect, returnToUrl);

                        // add request for name and email using sreg (OpenID Simple Registration
                        // Extension)
                        request.AddExtension(new ClaimsRequest
                        {
                            Email    = DemandLevel.Require,
                            FullName = DemandLevel.Require,
                            Nickname = DemandLevel.Require
                        });

                        // also add AX request
                        var axRequest = new FetchRequest();
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        request.AddExtension(axRequest);

                        var redirectingResponse = request.RedirectingResponse;

                        return(redirectingResponse.AsActionResult());
                    }
                }
                catch (ProtocolException ex)
                {
                    model.Message = ex.Message;
                    return(View("Login", model));
                }
            }
            else
            {
                model.Message = "Invalid identifier";
                return(View("Login", model));
            }
        }