コード例 #1
0
        public void Should_Registration_Request_Has_RedirectUris()
        {
            rpid = "rp-registration-redirect_uris";

            // given
            string registrationEndopoint         = GetBaseUrl("/registration");
            OIDCClientInformation clientMetadata = new OIDCClientInformation();

            clientMetadata.ApplicationType = "web";
            clientMetadata.RedirectUris    = new List <string>()
            {
                myBaseUrl + "code_flow_callback"
            };
            clientMetadata.ResponseTypes = new List <ResponseType>()
            {
                ResponseType.Code
            };
            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            // when
            OIDCClientInformation response = rp.RegisterClient(registrationEndopoint, clientMetadata);

            // then
            response.Validate();
            CollectionAssert.AreEquivalent(clientMetadata.RedirectUris, response.RedirectUris);
        }
コード例 #2
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;
            }
        }
コード例 #3
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);
        }
    }
コード例 #4
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());
            }
        }
コード例 #5
0
        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());
        }
コード例 #6
0
ファイル: OpenIdController.cs プロジェクト: sh77awn/prontocms
        public ActionResult Login()
        {
            var openid = new OpenIdRelyingParty();

            if (openid.Response == null)
            {
                throw new InvalidOperationException("Not an OpenID response.");
            }
            else
            {
                var returnUrl = (string)Session["returnUrl"] ?? "~/";
                // Stage 3: OpenID Provider sending assertion response
                switch (openid.Response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    FormsAuthentication.SetAuthCookie(openid.Response.ClaimedIdentifier, false);
                    return(Redirect(returnUrl));

                case AuthenticationStatus.Canceled:
                    return(Redirect(returnUrl + "#login-cancelled"));

                default:
                    return(Redirect(returnUrl + "#login-fail"));
                }
            }
        }
コード例 #7
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;
        }
    }
コード例 #8
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;
            }
        }
コード例 #9
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;
                }
            }
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        public void Should_Nonce_Be_Present_In_Self_Issued()
        {
            rpid = "rp-nonce-unless_code_flow";
            WebRequest.RegisterPrefix("openid", new OIDCWebRequestCreate());

            // given
            OIDCAuthorizationRequestMessage requestMessage = new OIDCAuthorizationRequestMessage();

            requestMessage.ClientId = clientInformation.RedirectUris[0];
            requestMessage.Scope    = new List <MessageScope>()
            {
                MessageScope.Openid, MessageScope.Profile, MessageScope.Email, MessageScope.Address, MessageScope.Phone
            };
            requestMessage.State        = WebOperations.RandomString();
            requestMessage.Nonce        = WebOperations.RandomString();
            requestMessage.ResponseType = new List <ResponseType>()
            {
                ResponseType.IdToken
            };
            requestMessage.RedirectUri = clientInformation.RedirectUris[0];
            requestMessage.Validate();

            X509Certificate2   certificate = new X509Certificate2("server.pfx", "", X509KeyStorageFlags.Exportable);
            OpenIdRelyingParty rp          = new OpenIdRelyingParty();

            // when
            OIDCAuthImplicitResponseMessage response = rp.Authenticate("openid://", requestMessage, certificate);
            OIDCIdToken idToken = response.GetIdToken();

            // then
            response.Validate();
        }
コード例 #12
0
        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"));
            }
        }
コード例 #13
0
        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;
                }
            }
        }
コード例 #14
0
        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);
        }
コード例 #15
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();
            }
        }
コード例 #16
0
        private ActionResult OpenIdRequest(OpenIdRelyingParty openid)
        {
            var openIdIdentifier = this.Request.Form["openid_identifier"];

            if (openIdIdentifier == TestAccountIdentifier)
            {
                return(this.LoginAsTestUser());
            }
            else
            {
                Identifier id;
                if (Identifier.TryParse(openIdIdentifier, out id))
                {
                    try
                    {
                        return(OpenIdService.SendRequest(openid, id));
                    }
                    catch (ProtocolException ex)
                    {
                        Logger.Error("OpenIdRequestError: {0}", ex.Message);
                        this.ViewBag.Error = "Authentication failed";
                        return(this.View("Login"));
                    }
                }
                else
                {
                    Logger.Error(
                        "Openid_identifier parse error.\r\nThis value should be in the Form Request.\r\nPossible error in View.");
                    this.ViewBag.Error = "Authentication error";
                    return(this.View("Login"));
                }
            }
        }
コード例 #17
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"));
        }
コード例 #18
0
        /// <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);
            }
        }
