Ejemplo n.º 1
0
        public async Task UnsolicitedAssertion()
        {
            var opStore = new MemoryCryptoKeyAndNonceStore();

            Handle(RPUri).By(
                async req => {
                var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
                IAuthenticationResponse response = await rp.GetResponseAsync(req);
                Assert.That(response, Is.Not.Null);
                Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status);
                return(new HttpResponseMessage());
            });
            Handle(OPUri).By(
                async(req, ct) => {
                var op = new OpenIdProvider(opStore, this.HostFactories);
                return(await this.AutoProviderActionAsync(op, req, ct));
            });
            this.RegisterMockRPDiscovery(ssl: false);

            {
                var        op        = new OpenIdProvider(opStore, this.HostFactories);
                Identifier id        = GetMockIdentifier(ProtocolVersion.V20);
                var        assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]);

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Authenticate(string returnUrl)
        {
            var rp       = new OpenIdRelyingParty();
            var response = await rp.GetResponseAsync(Request);

            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"));
        }
Ejemplo n.º 3
0
        public async Task <ActionResult> OpenIdCallback(string returnUrl)
        {
            var model = new LoginModel {
                ReturnUrl = returnUrl
            };
            var openId             = new OpenIdRelyingParty();
            var openIdResponseTask = openId.GetResponseAsync();

            await openIdResponseTask;

            var openIdResponse = openIdResponseTask.Result;

            if (openIdResponse.Status == AuthenticationStatus.Authenticated)
            {
                var friendlyName = GetFriendlyName(openIdResponse);

                var isPersistentCookie = true;
                SetAuthCookie(openIdResponse.ClaimedIdentifier, isPersistentCookie, friendlyName);

                return(Redirect(returnUrl.AsNullIfEmpty() ?? Url.Action("Index", "Home")));
            }

            model.Message = "Sorry, login failed.";
            return(View("Login", model));
        }
Ejemplo n.º 4
0
        public async Task AssertionWithEndpointFilter()
        {
            var opStore = new MemoryCryptoKeyAndNonceStore();

            Handle(RPUri).By(
                async req => {
                var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);

                // Rig it to always deny the incoming OP
                rp.EndpointFilter = op => false;

                // Receive the unsolicited assertion
                var response = await rp.GetResponseAsync(req);
                Assert.That(response, Is.Not.Null);
                Assert.AreEqual(AuthenticationStatus.Failed, response.Status);
                return(new HttpResponseMessage());
            });
            this.RegisterAutoProvider();
            {
                var        op        = new OpenIdProvider(opStore, this.HostFactories);
                Identifier id        = GetMockIdentifier(ProtocolVersion.V20);
                var        assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, GetMockRealm(false), id, id);

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
        public async Task <ActionResult> Authenticate(string returnUrl)
        {
            var response = await openid.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken);

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try {
                        var request = await openid.CreateRequestAsync(Request.Form["openid_identifier"]);

                        var redirectingResponse = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken);

                        Response.ContentType = redirectingResponse.Content.Headers.ContentType.ToString();
                        return(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:
                    Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                    var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, false);
                    Response.SetCookie(cookie);
                    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());
        }
Ejemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                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 = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                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;
                    }
                }
            }));
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> LogOn()
        {
            var response = await RP.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken);

            if (response == null)
            {
                Session["customidentity"] = null;
                var request = await RP.CreateRequestAsync(EndPoint);

                StoreRequest store = new StoreRequest();
                store.Attributes.Add(new AttributeValues(Util.GetRootedUri("").ToString(), new[] { Session.SessionID }));
                request.AddExtension(store);
                var redirecting = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken);

                //设置本地响应头部信息
                Response.ContentType = redirecting.Content.Headers.ContentType.ToString();
                return(redirecting.AsActionResult());
            }

            switch (response.Status)
            {
            case AuthenticationStatus.Authenticated:

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

                var dic = fetch.Attributes.Where(obj =>
                {
                    return(obj.TypeUri.IndexOf(EndPoint) == 0);
                }).Select(obj => new { name = obj.TypeUri.Replace(EndPoint, ""), value = obj.Values[0] })
                          .ToLookup(obj => obj.name).ToDictionary(obj => obj.Key, obj => obj.First().value);

                UserModel user = null;
                if (!dic.Any(obj => string.IsNullOrEmpty(obj.Value)))
                {
                    user = new UserModel
                    {
                        UserName = dic["username"],
                        Email    = dic["email"],
                        Gender   = dic["gender"][0]
                    };
                }
                this._formsAuth.SignIn(user);
                return(this.RedirectToAction("index", "home"));

            case AuthenticationStatus.Canceled:
                break;

            case AuthenticationStatus.Failed:
                break;
            }

            return(new EmptyResult());
        }
