Esempio n. 1
0
        private void ValidateLoginToken(string token, AppServiceAuthenticationOptions options)
        {
            // validate the token and get the claims principal
            ClaimsPrincipal claimsPrincipal = null;

            Assert.True(this.tokenHandler.TryValidateLoginToken(token, options.SigningKey, this.testWebsiteUrls, this.testWebsiteUrls, out claimsPrincipal));
        }
Esempio n. 2
0
        public void Authenticate_CorrectlyAuthenticates(string otherSigningKey, bool expectAuthenticated)
        {
            // Arrange
            HttpConfiguration config = new HttpConfiguration();
            AppServiceAuthenticationOptions optionsDefault = CreateTestOptions(config);

            optionsDefault.SigningKey = SigningKeyAlpha;

            AppServiceAuthenticationOptions optionsOtherSigningKey = CreateTestOptions(config);

            optionsOtherSigningKey.SigningKey = otherSigningKey;

            var mock    = new MobileAppAuthenticationHandlerMock(this.loggerMock.Object);
            var request = CreateAuthRequest(new Uri(TestWebsiteUrl), GetTestToken());

            // Act
            AuthenticationTicket authTicket = mock.Authenticate(request, optionsOtherSigningKey);

            // Assert
            if (expectAuthenticated)
            {
                // ensure the AuthenticationTicket is set correctly
                Assert.NotNull(authTicket);
                Assert.NotNull(authTicket.Identity);
                Assert.True(authTicket.Identity.IsAuthenticated);
            }
            else
            {
                Assert.NotNull(authTicket);
                Assert.NotNull(authTicket.Identity);
                Assert.False(authTicket.Identity.IsAuthenticated);
            }
        }
        private AppServiceAuthenticationOptions CreateTestOptions()
        {
            AppServiceAuthenticationOptions options = new AppServiceAuthenticationOptions
            {
                SigningKey = TestSigningKey,
            };

            return(options);
        }
Esempio n. 4
0
        public void TryValidateLoginToken_RejectsMalformedTokens()
        {
            AppServiceAuthenticationOptions options = this.CreateTestOptions();
            ClaimsPrincipal claimsPrincipal         = null;
            bool            result = this.tokenHandler.TryValidateLoginToken("this is not a valid jwt", options.SigningKey, this.testWebsiteUrls, this.testWebsiteUrls, out claimsPrincipal);

            Assert.False(result);
            Assert.Null(claimsPrincipal);
        }
Esempio n. 5
0
        private static AppServiceAuthenticationOptions CreateTestOptions(HttpConfiguration config)
        {
            AppServiceAuthenticationOptions options = new AppServiceAuthenticationOptions
            {
                ValidAudiences = new[] { TestWebsiteUrl },
                ValidIssuers   = new[] { TestWebsiteUrl },
                SigningKey     = SigningKeyAlpha,
                TokenHandler   = config.GetAppServiceTokenHandler()
            };

            return(options);
        }
Esempio n. 6
0
        public void CreateTokenInfo_AndValidateLoginToken_Works()
        {
            AppServiceAuthenticationOptions options = this.CreateTestOptions();

            Claim[] claims = new Claim[]
            {
                new Claim("sub", this.credentials.UserId),
            };

            // Create a login token for the provider
            JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, this.testSecretKey, this.testWebsiteUrls[0], this.testWebsiteUrls[0], Lifetime);

            this.ValidateLoginToken(token.RawData, options);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
#if DEBUG
            // It is useful to be able to debug the API app locally, but this becomes challenging
            // once authentication is involved - Azure App Service does the authentication for
            // us, and of course if we're running locally then Azure App Service is no longer in
            // the picture.
            // What we can do, though, is arrange for the client to authenticate against the real
            // service, but then talk to localhost for everything else. That wouldn't normally work
            // because the local service would have no way of validating the token. But the following
            // code configures the token handling so that it will work correctly with tokens supplied
            // by the real service.when running locally.
            // On the client side, this
            // First, we need to detect whether we are in fact running locally, or up in Azure:
            var config = GlobalConfiguration.Configuration;
            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
            var cons = settings.Connections;
            if (string.IsNullOrEmpty(settings.HostName))
            {
                // By default, HostName will only have a value when running in an App Service application,
                // so if we get here it means we're running locally.

                // Next, has the developer supplied the config we require to be able to validate
                // Azure-supplied keys locally?
                // See
                //  http://www.systemsabuse.com/2015/12/04/local-debugging-with-user-authentication-of-an-azure-mobile-app-service/
                // for details on how to get these settings.
                var signingKey = ConfigurationManager.AppSettings["SigningKey"];
                if (!string.IsNullOrWhiteSpace(signingKey))
                {
                    // The dev has supplied a signing key (and we assume if they've worked
                    // out how to do that, they've also filled in the audience and issuer)
                    // so let's configure the middleware to be able to process tokens from
                    // Azure.
                    var options = new AppServiceAuthenticationOptions
                    {
                        SigningKey     = ConfigurationManager.AppSettings["SigningKey"],
                        ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                        ValidIssuers   = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                        TokenHandler   = config.GetAppServiceTokenHandler()
                    };
                    app.UseAppServiceAuthentication(options);
                }
            }
