Beispiel #1
0
        private static async Task <(string, string, DateTime)> RefreshTokenAsync(string refreshToken, string clientId,
                                                                                 string clientSecret)
        {
            if (string.IsNullOrEmpty(refreshToken))
            {
                Console.WriteLine("No refresh token provided");
            }

            Console.WriteLine($"Using refresh token: {refreshToken}");

            // Get provider information manually
            ProviderInformation provider = await GetProviderInformation().ConfigureAwait(false);

            // Make a refresh token request. This will issue new access and refresh tokens.
            using HttpClient tokenClient             = new ();
            using RefreshTokenRequest refreshRequest = new ()
                  {
                      Address      = provider.TokenEndpoint,
                      ClientId     = clientId,
                      ClientSecret = clientSecret,
                      RefreshToken = refreshToken,
                  };
            TokenResponse response = await tokenClient.RequestRefreshTokenAsync(refreshRequest).ConfigureAwait(false);

            if (response.IsError)
            {
                Console.WriteLine("Error while getting the refresh token: " + response.Error);
                return(string.Empty, string.Empty, DateTime.Now);
            }

            return(response.AccessToken, response.RefreshToken,
                   DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime());
        }
Beispiel #2
0
        public void ValidateSubscriberAndProvider_ShouldReturnValidStatus()
        {
            // Arrange
            var dialogServiceMock = new Mock <IDialogService>();
            var api = new ChewsiApi(dialogServiceMock.Object);
            ProviderInformation        provider        = GetValidProvider();
            SubscriberInformation      subscriber      = GetValidSubscriber();
            ProviderAddressInformation providerAddress = GetValidProviderAddress();

            // Act
            ValidateSubscriberAndProviderResponse response = api.ValidateSubscriberAndProvider(provider, providerAddress, subscriber);

            // Assert
            // Validate provider
            Assert.IsNotNull(response.ProviderID);
            Assert.IsNull(response.ProviderValidationMessage);
            Assert.AreEqual("Valid", response.ProviderValidationStatus);
            // Validate subscriber
            Assert.AreEqual("4", response.SubscriberID);
            Assert.IsNull(response.SubscriberValidationMessage);
            Assert.AreEqual("Valid", response.SubscriberValidationStatus);
            Assert.AreEqual("1", response.OfficeNumber);

            Assert.AreEqual(true, response.ValidationPassed);
        }
Beispiel #3
0
        public void ValidateSubscriberAndProvider_WhenSubscriberDataIsIncorrect_ShouldReturnSubscriberNotFoundStatus()
        {
            // Arrange
            var dialogServiceMock = new Mock <IDialogService>();
            var api = new ChewsiApi(dialogServiceMock.Object);
            ProviderInformation   provider   = GetValidProvider();
            SubscriberInformation subscriber = GetValidSubscriber();

            subscriber.Id = "123456"; // API checks First Name and Chewsi Id
            ProviderAddressInformation providerAddress = GetValidProviderAddress();

            // Act
            ValidateSubscriberAndProviderResponse response = api.ValidateSubscriberAndProvider(provider, providerAddress, subscriber);

            // Assert
            // Validate provider
            Assert.AreEqual("4074437", response.ProviderID);
            Assert.IsNull(response.ProviderValidationMessage);
            Assert.AreEqual("Valid", response.ProviderValidationStatus);
            // Validate subscriber
            Assert.IsNull(response.SubscriberID);
            Assert.AreEqual("Please validate that the subscriber's Chewsi ID and First Name match the information shown before proceeding. If the information does not match, the Chewsi ID may have been keyed into the practice management system incorrectly. Please ask the subscriber for their Chewsi ID to validate.",
                            response.SubscriberValidationMessage);
            Assert.AreEqual("Subscriber Not Found", response.SubscriberValidationStatus);
            Assert.AreEqual("1", response.OfficeNumber);

            Assert.AreEqual(false, response.ValidationPassed);
        }
