public static IAppBuilder UseAppServiceAuthentication(this IAppBuilder appBuilder, HttpConfiguration config, AppServiceAuthenticationMode appServiceAuthMode, MobileAppAuthenticationOptions options, IMobileAppTokenHandler tokenHandler)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException("appBuilder");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
            bool runningInAzure = !string.IsNullOrEmpty(settings.HostName);

            if ((appServiceAuthMode == AppServiceAuthenticationMode.LocalOnly && !runningInAzure)
                            || appServiceAuthMode == AppServiceAuthenticationMode.Always)
            {
                appBuilder.Use(typeof(MobileAppAuthenticationMiddleware), new object[]
                {
                    appBuilder,
                    options,
                    tokenHandler
                });
            }
            return appBuilder;
        }
        /// <summary>
        /// Gets the <see cref="MobileAppAuthenticationOptions" /> that will be used by the <see cref="MobileAppAuthenticationHandler"/>./>
        /// </summary>
        /// <returns>The <see cref="MobileAppAuthenticationOptions" /> to use.</returns>
        private static MobileAppAuthenticationOptions GetMobileAppAuthenticationOptions(HttpConfiguration config, AuthenticationMode mode)
        {
            IMobileAppSettingsProvider settingsProvider = config.GetMobileAppSettingsProvider();
            MobileAppSettingsDictionary settings = settingsProvider.GetMobileAppSettings();

            MobileAppAuthenticationOptions serviceOptions = new MobileAppAuthenticationOptions
            {
                AuthenticationMode = mode,
                SigningKey = settings.SigningKey,
            };

            return serviceOptions;
        }
        /// <summary>
        /// Adds authentication using the built-in <see cref="MobileAppAuthenticationMiddleware"/> authentication model.
        /// </summary>
        /// <param name="appBuilder">The <see cref="IAppBuilder"/> passed to the configuration method.</param>
        /// <param name="options">Middleware configuration options.</param>
        /// <param name="tokenHandler">An <see cref="MobileAppTokenHandler"/> instance.</param>
        /// <returns>The updated <see cref="IAppBuilder"/>.</returns>
        public static IAppBuilder UseMobileAppAuthentication(this IAppBuilder appBuilder, MobileAppAuthenticationOptions options, IMobileAppTokenHandler tokenHandler)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException("appBuilder");
            }

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

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

            return appBuilder;
        }
 private MobileAppAuthenticationOptions CreateTestOptions()
 {
     MobileAppAuthenticationOptions options = new MobileAppAuthenticationOptions
     {
         SigningKey = TestSigningKey,
     };
     return options;
 }
 public new AuthenticationTicket Authenticate(IOwinRequest request, MobileAppAuthenticationOptions options)
 {
     return base.Authenticate(request, options);
 }
        private static MobileAppAuthenticationOptions CreateTestOptions(string signingKey = null)
        {
            MobileAppAuthenticationOptions options = new MobileAppAuthenticationOptions
            {
                SigningKey = signingKey,
            };

            if (string.IsNullOrEmpty(signingKey))
            {
                options.SigningKey = SigningKeyAlpha;
            }
            return options;
        }
 public void SkipTokenSignatureValidation_DefaultsFalse()
 {
     var opt = new MobileAppAuthenticationOptions();
     Assert.False(opt.SkipTokenSignatureValidation);
 }
 public MobileAppAuthenticationOptionsTests()
 {
     this.options = new MobileAppAuthenticationOptions();
     this.options.SigningKey = SigningKey;
 }
 public new bool TryParseLoginToken(string token, MobileAppAuthenticationOptions options, out ClaimsPrincipal claimsPrincipal)
 {
     return base.TryParseLoginToken(token, options, out claimsPrincipal);
 }
 private void ValidateLoginToken(string token, MobileAppAuthenticationOptions options)
 {
     // validate the token and get the claims principal
     ClaimsPrincipal claimsPrincipal = null;
     Assert.True(this.tokenHandler.TryValidateLoginToken(token, options.SigningKey, TestWebsiteUrl, TestWebsiteUrl, out claimsPrincipal));
 }
        public void Authenticate_CorrectlyAuthenticates(MobileAppAuthenticationOptions options, bool expectAuthenticated)
        {
            // Arrange
            var mock = new MobileAppAuthenticationHandlerMock(this.loggerMock.Object, this.tokenHandler);
            var request = CreateAuthRequest("signing_key");
            request.User = new ClaimsPrincipal();

            // Act
            mock.Authenticate(request, options);

            // Assert            
            if (expectAuthenticated)
            {
                Assert.NotNull(request.User.Identity);
                Assert.True(request.User.Identity.IsAuthenticated);
                Assert.IsType(typeof(MobileAppUser), request.User);
            }
            else
            {
                Assert.Null(request.User);
            }
        }
        public void TryParseLoginToken_ReturnsSameClaimsIdentity_WhetherValidatingTokensOrNot()
        {
            // Arrange
            MobileAppAuthenticationOptions options = new MobileAppAuthenticationOptions();
            options.SigningKey = "SOME_SIGNING_KEY";
            // SkipTokenSignatureValidation defaults to false
            JwtSecurityToken token = GetTestToken(options.SigningKey);

            MobileAppAuthenticationOptions skipOptions = new MobileAppAuthenticationOptions();
            skipOptions.SigningKey = "SOME_SIGNING_KEY";
            skipOptions.SkipTokenSignatureValidation = true;
            JwtSecurityToken skipToken = GetTestToken("SOME_OTHER_KEY");

            // Act
            ClaimsPrincipal claimsPrincipal;
            this.handlerMock.TryParseLoginToken(token.RawData, options, out claimsPrincipal);
            Assert.True(claimsPrincipal.Identity.IsAuthenticated);

            ClaimsPrincipal skipClaimsPrincipal;
            this.handlerMock.TryParseLoginToken(skipToken.RawData, skipOptions, out skipClaimsPrincipal);
            Assert.True(claimsPrincipal.Identity.IsAuthenticated);

            // Assert
            ClaimsIdentity claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
            ClaimsIdentity skipClaimsIdentity = (ClaimsIdentity)skipClaimsPrincipal.Identity;

            Assert.Equal(claimsIdentity.Actor, skipClaimsIdentity.Actor);
            Assert.Equal(claimsIdentity.AuthenticationType, skipClaimsIdentity.AuthenticationType);
            Assert.Equal(claimsIdentity.BootstrapContext, skipClaimsIdentity.BootstrapContext);
            Assert.Equal(claimsIdentity.IsAuthenticated, skipClaimsIdentity.IsAuthenticated);
            Assert.Equal(claimsIdentity.Label, skipClaimsIdentity.Label);
            Assert.Equal(claimsIdentity.Name, skipClaimsIdentity.Name);
            Assert.Equal(claimsIdentity.NameClaimType, skipClaimsIdentity.NameClaimType);
            Assert.Equal(claimsIdentity.RoleClaimType, skipClaimsIdentity.RoleClaimType);
            Assert.Equal(claimsIdentity.Claims.Count(), skipClaimsIdentity.Claims.Count());
            Claim[] claims = claimsIdentity.Claims.OrderBy(c => c.Type).ToArray();
            Claim[] skipClaims = skipClaimsIdentity.Claims.OrderBy(c => c.Type).ToArray();
            for (int i = 0; i < claims.Length; i++)
            {
                Claim claim = claims[i];
                Claim skipClaim = skipClaims[i];
                Assert.Equal(claim.Type, skipClaim.Type);
                Assert.Equal(claim.Issuer, skipClaim.Issuer);
                Assert.Equal(claim.OriginalIssuer, skipClaim.OriginalIssuer);
                Assert.Equal(claim.Subject, claimsIdentity);
                Assert.Equal(skipClaim.Subject, skipClaimsIdentity);
                Assert.Equal(claim.ValueType, skipClaim.ValueType);
                Assert.Equal(claim.Properties.Count, skipClaim.Properties.Count);
                if (claim.Type == "nbf")
                {
                    // nbf can be slightly off
                    int claimNbf = Int32.Parse(claim.Value);
                    int skipClaimNbf = Int32.Parse(skipClaim.Value);
                    Assert.True(Math.Abs(claimNbf - skipClaimNbf) < 10);
                }
                else
                {
                    Assert.Equal(claim.Value, skipClaim.Value);
                }
            }
        }
        public void TryParseLoginToken_NoTokenValidation_ReturnsExpectedClaims()
        {
            // Arrange
            Mock<MobileAppTokenHandler> tokenHandlerMock = new Mock<MobileAppTokenHandler>(this.config);
            MobileAppAuthenticationHandlerMock authHandlerMock = new MobileAppAuthenticationHandlerMock(this.loggerMock.Object, tokenHandlerMock.Object);
            MobileAppAuthenticationOptions skipOptions = new MobileAppAuthenticationOptions();
            skipOptions.SigningKey = "SOME_SIGNING_KEY";
            skipOptions.SkipTokenSignatureValidation = true;

            JwtSecurityToken skipToken = GetTestToken("SOME_OTHER_KEY");

            // Act
            ClaimsPrincipal skipClaimsPrincipal;
            bool skipResult = authHandlerMock.TryParseLoginToken(skipToken.RawData, skipOptions, out skipClaimsPrincipal);

            // Assert
            tokenHandlerMock.Verify(h => h.TryValidateLoginToken(It.IsAny<string>(), It.IsAny<string>(), out skipClaimsPrincipal), Times.Never);
            Assert.True(skipResult);
            MobileAppUser user = this.tokenHandler.CreateServiceUser((ClaimsIdentity)skipClaimsPrincipal.Identity, skipToken.RawData);

            Assert.Equal("Facebook:1234", user.Id);
            Assert.True(user.Identity.IsAuthenticated);

            Claim[] claims = user.Claims.ToArray();
            Assert.Equal(8, claims.Length);
            Assert.Equal("Frank", claims.Single(p => p.Type == ClaimTypes.GivenName).Value);
            Assert.Equal("Miller", claims.Single(p => p.Type == ClaimTypes.Surname).Value);
            Assert.Equal("Admin", claims.Single(p => p.Type == ClaimTypes.Role).Value);
            Assert.Equal("Facebook:1234", claims.Single(p => p.Type == "uid").Value);
            Assert.Equal("MyClaimValue", claims.Single(p => p.Type == "my_custom_claim").Value);
        }
        public void TryParseLoginToken_ReturnsExpectedClaims()
        {
            // Arrange
            MobileAppAuthenticationOptions options = new MobileAppAuthenticationOptions();
            options.SigningKey = "SOME_SIGNING_KEY";
            // SkipTokenSignatureValidation defaults to false
            JwtSecurityToken token = GetTestToken(options.SigningKey);

            // Act
            ClaimsPrincipal claimsPrincipal;
            bool result = this.handlerMock.TryParseLoginToken(token.RawData, options, out claimsPrincipal);

            // Assert
            Assert.True(result);
            MobileAppUser user = this.tokenHandler.CreateServiceUser((ClaimsIdentity)claimsPrincipal.Identity, token.RawData);
            Assert.Equal("Facebook:1234", user.Id);
            Assert.True(user.Identity.IsAuthenticated);

            Claim[] claims = user.Claims.ToArray();
            Assert.Equal(8, claims.Length);
            Assert.Equal("Frank", claims.Single(p => p.Type == ClaimTypes.GivenName).Value);
            Assert.Equal("Miller", claims.Single(p => p.Type == ClaimTypes.Surname).Value);
            Assert.Equal("Admin", claims.Single(p => p.Type == ClaimTypes.Role).Value);
            Assert.Equal("Facebook:1234", claims.Single(p => p.Type == "uid").Value);
            Assert.Equal("MyClaimValue", claims.Single(p => p.Type == "my_custom_claim").Value);
        }
            private TestServer CreateTestServer(HttpConfiguration config, bool skipTokenSignatureValidation)
            {
                config.MapHttpAttributeRoutes();

                new MobileAppConfiguration()
                    .MapApiControllers()
                    .AddTables(
                        new MobileAppTableConfiguration()
                        .MapTableControllers())
                    .ApplyTo(config);

                // setup test authorization config values
                IMobileAppSettingsProvider settingsProvider = config.GetMobileAppSettingsProvider();
                var settings = settingsProvider.GetMobileAppSettings();
                settings.SigningKey = "signing_key";

                return TestServer.Create((appBuilder) =>
                {
                    MobileAppAuthenticationOptions options = new MobileAppAuthenticationOptions()
                    {
                        SigningKey = settings.SigningKey,
                        SkipTokenSignatureValidation = skipTokenSignatureValidation
                    };

                    appBuilder.UseMobileAppAuthentication(options, config.GetMobileAppTokenHandler());
                    appBuilder.UseWebApi(config);
                });
            }