#endif

            // If we're not debugging locally, we rely entirely on Azure App
            // Service authentication, so there's nothing for us to do.
        }
Esempio n. 8
0
        public void Authenticate_Fails_WithInvalidIssuer()
        {
            // Arrange
            AppServiceAuthenticationOptions options = CreateTestOptions(new HttpConfiguration());
            var mock    = new MobileAppAuthenticationHandlerMock(this.loggerMock.Object);
            var request = CreateAuthRequest(new Uri(TestWebsiteUrl), GetTestToken(issuer: "https://invalidIssuer/"));

            // Act
            AuthenticationTicket authticket = mock.Authenticate(request, options);

            // Assert
            Assert.NotNull(authticket);
            Assert.NotNull(authticket.Identity);
            Assert.False(authticket.Identity.IsAuthenticated, "Expected Authenticate to fail with invalid issuer");
        }
        /// <summary>
        /// Create a test user
        /// </summary>
        private ClaimsPrincipal CreateTestUser()
        {
            AppServiceAuthenticationOptions options = CreateTestOptions();

            Claim[] claims = new Claim[]
            {
                new Claim("sub", this.facebookCredentials.UserId)
            };

            JwtSecurityToken token = AppServiceLoginHandler.CreateToken(claims, TestSigningKey, TestLocalhostUrl, TestLocalhostUrl, TimeSpan.FromDays(10));

            ClaimsPrincipal user = null;

            string[] validIssAud = new[] { TestLocalhostUrl };
            this.tokenHandler.TryValidateLoginToken(token.RawData, options.SigningKey, validIssAud, validIssAud, out user);

            return(user);
        }
Esempio n. 10
0
        public void Authenticate_FailsToAuthenticate_ValidIdentity_WithoutSigningKey()
        {
            // Arrange
            AppServiceAuthenticationOptions options = CreateTestOptions(new HttpConfiguration());

            var mock    = new MobileAppAuthenticationHandlerMock(this.loggerMock.Object);
            var request = CreateAuthRequest(new Uri(TestWebsiteUrl), GetTestToken());

            options.SigningKey = null;

            // Act
            AuthenticationTicket authticket = mock.Authenticate(request, options);

            // Assert
            Assert.NotNull(authticket);
            Assert.NotNull(authticket.Identity);
            Assert.False(authticket.Identity.IsAuthenticated, "Expected Authenticate to fail without signing key specified in MobileAppAuthenticationOptions");
        }
Esempio n. 11
0
        public void UseMobileAppAuthentication_ConfiguresServiceAuthentication_WhenAuthEnabled()
        {
            // Arrange
            MobileAppConfiguration configOptions = new MobileAppConfiguration();

            this.config.SetMobileAppConfiguration(configOptions);
            AppServiceAuthenticationOptions options = new AppServiceAuthenticationOptions();

            this.appBuilderMock.Setup(p => p.Use(It.IsAny <object>(), It.IsAny <object[]>()))
            .Callback <object, object[]>((mockObject, mockArgs) =>
            {
                options = (AppServiceAuthenticationOptions)mockArgs[1];
            })
            .Returns(this.appBuilder)
            .Verifiable();

            // Act
            this.appBuilder.UseAppServiceAuthentication(options);

            // Assert
            this.appBuilderMock.Verify(p => p.Use(It.IsAny <object>(), It.IsAny <object[]>()), Times.Once);
            Assert.Equal("MobileApp", options.AuthenticationType);
        }
Esempio n. 12
0
        public void TryValidateLoginToken_AcceptsPreviousTokenVersions(string tokenValue)
        {
            AppServiceAuthenticationOptions options = this.CreateTestOptions();

            this.ValidateLoginToken(tokenValue, options);
        }
Esempio n. 13
0
 public new AuthenticationTicket Authenticate(IOwinRequest request, AppServiceAuthenticationOptions options)
 {
     return(base.Authenticate(request, options));
 }
Esempio n. 14
0
        public static IAppBuilder UseAppServiceAuthentication(this IAppBuilder appBuilder, AppServiceAuthenticationOptions options)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException("appBuilder");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            appBuilder.Use(typeof(AppServiceAuthenticationMiddleware), new object[]
            {
                appBuilder,
                options
            });

            return(appBuilder);
        }
Esempio n. 15
0
 public MobileAppAuthenticationOptionsTests()
 {
     this.options            = new AppServiceAuthenticationOptions();
     this.options.SigningKey = SigningKey;
 }