Beispiel #4
0
        public void ValidateSubscriberAndProvider_WhenProviderDataIsIncorrect_ShouldReturnProviderNotFoundStatus()
        {
            // Arrange
            var dialogServiceMock = new Mock <IDialogService>();
            var api = new ChewsiApi(dialogServiceMock.Object);
            ProviderInformation        provider        = GetValidProvider();
            SubscriberInformation      subscriber      = GetValidSubscriber();
            ProviderAddressInformation providerAddress = GetValidProviderAddress();

            providerAddress.RenderingAddress1 += " test";

            // Act
            ValidateSubscriberAndProviderResponse response = api.ValidateSubscriberAndProvider(provider, providerAddress, subscriber);

            // Assert
            // Validate provider
            Assert.IsNull(response.ProviderID);
            Assert.AreEqual("We did not find the provider for which this claim is being submitted for in the list of Chewsi registered providers. Please validate that the claim is being submitted under a provider who has already registered themselves under the Chewsi network.",
                            response.ProviderValidationMessage);
            Assert.AreEqual("Provider Not Found", response.ProviderValidationStatus);
            // Validate subscriber
            Assert.AreEqual("4", response.SubscriberID);
            Assert.IsNull(response.SubscriberValidationMessage);
            Assert.AreEqual("Valid", response.SubscriberValidationStatus);

            //TODO
            Assert.AreEqual("", response.OfficeNumber);

            Assert.AreEqual(false, response.ValidationPassed);
        }
 void UseProviderChanged(Object obj)
 {
     if (UseProvider)
     {
         ProviderInfo = new ProviderInformation();
     }
     else
     {
         ProviderInfo = null;
         BlogsLoaded  = false;
     }
 }