Ejemplo n.º 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                using (var openid = new OpenIdRelyingParty()) {
                    // In order to receive the UIRequest as a response, we must register a custom extension factory.
                    openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory());

                    var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                    if (response == null)
                    {
                        // Submit an OpenID request which Google must reply to immediately.
                        // If the user hasn't established a trust relationship with this site yet,
                        // Google will not give us the user identity, but they will tell us whether the user
                        // at least has an active login session with them so we know whether to promote the
                        // "Log in with Google" button.
                        IAuthenticationRequest request =
                            await
                            openid.CreateRequestAsync(
                                "https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                        request.AddExtension(new UIRequest {
                            Mode = UIModeDetectSession
                        });
                        request.Mode = AuthenticationRequestMode.Immediate;
                        await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
                    }
                    else
                    {
                        if (response.Status == AuthenticationStatus.Authenticated)
                        {
                            this.YouTrustUsLabel.Visible = true;
                        }
                        else if (response.Status == AuthenticationStatus.SetupRequired)
                        {
                            // Google refused to authenticate the user without user interaction.
                            // This is either because Google doesn't know who the user is yet,
                            // or because the user hasn't indicated to Google to trust this site.
                            // Google uniquely offers the RP a tip as to which of the above situations is true.
                            // Figure out which it is.  In a real app, you might use this value to promote a
                            // Google login button on your site if you detect that a Google session exists.
                            var ext = response.GetUntrustedExtension <UIRequest>();
                            this.YouAreLoggedInLabel.Visible    = ext != null && ext.Mode == UIModeDetectSession;
                            this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible;
                        }
                    }
                }
            }));
        }
        public async Task <ActionResult> Authenticate()
        {
            var rp       = new OpenIdRelyingParty(null);
            var response = await rp.GetResponseAsync(this.Request);

            if (response != null)
            {
                if (response.Status == AuthenticationStatus.Authenticated)
                {
                    FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                    return(this.Redirect(FormsAuthentication.GetRedirectUrl(response.ClaimedIdentifier, false)));
                }
            }

            return(this.RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 10
0
        protected async void Page_Load(object sender, EventArgs e)
        {
            this.openIdBox.Focus();
            using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) {
                IAuthenticationResponse response = await rp.GetResponseAsync(new HttpRequestWrapper(this.Request), this.Response.ClientDisconnectedToken);

                if (response != null)
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.ExtensionsOnly:
                        this.ExtensionResponsesPanel.Visible = true;

                        // This is the "success" status we get when no authentication was requested.
                        var sreg = response.GetExtension <ClaimsResponse>();
                        if (sreg != null)
                        {
                            this.emailLabel.Text      = sreg.Email;
                            this.timeZoneLabel.Text   = sreg.TimeZone;
                            this.postalCodeLabel.Text = sreg.PostalCode;
                            this.countryLabel.Text    = sreg.Country;
                            if (sreg.Gender.HasValue)
                            {
                                this.genderLabel.Text = sreg.Gender.Value.ToString();
                            }
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                        this.resultMessage.Text = "Canceled at OP.  This may be a sign that the OP doesn't support this message.";
                        break;

                    case AuthenticationStatus.Failed:
                        this.resultMessage.Text = "OP returned a failure: " + response.Exception;
                        break;

                    case AuthenticationStatus.SetupRequired:
                    case AuthenticationStatus.Authenticated:
                    default:
                        this.resultMessage.Text = "OP returned an unexpected response.";
                        break;
                    }
                }
            }
        }