コード例 #19
0
ファイル: UserController.cs プロジェクト: Myslik/opencat
        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());
        }
        public void Should_Request_And_Use_Claims_Id_Token()
        {
            rpid    = "rp-response_type-id_token+token";
            signalg = "RS256";
            GetProviderMetadata();

            // given
            string    Nonce         = WebOperations.RandomString();
            OIDClaims requestClaims = new OIDClaims();

            requestClaims.IdToken = new Dictionary <string, OIDClaimData>();
            requestClaims.IdToken.Add("name", new OIDClaimData());

            // when
            OIDCAuthImplicitResponseMessage response = (OIDCAuthImplicitResponseMessage)GetAuthResponse(ResponseType.IdToken, Nonce, true, requestClaims);

            // then
            response.Validate();
            Assert.NotNull(response.AccessToken);

            OpenIdRelyingParty rp      = new OpenIdRelyingParty();
            OIDCIdToken        idToken = response.GetIdToken(providerMetadata.Keys, clientInformation.ClientSecret);

            rp.ValidateIdToken(idToken, clientInformation, providerMetadata.Issuer, Nonce);
            Assert.IsNotNullOrEmpty(idToken.Name);
        }
コード例 #21
0
        public void Should_Use_Request_Uri_Parameter_Signed_And_Encrypted()
        {
            rpid = "rp-request_uri-sig+enc";

            // given
            OIDCAuthorizationRequestMessage requestMessage = generateRequestMessage();
            OIDCAuthorizationRequestMessage requestObject  = generateRequestObject(requestMessage.State, requestMessage.Nonce);

            X509Certificate2         certificate = new X509Certificate2("server.pfx", "", X509KeyStorageFlags.Exportable);
            RSACryptoServiceProvider signKey     = getSignKey();
            RSACryptoServiceProvider encKey      = getEncKey();

            request = JWT.Encode(requestObject.SerializeToJsonString(), signKey, JwsAlgorithm.RS256);
            request = JWT.Encode(request, encKey, JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256);

            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            // when
            rp.Authenticate(GetBaseUrl("/authorization"), requestMessage);
            semaphore.WaitOne();
            OIDCAuthCodeResponseMessage response = rp.ParseAuthCodeResponse(result, requestMessage.Scope);

            // then
            response.Validate();
        }
コード例 #22
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());
        }
コード例 #23
0
        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());
        }
コード例 #24
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());
            }
        }
コード例 #25
0
    OpenIdRelyingParty createRelyingParty()
    {
        OpenIdRelyingParty openid = new OpenIdRelyingParty();
        int minsha, maxsha, minversion;

        if (int.TryParse(Request.QueryString["minsha"], out minsha))
        {
            openid.Settings.MinimumHashBitLength = minsha;
        }
        if (int.TryParse(Request.QueryString["maxsha"], out maxsha))
        {
            openid.Settings.MaximumHashBitLength = maxsha;
        }
        if (int.TryParse(Request.QueryString["minversion"], out minversion))
        {
            switch (minversion)
            {
            case 1: openid.Settings.MinimumRequiredOpenIdVersion = ProtocolVersion.V10; break;

            case 2: openid.Settings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20; break;

            default: throw new ArgumentOutOfRangeException("minversion");
            }
        }
        return(openid);
    }
コード例 #26
0
        public void Should_Client_Only_Use_Https_Endpoints()
        {
            rpid = "rp-registration-uses_https_endpoints";

            // given
            string registrationEndopoint         = GetBaseUrl("/registration");
            OIDCClientInformation clientMetadata = new OIDCClientInformation();

            clientMetadata.ApplicationType = "web";
            clientMetadata.RedirectUris    = new List <string>()
            {
                myBaseUrl + "code_flow_callback"
            };
            clientMetadata.ResponseTypes = new List <ResponseType>()
            {
                ResponseType.Code
            };
            clientMetadata.JwksUri = myBaseUrl + "my_public_keys.jwks";
            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            // when
            OIDCClientInformation response = rp.RegisterClient(registrationEndopoint, clientMetadata);

            response.JwksUri = clientMetadata.JwksUri.Replace("https", "http");

            // then
            response.Validate();
        }
コード例 #27
0
ファイル: AuthenticationTests.cs プロジェクト: terry2012/DSV
        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();
                    }
                }
            }
        }
コード例 #28
0
        public void Should_Client_Be_Able_To_Register()
        {
            rpid = "rp-registration-dynamic";

            // given
            string registrationEndopoint         = GetBaseUrl("/registration");
            OIDCClientInformation clientMetadata = new OIDCClientInformation();

            clientMetadata.ApplicationType = "web";
            clientMetadata.RedirectUris    = new List <string>()
            {
                myBaseUrl + "code_flow_callback"
            };
            clientMetadata.ResponseTypes = new List <ResponseType>()
            {
                ResponseType.Code
            };
            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            // when
            OIDCClientInformation response = rp.RegisterClient(registrationEndopoint, clientMetadata);

            // then
            response.Validate();
        }
