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);
        }
        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);
        }
            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);
                }));
            }
        public void UseMobileAppAuthentication_ConfiguresServiceAuthentication_WhenAuthEnabled()
        {
            // Arrange
            MobileAppConfiguration configOptions = new MobileAppConfiguration();

            this.config.SetMobileAppConfiguration(configOptions);
            MobileAppAuthenticationOptions options = null;

            this.appBuilderMock.Setup(a => a.Properties)
            .Returns(new Dictionary <string, object>
            {
                { "integratedpipeline.StageMarker", (Action <IAppBuilder, string>)((app, stageName) => { }) }
            });
            this.appBuilderMock.Setup(p => p.Use(It.IsAny <object>(), It.IsAny <object[]>()))
            .Callback <object, object[]>((mockObject, mockArgs) =>
            {
                options = (MobileAppAuthenticationOptions)mockArgs[1];
            })
            .Returns(this.appBuilder)
            .Verifiable();

            // Act
            this.appBuilder.UseMobileAppAuthentication(this.config);

            // Assert
            // We expect three pieces of middleware to be added
            this.appBuilderMock.Verify(p => p.Use(It.IsAny <object>(), It.IsAny <object[]>()), Times.Once);
            Assert.Equal("Service", options.Realm);
            Assert.Equal("MobileApp", options.AuthenticationType);
        }
Exemple #5
0
        /// <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);
        }
Exemple #6
0
        public static IAppBuilder UseMobileAppAuthentication(this IAppBuilder appBuilder, HttpConfiguration config, AuthenticationMode mode = AuthenticationMode.Active)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException("appBuilder");
            }

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

            // Add the service authentication middleware
            MobileAppAuthenticationOptions serviceOptions = GetMobileAppAuthenticationOptions(config, mode);
            IMobileAppTokenHandler         tokenHandler   = config.GetMobileAppTokenHandler();

            appBuilder.UseMobileAppAuthentication(serviceOptions, tokenHandler);

            return(appBuilder);
        }
        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 new bool TryParseLoginToken(string token, MobileAppAuthenticationOptions options, out ClaimsPrincipal claimsPrincipal)
 {
     return(base.TryParseLoginToken(token, options, out claimsPrincipal));
 }
 public new AuthenticationTicket Authenticate(IOwinRequest request, MobileAppAuthenticationOptions options)
 {
     return(base.Authenticate(request, options));
 }
        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);
                }
            }
        }
Exemple #11
0
        /// <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);
        }
Exemple #12
0
        public void SkipTokenSignatureValidation_DefaultsFalse()
        {
            var opt = new MobileAppAuthenticationOptions();

            Assert.False(opt.SkipTokenSignatureValidation);
        }
Exemple #13
0
 public MobileAppAuthenticationOptionsTests()
 {
     this.options            = new MobileAppAuthenticationOptions();
     this.options.SigningKey = SigningKey;
 }