Ejemplo n.º 11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
                {
                    // Disable the button since the scenario won't work under localhost,
                    // and this will help encourage the user to read the the text above the button.
                    this.beginButton.Enabled = false;
                }

                IAuthenticationResponse authResponse =
                    await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                if (authResponse != null)
                {
                    switch (authResponse.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        State.FetchResponse             = authResponse.GetExtension <FetchResponse>();
                        AccessTokenResponse accessToken =
                            await Global.GoogleWebConsumer.ProcessUserAuthorizationAsync(authResponse, Response.ClientDisconnectedToken);
                        if (accessToken != null)
                        {
                            State.GoogleAccessToken = accessToken.AccessToken;
                            FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false);
                            Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx");
                        }
                        else
                        {
                            MultiView1.SetActiveView(AuthorizationDenied);
                        }
                        break;

                    case AuthenticationStatus.Canceled:
                    case AuthenticationStatus.Failed:
                    default:
                        this.MultiView1.SetActiveView(this.AuthenticationFailed);
                        break;
                    }
                }
            }));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the result of a user agent's visit to his OpenId provider in an
        /// authentication attempt.  Null if no response is available.
        /// </summary>
        /// <param name="url">The incoming request URL.</param>
        /// <param name="form">The form data that may have been included in the case of a POST request.</param>
        /// <returns>The Provider's response to a previous authentication request, or null if no response is present.</returns>
        public AuthenticationResponseShim ProcessAuthentication(string url, string form)
        {
            string method = "GET";
            NameValueCollection formMap = null;

            if (!string.IsNullOrEmpty(form))
            {
                method  = "POST";
                formMap = HttpUtility.ParseQueryString(form);
            }

            HttpRequestBase requestInfo = new HttpRequestInfo(method, new Uri(url), form: formMap);
            var             response    = relyingParty.GetResponseAsync(requestInfo, CancellationToken.None).Result;

            if (response != null)
            {
                return(new AuthenticationResponseShim(response));
            }

            return(null);
        }
Ejemplo 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>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult" /> containing authentication result.
        /// </returns>
        /// <exception cref="System.InvalidOperationException">Thrown if no OpenID response was found in the incoming HTTP request.</exception>
        public virtual async Task <AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken))
        {
            IAuthenticationResponse response = await RelyingParty.GetResponseAsync(context.Request, cancellationToken);

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

            if (response.Status == AuthenticationStatus.Authenticated)
            {
                string id        = response.ClaimedIdentifier;
                var    extraData = this.GetExtraData(response) ?? new NameValueCollection();

                // try to look up username from the 'username' or 'email' property. If not found, fall back to 'friendly id'
                string username = extraData["username"] ?? extraData["email"] ?? response.FriendlyIdentifierForDisplay;

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

            return(AuthenticationResult.Failed);
        }
Ejemplo n.º 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                UriBuilder returnToBuilder = new UriBuilder(Request.Url);
                returnToBuilder.Path       = "/login.aspx";
                returnToBuilder.Query      = null;
                returnToBuilder.Fragment   = null;
                Uri returnTo         = returnToBuilder.Uri;
                returnToBuilder.Path = "/";
                Realm realm          = returnToBuilder.Uri;

                var response =
                    await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                if (response == null)
                {
                    if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated)
                    {
                        // The user must have been directed here because he has insufficient
                        // permissions to access something.
                        this.MultiView1.ActiveViewIndex = 1;
                    }
                    else
                    {
                        // Because this is a sample of a controlled SSO environment,
                        // we don't ask the user which Provider to use... we just send
                        // them straight off to the one Provider we trust.
                        var request =
                            await
                            relyingParty.CreateRequestAsync(
                                ConfigurationManager.AppSettings["SsoProviderOPIdentifier"], realm, returnTo, Response.ClientDisconnectedToken);
                        var fetchRequest = new FetchRequest();
                        fetchRequest.Attributes.AddOptional(RolesAttribute);
                        request.AddExtension(fetchRequest);
                        await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
                    }
                }
                else
                {
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Canceled:
                        this.errorLabel.Text = "Login canceled.";
                        break;

                    case AuthenticationStatus.Failed:
                        this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message);
                        break;

                    case AuthenticationStatus.Authenticated:
                        IList <string> roles = null;
                        var fetchResponse    = response.GetExtension <FetchResponse>();
                        if (fetchResponse != null)
                        {
                            if (fetchResponse.Attributes.Contains(RolesAttribute))
                            {
                                roles = fetchResponse.Attributes[RolesAttribute].Values;
                            }
                        }
                        if (roles == null)
                        {
                            roles = new List <string>(0);
                        }

                        // Apply the roles to this auth ticket
                        const int TimeoutInMinutes = 100;                                                 // TODO: look up the right value from the web.config file
                        var ticket = new FormsAuthenticationTicket(
                            2,
                            response.ClaimedIdentifier,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(TimeoutInMinutes),
                            false,                                                     // non-persistent, since login is automatic and we wanted updated roles
                            string.Join(";", roles.ToArray()));

                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                        Response.SetCookie(cookie);
                        Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
                        break;

                    default:
                        break;
                    }
                }
            }));
        }