コード例 #29
0
        public void GetProviderMetadata()
        {
            string             hostname = GetBaseUrl("/");
            OpenIdRelyingParty rp       = new OpenIdRelyingParty();

            providerMetadata = rp.ObtainProviderInformation(hostname);
        }
コード例 #30
0
        public void Should_Keys_Be_Published_As_JWK()
        {
            rpid = "rp-registration-well_formed_jwk";

            // given
            string registrationEndopoint         = GetBaseUrl("/registration");
            OIDCClientInformation clientMetadata = new OIDCClientInformation();

            clientMetadata.ApplicationType = "web";
            clientMetadata.RedirectUris    = new List <string>()
            {
                myBaseUrl + "code_flow_callback"
            };
            clientMetadata.ResponseTypes = new List <ResponseType>()
            {
                ResponseType.Code
            };
            clientMetadata.JwksUri = myBaseUrl + "my_public_keys.jwks";
            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            // when
            OIDCClientInformation response = rp.RegisterClient(registrationEndopoint, clientMetadata);

            // then
            response.Validate();
        }
コード例 #31
0
        public void RegisterClient(IRPOptions rpOptions, OpenIDUrls urls)
        {
            if (SelfRegistered && ClientInformation == null)
            {
                OIDCClientInformation clientMetadata = new OIDCClientInformation();
                clientMetadata.ApplicationType = "web";
                clientMetadata.ResponseTypes = new List<ResponseType>() { ResponseType.Code };
                clientMetadata.RedirectUris = new List<string>() { urls.CodeCallbackCommand.ToString() };
                clientMetadata.TokenEndpointAuthMethod = "client_secret_basic";

                if ((Sign && rpOptions.SignCertificate != null) || (Encrypt && rpOptions.EncCertificate != null))
                {
                    clientMetadata.JwksUri = urls.JwksCallbackCommand.ToString();
                }

                OpenIdRelyingParty rp = new OpenIdRelyingParty();
                ClientInformation = rp.RegisterClient(ProviderMatadata.RegistrationEndpoint, clientMetadata);
            }
        }
コード例 #32
0
        private void LoadOPInformation(OpenIDProviderElement opEntry)
        {
            Sign = opEntry.Sign;
            Encrypt = opEntry.Encrypt;

            if (!String.IsNullOrEmpty(opEntry.OPIssuer))
            {
                OpenIdRelyingParty rp = new OpenIdRelyingParty();
                ProviderMatadata = rp.ObtainProviderInformation(opEntry.OPIssuer, opEntry.OPIssuer);
            }
            else
            {
                foreach (string value in new List<string>() { opEntry.AuthorizationEndpoint, opEntry.TokenEndpoint, opEntry.UserinfoEndpoint })
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        throw new ArgumentException("Missign one requred value for configuration. When configuring rp without isser discovery, all these fields must be specified: authorizationEndpoint, tokenEndpoint, userinfoEndpoint.");
                    }
                }

                ProviderMatadata = new OIDCProviderMetadata()
                {
                    AuthorizationEndpoint = opEntry.AuthorizationEndpoint,
                    TokenEndpoint = opEntry.TokenEndpoint,
                    UserinfoEndpoint = opEntry.UserinfoEndpoint,
                };

                if (!string.IsNullOrEmpty(opEntry.RegistrationEndpoint))
                {
                    ProviderMatadata.RegistrationEndpoint = opEntry.RegistrationEndpoint;
                }
            }
        }
コード例 #33
0
        private OIDCUserInfoResponseMessage GetUserInfo(OIDCAuthCodeResponseMessage authResponse, IOptions options, HttpSessionState session, string accessToken)
        {
            OpenIDProviderData providerData = options.OpenIDProviders[session["op"] as string];
            OpenIdRelyingParty rp = new OpenIdRelyingParty();

            OIDClaims requestClaims = new OIDClaims();
            requestClaims.IdToken = new Dictionary<string, OIDClaimData>();
            requestClaims.IdToken.Add("name", new OIDClaimData());
            requestClaims.IdToken.Add("family_name", new OIDClaimData());
            requestClaims.IdToken.Add("given_name", new OIDClaimData());
            requestClaims.IdToken.Add("email", new OIDClaimData());
            requestClaims.IdToken.Add("gender", new OIDClaimData());

            OIDCUserInfoRequestMessage userInfoRequestMessage = new OIDCUserInfoRequestMessage();
            userInfoRequestMessage.Scope = authResponse.Scope;
            userInfoRequestMessage.State = authResponse.State;
            userInfoRequestMessage.Claims = requestClaims;

            var urlInfoUrl = providerData.ProviderMatadata.UserinfoEndpoint;
            return rp.GetUserInfo(urlInfoUrl, userInfoRequestMessage, accessToken);
        }
コード例 #34
0
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (OpenId == null) {  OpenId = new OpenIdRelyingParty(); }

            base.Initialize(requestContext);
        }