Example #1
0
        internal void SymmetricJwtTokenAuthenticationWithProviderConfiguration(IAppBuilder app)
        {
            string issuer           = "http://katanatesting.com/";
            var    signingAlgorithm = new AesManaged();

            var SymmetricJwtOptions = new JwtBearerAuthenticationOptions()
            {
                AllowedAudiences           = new string[] { issuer },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[] { new SymmetricKeyIssuerSecurityKeyProvider(issuer, signingAlgorithm.Key) },
                Provider = new OAuthBearerAuthenticationProvider()
                {
                    OnRequestToken = context =>
                    {
                        context.OwinContext.Set <bool>("OnRequestToken", true);
                        return(Task.FromResult(0));
                    },
                    OnValidateIdentity = context =>
                    {
                        context.OwinContext.Set <bool>("OnValidateIdentity", true);
                        return(Task.FromResult(0));
                    }
                }
            };

            //This test is to demonstrate the use of this extension method
            app.UseJwtBearerAuthentication(SymmetricJwtOptions);

            app.Map("/BearerAuthenticationToken", subApp =>
            {
                subApp.Run(async context =>
                {
                    var identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "test") }, SymmetricJwtOptions.AuthenticationType, ClaimTypes.Name, ClaimTypes.Role);
                    identity.AddClaim(new Claim(identity.RoleClaimType, "Guest", ClaimValueTypes.String));

                    var ticket = bool.Parse(context.Request.Query["issueExpiredToken"]) ?
                                 new AuthenticationTicket(identity, new AuthenticationProperties()
                    {
                        ExpiresUtc = DateTime.UtcNow
                    }) :
                                 new AuthenticationTicket(identity, new AuthenticationProperties()
                    {
                        ExpiresUtc = DateTime.UtcNow.AddYears(4)
                    });

                    var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                    await context.Response.WriteAsync(SecurityUtils.CreateJwtToken(ticket, issuer, signingCredentials));
                });
            });

            app.UseBearerApplication();
        }
        public void Security_SymmetricKeyTokenVerificationFact()
        {
            var issuer       = "http://katanatesting.com/";
            var sentIdentity = new ClaimsIdentity("CustomJwt", "MyNameClaimType", "MyRoleClaimType");

            sentIdentity.AddClaims(new Claim[] { new Claim("MyNameClaimType", "TestUser"), new Claim("MyRoleClaimType", "Administrator") });
            for (int i = 0; i < 5; i++)
            {
                sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
            }

            var authProperties = new AuthenticationProperties();
            var sentTicket     = new AuthenticationTicket(sentIdentity, authProperties);

            var signingAlgorithm          = new AesManaged();
            var signingCredentials        = new SigningCredentials(new SymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdentity.AuthenticationType
            };
            var formatter = new JwtFormat(tokenValidationParameters, new SymmetricKeyIssuerSecurityKeyProvider(issuer, signingAlgorithm.Key));

            formatter.TokenHandler = new JwtSecurityTokenHandler();

            var protectedtext = SecurityUtils.CreateJwtToken(sentTicket, issuer, signingCredentials);

            //Receive part
            var receivedTicket = formatter.Unprotect(protectedtext);

            var receivedClaims = receivedTicket.Identity.Claims;

            Assert.Equal("CustomJwt", receivedTicket.Identity.AuthenticationType);
            Assert.Equal(ClaimsIdentity.DefaultNameClaimType, receivedTicket.Identity.NameClaimType);
            Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, receivedTicket.Identity.RoleClaimType);
            Assert.NotNull(receivedTicket.Identity.BootstrapContext);
            Assert.NotNull((receivedTicket.Identity.BootstrapContext) as string);
            Assert.Equal(issuer, receivedClaims.Where <Claim>(claim => claim.Type == "iss").FirstOrDefault().Value);
            Assert.Equal(issuer, receivedClaims.Where <Claim>(claim => claim.Type == "aud").FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where <Claim>(claim => claim.Type == "exp").FirstOrDefault().Value);

            for (int i = 0; i < 5; i++)
            {
                sentIdentity.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
                Assert.Equal(i.ToString(), receivedClaims.Where <Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value);
            }

            Assert.Equal("TestUser", receivedClaims.Where <Claim>(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault().Value);
            Assert.Equal("Administrator", receivedClaims.Where <Claim>(claim => claim.Type == ClaimsIdentity.DefaultRoleClaimType).FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where <Claim>(claim => claim.Type == "iat").FirstOrDefault().Value);
            Assert.NotEmpty(receivedClaims.Where <Claim>(claim => claim.Type == "jti").FirstOrDefault().Value);
        }