Ejemplo n.º 15
0
        public async Task <ActionResult> Authenticate(string returnUrl)
        {
            HttpRequestMessage          req    = this.Request.AsHttpRequestMessage();
            Dictionary <string, string> fields = new Dictionary <string, string>();

            fields.AddRange(await ParseUrlEncodedFormContentAsync(req));

            if (fields.Count == 0 && req.Method.Method != "POST")
            { // OpenID 2.0 section 4.1.2
                fields.AddRange(HttpUtility.ParseQueryString(req.RequestUri.Query).AsKeyValuePairs());
            }


            string mode;

            if (fields.TryGetValue("openid.mode", out mode))
            {
                string symVal = "";
                fields.TryGetValue("openid.symval", out symVal);

                //first, we add RP's code onto our symval
                string hash_rp = PositiveAssertionResponse.code_to_hash(PositiveAuthenticationResponse.SourceCode_RP);
                //((AuthenticationRequest)request).ProviderEndpoint.Authority + "[[" + PositiveAssertionResponse.hashvalue_op + "()]";
                symVal = this.Request.Url.Authority + "[[" + hash_rp + "(" + symVal + ")]]";



                generate_cs_file_from_symval(symVal, fields);

                TimeSpan t1 = (DateTime.UtcNow - new DateTime(1970, 1, 1));
                TimeSpan t2 = (DateTime.UtcNow - new DateTime(1970, 1, 1));


                int num = (int)(t2.TotalMilliseconds - t1.TotalMilliseconds);

                HttpRequestMessage request = this.Request.AsHttpRequestMessage();

                MessageReceivingEndpoint recipient;
                recipient = request.GetRecipient();

                IProtocolMessage message = openid.Channel.MessageFactory.GetNewRequestMessage(recipient, fields);

                // If there was no data, or we couldn't recognize it as a message, abort.
                if (message == null)
                {
                    return(null);
                }

                // We have a message!  Assemble it.
                var messageAccessor = openid.Channel.MessageDescriptions.GetAccessor(message);
                messageAccessor.Deserialize(fields);

                //IDirectedProtocolMessage message = await openid.Channel.ReadFromRequestAsync_ccp(fields, request, this.Response.ClientDisconnectedToken);

                //only the final response will be here
                var response_ccp = await openid.GetResponseAsync_ccp(message, this.Response.ClientDisconnectedToken);

                //var response_ccp = await openid.GetResponseAsync(req, this.Response.ClientDisconnectedToken);

                // Stage 3: OpenID Provider sending assertion response
                if (!checkLogicProperty())
                {
                    return(new EmptyResult());
                }
                switch (response_ccp.Status)
                {
                case AuthenticationStatus.Authenticated:
                    Session["FriendlyIdentifier"] = response_ccp.FriendlyIdentifierForDisplay;
                    var cookie = FormsAuthentication.GetAuthCookie(response_ccp.ClaimedIdentifier, false);
                    Response.SetCookie(cookie);
                    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_ccp.Exception.Message;
                    return(View("Login"));
                }

                return(new EmptyResult());
            }
            else
            {
                var response = await openid.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken);

                if (response == null)
                {
                    // Stage 2: user submitting Identifier
                    Identifier id;
                    if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                    {
                        try
                        {
                            var request = await openid.CreateRequestAsync(Request.Form["openid_identifier"]);

                            //Eric - add extension
                            var sregRequest = new ClaimsRequest();
                            sregRequest.Email = DemandLevel.Require;
                            request.AddExtension(sregRequest);

                            var redirectingResponse = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken);

                            // this code is handled by HttpResponseMessageActionResult :: ExecuteResult(ControllerContext context)
                            return(redirectingResponse.AsActionResult());
                        }
                        catch (ProtocolException ex)
                        {
                            ViewData["Message"] = ex.Message;
                            return(View("Login"));
                        }
                    }
                    else
                    {
                        ViewData["Message"] = "Invalid identifier";
                        return(View("Login"));
                    }
                }
                return(new EmptyResult());
            }
            //ERIC'S CODE - end
        }
Ejemplo n.º 16
0
        public async Task <ActionResult> Authenticate(string redirect)
        {
            var response = await openid.GetResponseAsync(this.Request);

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(c_STEAM_PROVIDER, out id))
                {
                    try
                    {
                        var request = await openid.CreateRequestAsync(c_STEAM_PROVIDER);

                        var redirectingResponse = await request.GetRedirectingResponseAsync();

                        return(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:
                    //authenticate user
                    Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                    var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, true);
                    cookie.Expires = DateTime.Now.Add(new TimeSpan(7, 0, 0, 0));
                    Response.SetCookie(cookie);
                    if (!string.IsNullOrEmpty(redirect))
                    {
                        return(Redirect(redirect));
                    }
                    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());
        }