Beispiel #6
0
    public override OidcClient CreateAuthClient()
    {
        string uriScheme = "";
        string uriHost   = "";
        string clientId  = "";

        var options = new OidcClientOptions()
        {
            Authority = "https://oauth.magicleap.com",
            ClientId  = clientId,
            Scope     = "openid offline_access",
            // HACK: remove profile. external credentials will not have the "profile" scope provided (where it gives you back your name once you sign in)  for security reasons
            // Scope = "openid profile offline_access",
            // Redirect (reply) uri is specified in the AndroidManifest and code for handling
            // it is in the associated AndroidUnityPlugin project, and OAuthUnityAppController.mm.
            RedirectUri  = $"{uriScheme}://{uriHost}",
            ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect,
            Flow         = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
            Browser      = Browser,
        };

        // TODO: MLID endpoints for validation do not exist yet so we make up the discovery data
        // and disable a bunch of verification steps.
        var info = new ProviderInformation();

        info.AuthorizeEndpoint  = $"{options.Authority}/auth";
        info.IssuerName         = "https://auth.magicleap.com";
        info.EndSessionEndpoint = $"{options.Authority}/logout";
        info.TokenEndpoint      = $"{options.Authority}/token";
        info.TokenEndPointAuthenticationMethods = new List <string>
        {
            "client_secret_basic",
            "client_secret_post"
        };

        Stream stream = WebRequest.CreateHttp("https://auth.magicleap.com/.well-known/jwks.json").GetResponse().GetResponseStream();
        string json   = new StreamReader(stream, Encoding.UTF8).ReadToEnd();

        info.KeySet = new JsonWebKeySet(json);

        options.PostLogoutRedirectUri = options.RedirectUri;
        options.LoggerFactory.AddProvider(new Assets.UnityAuthLoggerProvider());
        options.RefreshDiscoveryDocumentForLogin = false;
        options.ProviderInformation = info;
        options.LoadProfile         = false;
        options.Policy.RequireIdentityTokenSignature = false;
        options.Policy.Discovery.ValidateIssuerName  = false;
        options.Policy.RequireAccessTokenHash        = false;
        options.Policy.RequireAuthorizationCodeHash  = false;
        options.Policy.RequireIdentityTokenOnRefreshTokenResponse = false;

        return(new OidcClient(options));
    }
        public BloggerClient(ProviderInformation provider)
        {
            _userName = provider.UserName;
            _password = Crypt.DecryptPassword(provider.Password);
            _blogId   = provider.Blog.blogid;

            _metaWeblogProvider = (IMetaWeblogProvider)XmlRpcProxyGen.Create(typeof(IMetaWeblogProvider));
            XmlRpcClientProtocol clientProtocol = (XmlRpcClientProtocol)_metaWeblogProvider;

            clientProtocol.Url         = provider.ProviderURL;
            clientProtocol.UserAgent   = "PS Cmdlet Help Editor/" + Assembly.GetExecutingAssembly().GetName().Version;
            clientProtocol.NonStandard = XmlRpcNonStandard.All;
        }
        public static Blogger InitializeBlogger(ProviderInformation provInfo)
        {
            if (
                String.IsNullOrEmpty(provInfo.ProviderURL) ||
                String.IsNullOrEmpty(provInfo.UserName) ||
                provInfo.SecurePassword == null
                )
            {
                return(null);
            }
            Blogger blogger = new Blogger(provInfo.ProviderURL, provInfo.UserName, provInfo.SecurePassword);

            if (provInfo.Blog != null && !String.IsNullOrEmpty(provInfo.Blog.blogid))
            {
                blogger.SetBlog(provInfo.Blog.blogid);
            }
            return(blogger);
        }
        public Task <IdentityTokenValidationResult> ValidateAsync(string identityToken, string clientId, ProviderInformation providerInformation)
        {
            Logger.Debug("starting identity token validation");
            Logger.Debug($"identity token: {identityToken}");

            var fail = new IdentityTokenValidationResult();

            ValidatedToken token;

            try
            {
                token = ValidateSignature(identityToken, providerInformation.KeySet);
            }
            catch (Exception ex)
            {
                fail.Error = ex.ToString();
                Logger.Error(fail.Error);

                return(Task.FromResult(fail));
            }

            if (!token.Success)
            {
                fail.Error = token.Error;
                Logger.Error(fail.Error);

                return(Task.FromResult(fail));
            }

            var issuer = token.Payload["iss"].ToString();

            Logger.Debug($"issuer: {issuer}");

            var audience = token.Payload["aud"].ToString();

            Logger.Debug($"audience: {audience}");

            if (!string.Equals(issuer, providerInformation.IssuerName, StringComparison.Ordinal))
            {
                fail.Error = "Invalid issuer name";
                Logger.Error(fail.Error);

                return(Task.FromResult(fail));
            }

            if (!string.Equals(audience, clientId, StringComparison.Ordinal))
            {
                fail.Error = "Invalid audience";
                Logger.Error(fail.Error);

                return(Task.FromResult(fail));
            }

            var utcNow = DateTime.UtcNow;
            var exp    = token.Payload.Value <long>("exp");
            var nbf    = token.Payload.Value <long?>("nbf");

            Logger.Debug($"exp: {exp}");

            if (nbf != null)
            {
                Logger.Debug($"nbf: {nbf}");

                var notBefore = nbf.Value.ToDateTimeFromEpoch();
                if (notBefore > utcNow.Add(ClockSkew))
                {
                    fail.Error = "Token not valid yet";
                    Logger.Error(fail.Error);

                    return(Task.FromResult(fail));
                }
            }

            var expires = exp.ToDateTimeFromEpoch();

            if (expires < utcNow.Add(ClockSkew.Negate()))
            {
                fail.Error = "Token expired";
                Logger.Error(fail.Error);

                return(Task.FromResult(fail));
            }

            Logger.Info("identity token validation success");

            return(Task.FromResult(new IdentityTokenValidationResult
            {
                Claims = token.Payload.ToClaims(),
                SignatureAlgorithm = token.Algorithm
            }));
        }
        public ProviderWithResultsForSpecificationsBuilder WithProviderInformation(ProviderInformation providerInformation)
        {
            _providerInformation = providerInformation;

            return(this);
        }
        public Task <IdentityTokenValidationResult> ValidateAsync(string identityToken, string clientId, ProviderInformation providerInformation)
        {
            var fail = new IdentityTokenValidationResult
            {
                Success = false
            };

            var e      = Base64Url.Decode(providerInformation.KeySet.Keys.First().E);
            var n      = Base64Url.Decode(providerInformation.KeySet.Keys.First().N);
            var pubKey = PublicKey.New(e, n);

            var json    = JosePCL.Jwt.Decode(identityToken, pubKey);
            var payload = JObject.Parse(json);

            var issuer   = payload["iss"].ToString();
            var audience = payload["aud"].ToString();

            if (issuer != providerInformation.IssuerName)
            {
                fail.Error = "Invalid issuer name";
                return(Task.FromResult(fail));
            }

            if (audience != clientId)
            {
                fail.Error = "Invalid audience";
                return(Task.FromResult(fail));
            }

            var exp = payload["exp"].ToString();
            var nbf = payload["nbf"].ToString();

            var utcNow    = DateTime.UtcNow;
            var notBefore = long.Parse(nbf).ToDateTimeFromEpoch();
            var expires   = long.Parse(exp).ToDateTimeFromEpoch();

            if (notBefore > utcNow.Add(ClockSkew))
            {
                fail.Error = "Token not valid yet";
                return(Task.FromResult(fail));
            }

            if (expires < utcNow.Add(ClockSkew.Negate()))
            {
                fail.Error = "Token expired";
                return(Task.FromResult(fail));
            }

            return(Task.FromResult(new IdentityTokenValidationResult
            {
                Success = true,
                Claims = payload.ToClaims(),
                SignatureAlgorithm = "RS256"
            }));
        }