Example #1
0
        internal static OAuthBearerAuthenticationOptions ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            var discoveryEndpoint = options.Authority.EnsureTrailingSlash();

            discoveryEndpoint += ".well-known/openid-configuration";

            var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                discoveryEndpoint,
                options,
                loggerFactory);

            var valParams = new TokenValidationParameters
            {
                ValidAudience = issuerProvider.Audience,
                NameClaimType = options.NameClaimType,
                RoleClaimType = options.RoleClaimType
            };

            var tokenFormat = new JwtFormat(valParams, issuerProvider);

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                AccessTokenFormat  = tokenFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Provider           = new ContextTokenProvider()
            };

            return(bearerOptions);
        }
 public OAuthOptions()
 {
     TokenEndpointPath = new PathString("/token");
     AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60);
     AccessTokenFormat = new JwtFormat(this);
     Provider = new OAuthProvider();
     AllowInsecureHttp = true;
 }
 public OAuthConfig()
 {
     TokenEndpointPath = new PathString("/token");
     AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(24*60);
     Provider = new SimpleOAuthProvider();
     AccessTokenFormat = new JwtFormat(this);
     // TODO: Don't allow this in production. ALWAYS USE SSL
     AllowInsecureHttp = true;
 }
        /// <summary>
        /// Adds Active Directory Federation Services (ADFS) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseActiveDirectoryFederationServicesBearerAuthentication(this IAppBuilder app, ActiveDirectoryFederationServicesBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var cachingSecurityTokenProvider = new WsFedCachingSecurityTokenProvider(options.MetadataEndpoint,
                    options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler);

#pragma warning disable 618
            JwtFormat jwtFormat = null;
            if (options.TokenValidationParameters != null)
            {
                if (!string.IsNullOrWhiteSpace(options.Audience))
                {
                    // Carry over obsolete property if set
                    if (string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
                    {
                        options.TokenValidationParameters.ValidAudience = options.Audience;
                    }
                    else if (options.TokenValidationParameters.ValidAudiences == null)
                    {
                        options.TokenValidationParameters.ValidAudiences = new[] { options.Audience };
                    }
                    else
                    {
                        options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Concat(new[] { options.Audience });
                    }
                }

                jwtFormat = new JwtFormat(options.TokenValidationParameters, cachingSecurityTokenProvider);
            }
            else
            {
                jwtFormat = new JwtFormat(options.Audience, cachingSecurityTokenProvider);
            }
#pragma warning restore 618
            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm,
                Provider = options.Provider,
                AccessTokenFormat = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
Example #5
0
        /// <summary>
        /// Adds Active Directory Federation Services (ADFS) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseActiveDirectoryFederationServicesBearerAuthentication(this IAppBuilder app, ActiveDirectoryFederationServicesBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var cachingSecurityTokenProvider = new WsFedCachingSecurityTokenProvider(options.MetadataEndpoint,
                                                                                     options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler);

#pragma warning disable 618
            JwtFormat jwtFormat = null;
            if (options.TokenValidationParameters != null)
            {
                if (!string.IsNullOrWhiteSpace(options.Audience))
                {
                    // Carry over obsolete property if set
                    if (string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
                    {
                        options.TokenValidationParameters.ValidAudience = options.Audience;
                    }
                    else if (options.TokenValidationParameters.ValidAudiences == null)
                    {
                        options.TokenValidationParameters.ValidAudiences = new[] { options.Audience };
                    }
                    else
                    {
                        options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Concat(new[] { options.Audience });
                    }
                }

                jwtFormat = new JwtFormat(options.TokenValidationParameters, cachingSecurityTokenProvider);
            }
            else
            {
                jwtFormat = new JwtFormat(options.Audience, cachingSecurityTokenProvider);
            }
#pragma warning restore 618
            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = options.Realm,
                Provider           = options.Provider,
                AccessTokenFormat  = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }
Example #6
0
        internal static void UseLocalValidation(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            var discoveryEndpoint = options.Authority;

            if (!discoveryEndpoint.EndsWith("/"))
            {
                discoveryEndpoint += "/";
            }

            discoveryEndpoint += ".well-known/openid-configuration";

            var provider = new DiscoveryCachingSecurityTokenProvider(
                discoveryEndpoint,
                options.BackchannelCertificateValidator,
                options.BackchannelHttpHandler);

            JwtFormat jwtFormat = null;

            if (options.TokenValidationParameters != null)
            {
                jwtFormat = new JwtFormat(options.TokenValidationParameters, provider);
            }
            else
            {
                var valParams = new TokenValidationParameters
                {
                    ValidAudience = provider.Audience,
                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType
                };

                jwtFormat = new JwtFormat(valParams, provider);
            }

            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = provider.Audience,
                Provider           = options.Provider,
                AccessTokenFormat  = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);
        }
        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);
        }
        public void Security_X509CertificateTokenVerificationFact()
        {
            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 signingCertificate = GetACertificateWithPrivateKey();
            var signingCredentials = new X509SigningCredentials(signingCertificate);
            var tokenValidationParameters = new TokenValidationParameters() { ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdentity.AuthenticationType };
            var formatter = new JwtFormat(tokenValidationParameters, new X509CertificateSecurityTokenProvider(issuer, signingCertificate));
            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<string>("CustomJwt", receivedTicket.Identity.AuthenticationType);
            Assert.Equal<string>(ClaimsIdentity.DefaultNameClaimType, receivedTicket.Identity.NameClaimType);
            Assert.Equal<string>(ClaimsIdentity.DefaultRoleClaimType, receivedTicket.Identity.RoleClaimType);
            Assert.NotNull(receivedTicket.Identity.BootstrapContext);
            Assert.NotNull(((BootstrapContext)receivedTicket.Identity.BootstrapContext).Token);
            Assert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "iss").FirstOrDefault().Value);
            Assert.Equal<string>(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<string>(i.ToString(), receivedClaims.Where<Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value);
            }

            Assert.Equal<string>("TestUser", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType).FirstOrDefault().Value);
            Assert.Equal<string>("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);
        }
Example #9
0
        public static IAppBuilder UseJwtBearerAuthenticationWithTokenProvider(this IAppBuilder app,
                                                                              JwtBearerTokenAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            JwtFormat jwtFormat;

            if (options.JwtBearerOptions.TokenValidationParameters != null)
            {
                jwtFormat = new JwtFormat(options.JwtBearerOptions.TokenValidationParameters);
            }
            else
            {
                jwtFormat = new JwtFormat(options.JwtBearerOptions.AllowedAudiences, options.JwtBearerOptions.IssuerSecurityTokenProviders);
            }
            if (options.JwtBearerOptions.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.JwtBearerOptions.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = options.JwtBearerOptions.Realm,
                Provider           = options.JwtBearerOptions.Provider,
                AccessTokenFormat  = jwtFormat,
                AuthenticationMode = options.JwtBearerOptions.AuthenticationMode,
                AuthenticationType = options.JwtBearerOptions.AuthenticationType,
                Description        = options.JwtBearerOptions.Description
            };

            bearerOptions.AccessTokenProvider = new JwtBearerTokenProvider(options.JwtOptions);

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }
        internal static Lazy <OAuthBearerAuthenticationOptions> ConfigureLocalValidation(
            BearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return(new Lazy <OAuthBearerAuthenticationOptions>(() =>
            {
                // use discovery endpoint
                if (string.IsNullOrWhiteSpace(options.Authority))
                {
                    throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                }

                var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                discoveryEndpoint += ".well-known/openid-configuration";

                IIssuerSecurityKeyProvider issuerProvider = new DiscoveryDocumentIssuerSecurityKeyProvider(
                    discoveryEndpoint,
                    options,
                    loggerFactory);

                var valParams = new TokenValidationParameters
                {
                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType
                };

                valParams.IssuerSigningKeyResolver = ResolveRsaKeys;
                valParams.ValidateAudience = false;


                var tokenFormat = new JwtFormat(valParams, issuerProvider);

                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;
            }, LazyThreadSafetyMode.PublicationOnly));
        }
        public static IAppBuilder UseJwtBearerAuthenticationWithTokenProvider(this IAppBuilder app,
            JwtBearerTokenAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            JwtFormat jwtFormat;
            if (options.JwtBearerOptions.TokenValidationParameters != null)
            {
                jwtFormat = new JwtFormat(options.JwtBearerOptions.TokenValidationParameters);
            }
            else
            {
                jwtFormat = new JwtFormat(options.JwtBearerOptions.AllowedAudiences, options.JwtBearerOptions.IssuerSecurityTokenProviders);
            }
            if (options.JwtBearerOptions.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.JwtBearerOptions.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.JwtBearerOptions.Realm,
                Provider = options.JwtBearerOptions.Provider,
                AccessTokenFormat = jwtFormat,
                AuthenticationMode = options.JwtBearerOptions.AuthenticationMode,
                AuthenticationType = options.JwtBearerOptions.AuthenticationType,
                Description = options.JwtBearerOptions.Description
            };

            bearerOptions.AccessTokenProvider = new JwtBearerTokenProvider(options.JwtOptions);

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
        /// <summary>
        /// Validates the specified JWT and builds an AuthenticationTicket from it.
        /// </summary>
        /// <param name="protectedText">The JWT to validate.</param>
        /// <returns>An AuthenticationTicket built from the <paramref name="protectedText"/>.</returns>
        /// <exception cref="T:System.ArgumentNullException">
        /// Thrown if the <paramref name="protectedText"/> is null or empty.
        /// </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        /// Thrown if the <paramref name="protectedText"/> is not a JWT.
        /// </exception>
        public AuthenticationTicket Unprotect(string protectedText)
        {
            if (string.IsNullOrWhiteSpace(protectedText))
            {
                throw new ArgumentNullException(nameof(protectedText));
            }

            var jwt = this.privateKey != null?JWT.Decode(protectedText, this.privateKey) : protectedText;

            var securityTokenProviders = this.settings.AllowedServers.Select(
                server => new Microsoft.Owin.Security.Jwt.SymmetricKeyIssuerSecurityTokenProvider(
                    server.Issuer,
                    TextEncodings.Base64Url.Decode(server.Secret)));

            var jwtFormat = new JwtFormat(this.settings.AllowedClients, securityTokenProviders);

            var ticket = jwtFormat.Unprotect(jwt);

            return(ticket);
        }
        /*
         * Configure the authorization OWIN middleware
         */
        public void Configure(IAppBuilder app)
        {
            // Retrieve settings from web.settings (actually, web.settings.appSettings.exclude):
            // We want the ClientId / CallbackUri relevent to this API service
            _ib2COidcConfidentialClientSettingsConfiguration = this._keyVaultService
                                                               .GetObject <AuthBearerTokenSettingsConfiguration>("bearerTokenAuth:");


            // Configuring with an B2C url similar to:
            // https://login.microsoftonline.com/{authorityTenantName}/v2.0/.well-known/openid-configuration
            var openIdConnectCachingSecurityTokenProvider =
                new OpenIdConnectCachingSecurityTokenProvider(
                    _ib2COidcConfidentialClientSettingsConfiguration.AuthorityUri,
                    _ib2COidcConfidentialClientSettingsConfiguration.PolicyIdB2C);



            // TokenValidationParameters: parameters used by System.IdentityModel.Tokens.SecurityTokenHandler validating System.IdentityModel.Tokens.SecurityToken.
            var tvps = new TokenValidationParameters()
            {
                // Accept only those tokens where the audience of the token is equal to the client ID of this app
                ValidAudiences = GetValidAudiences(),
                // ensure that issuers are only what we deem are necessary, maybe dont want this in the future
                ValidIssuers = GetValidIssuers(openIdConnectCachingSecurityTokenProvider.Issuer),
            };


            var accessTokenFormat = new JwtFormat(tvps, openIdConnectCachingSecurityTokenProvider);

            // We're using OIDC, but that's really just a formal extension to OAuth, so tell the OWIN
            // pipeline that we're adding an auth handler.
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                // This SecurityTokenProvider fetches the Azure AD B2C metadata & signing keys from the OpenIDConnect metadata endpoint
                AccessTokenFormat = accessTokenFormat,
                Provider          = new OAuthBearerUserAuthenticationProvider(_oidcNotificationHandlerService)
            });
        }
Example #14
0
        public async Task RequestToken_ValidateUsingExposedPublicKey_ValidationSucceded()
        {
            var mockServer = new MockIdentityServer();
            var token      = await mockServer.GetTokenForUser("blah");

            var valParams = new TokenValidationParameters {
                IssuerSigningKeyResolver =
                    (t, securityToken, keyIdentifier, validationParameters) =>
                {
                    var kid =
                        keyIdentifier.OfType <NamedKeySecurityKeyIdentifierClause>()
                        .Where(identifier => identifier.Name.Equals("kid"))
                        .Select(identifier => identifier.Id)
                        .Single();
                    return(validationParameters.IssuerSigningTokens.Single(key => key.Id == kid).SecurityKeys.First());
                },
                ValidAudience = "http://localhost/resources"
            };

            var format = new JwtFormat(valParams, new Provider((await mockServer.GetPublicKeys()).Keys));

            format.Unprotect(token);
        }
Example #15
0
        public void ProtectShouldThrowNotImplementedException()
        {
            var instance = new JwtFormat("http://contoso.com", new TestIssuerSecurityTokenProvider("urn:issuer"));

            Should.Throw<NotSupportedException>(() => instance.Protect(null));
        }
        internal static OAuthBearerAuthenticationOptions ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
            discoveryEndpoint += ".well-known/openid-configuration";

            var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                discoveryEndpoint,
                options,
                loggerFactory);

            var valParams = new TokenValidationParameters
            {
                ValidAudience = issuerProvider.Audience,
                NameClaimType = options.NameClaimType,
                RoleClaimType = options.RoleClaimType
            };

            var tokenFormat = new JwtFormat(valParams, issuerProvider);

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                AccessTokenFormat = tokenFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Provider = options.TokenProvider ?? new ContextTokenProvider(),
            };

            return bearerOptions;
        }
        internal static OAuthBearerAuthenticationOptions ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            JwtFormat tokenFormat = null;

            // use static configuration
            if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                options.SigningCertificate != null)
            {
                var audience = options.IssuerName.EnsureTrailingSlash();
                audience += "resources";

                var valParams = new TokenValidationParameters
                { 
                    ValidIssuer = options.IssuerName,
                    ValidAudience = audience,
                    IssuerSigningToken = new X509SecurityToken(options.SigningCertificate),

                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType,
                };

                tokenFormat = new JwtFormat(valParams);
            }
            else
            {
                // use discovery endpoint
                if (string.IsNullOrWhiteSpace(options.Authority))
                {
                    throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                }

                var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                discoveryEndpoint += ".well-known/openid-configuration";

                var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                    discoveryEndpoint,
                    options,
                    loggerFactory);

                var valParams = new TokenValidationParameters
                {
                    ValidAudience = issuerProvider.Audience,
                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType
                };

                tokenFormat = new JwtFormat(valParams, issuerProvider);
            }
            

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                AccessTokenFormat = tokenFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Provider = new ContextTokenProvider()
            };

            if (options.TokenProvider != null)
            {
                bearerOptions.Provider = options.TokenProvider;
            }

            return bearerOptions;
        }
        internal static Lazy <OAuthBearerAuthenticationOptions> ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return(new Lazy <OAuthBearerAuthenticationOptions>(() =>
            {
                JwtFormat tokenFormat = null;

                // use static configuration
                if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                    options.SigningCertificate != null)
                {
                    string audience = null;
                    bool validateAudience = true;

                    // if API name is set, do a strict audience check for
                    //https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation/blob/677bf6863a27c851270436faf9dfac437f46d90d/src/IdentityServerAuthenticationOptions.cs#L192
                    if (!string.IsNullOrWhiteSpace(options.ApiName) && !options.LegacyAudienceValidation)
                    {
                        audience = options.ApiName;
                    }
                    else if (options.LegacyAudienceValidation)
                    {
                        audience = options.IssuerName.EnsureTrailingSlash() + "resources";
                    }
                    else
                    {
                        // no audience validation, rely on scope checks only
                        validateAudience = false;
                    }

                    var valParams = new TokenValidationParameters
                    {
                        ValidIssuer = options.IssuerName,
                        ValidAudience = audience,
                        ValidateAudience = validateAudience,
                        IssuerSigningKey = new X509SecurityKey(options.SigningCertificate),
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                    };

                    tokenFormat = new JwtFormat(valParams);
                }
                else
                {
                    // use discovery endpoint
                    if (string.IsNullOrWhiteSpace(options.Authority))
                    {
                        throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                    }

                    var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                    discoveryEndpoint += ".well-known/openid-configuration";

                    var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                        discoveryEndpoint,
                        options,
                        loggerFactory);


                    string audience = issuerProvider.Audience;
                    bool validateAudience = true;

                    // if API name is set, do a strict audience check for
                    //https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation/blob/677bf6863a27c851270436faf9dfac437f46d90d/src/IdentityServerAuthenticationOptions.cs#L192
                    if (string.IsNullOrWhiteSpace(audience) && !options.LegacyAudienceValidation)
                    {
                        // no audience validation, rely on scope checks only
                        validateAudience = false;
                    }


                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = audience,
                        ValidateAudience = validateAudience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    if (options.IssuerSigningKeyResolver != null)
                    {
                        valParams.IssuerSigningKeyResolver = options.IssuerSigningKeyResolver;
                    }
                    else
                    {
                        valParams.IssuerSigningKeyResolver = IssuerSigningKeyResolver;
                    }

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }


                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;
            }, LazyThreadSafetyMode.PublicationOnly));
        }
Example #19
0
        public void ProtectShouldThrowNotImplementedException()
        {
            var instance = new JwtFormat("http://contoso.com", new TestIssuerSecurityTokenProvider("urn:issuer"));

            Should.Throw <NotSupportedException>(() => instance.Protect(null));
        }
Example #20
0
        public void HandlerConstructorShouldNotThrowWithValidValues()
        {
            var instance = new JwtFormat("http://audience/", new TestIssuerSecurityTokenProvider("urn:issuer"));

            instance.ShouldNotBe(null);
        }
        internal static void UseLocalValidation(this IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            JwtFormat tokenFormat = null;

            // use discovery document to fully configure middleware
            if (!string.IsNullOrEmpty(options.Authority))
            {
                var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                discoveryEndpoint += ".well-known/openid-configuration";

                var issuerProvider = new CachingDiscoveryIssuerSecurityTokenProvider(
                    discoveryEndpoint,
                    options);

                if (options.TokenValidationParameters != null)
                {
                    tokenFormat = new JwtFormat(options.TokenValidationParameters, issuerProvider);
                }
                else
                {
                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = issuerProvider.Audience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }
            }
            // use token validation parameters
            else if (options.TokenValidationParameters != null)
            {
                tokenFormat = new JwtFormat(options.TokenValidationParameters);
            }
            // use simplified manual configuration
            else
            {
                var valParams = new TokenValidationParameters
                {
                    ValidIssuer = options.IssuerName,
                    ValidAudience = options.IssuerName.EnsureTrailingSlash() + "resources",
                    IssuerSigningToken = new X509SecurityToken(options.IssuerCertificate),
                    NameClaimType = options.NameClaimType,
                    RoleClaimType = options.RoleClaimType
                };

                tokenFormat = new JwtFormat(valParams);
            }

            if (options.TokenHandler != null)
            {
                tokenFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Provider = options.Provider,
                AccessTokenFormat = tokenFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            var issuer     = "http://localhost:51912/";                                                           //发行者
            var audience   = "fNm0EDIXbfuuDowUpAoq5GTEiywV8eg0TpiIVnV8";                                          //观众
            var secret     = TextEncodings.Base64Url.Decode(OAuthCommon.Constants.Consts.JWT.Security.SecretKey); //秘钥
            var signingKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(secret);

            //令牌验证参数
            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = "http://localhost:51912/",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = false,
                ValidAudience    = audience,

                // Validate the token expiry
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            //配置JwtBearer授权中间件   这个中间件的作用主要是解决由JWT方式提供的身份认证。算是Resource资源,认证服务器需要另外开发
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
            {
                TokenValidationParameters = tokenValidationParameters,
                AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType        = "Bearer",
                AllowedAudiences          = new[] { audience },
                Description = new AuthenticationDescription(),
                Realm       = "",//领域,范围;
                Provider    = new OAuthBearerAuthenticationProvider()
                {
                    //验证当前访客身份
                    OnValidateIdentity = context =>
                    {
                        AuthenticationTicket ticket = context.Ticket;

                        //校验身份是否过期
                        if (ticket.Properties.ExpiresUtc < DateTime.Now)
                        {
                            context.SetError("the token has expired!");
                            context.Rejected();
                        }
                        else
                        {
                            context.Validated(ticket);
                        }
                        return(Task.FromResult <object>(context));
                    },

                    //处理授权令牌 OAuthBearerAuthenticationHandler
                    //headers Authorization=Bear:token
                    OnRequestToken = (context) =>
                    {
                        context.Token = context.Token ?? context.Request.Query["access_token"];
                        if (context.Token != null)
                        {
                            context.Response.Headers["WWW-Authorization"] = "Bearer";
                            //protector
                            IDataProtector protector   = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
                            JwtFormat ticketDataFormat = new JwtFormat(tokenValidationParameters);

                            var ticket           = ticketDataFormat.Unprotect(context.Token);//从令牌字符串中,获取授权票据
                            context.Request.User = new ClaimsPrincipal(ticket.Identity);
                        }
                        return(Task.FromResult <object>(context));
                    },
                    OnApplyChallenge = (context) => { return(Task.FromResult <object>(context)); }
                },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret) //对称加密
                }
            });
        }
Example #23
0
        public void HandlerConstructorShouldNotThrowWithValidValues()
        {
            var instance = new JwtFormat("http://audience/", new TestIssuerSecurityTokenProvider("urn:issuer"));

            instance.ShouldNotBe(null);
        }
        internal static Lazy <OAuthBearerAuthenticationOptions> ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return(new Lazy <OAuthBearerAuthenticationOptions>(() =>
            {
                JwtFormat tokenFormat = null;

                // use static configuration
                if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                    options.SigningCertificate != null)
                {
                    var audience = options.IssuerName.EnsureTrailingSlash();
                    audience += "resources";

                    var valParams = new TokenValidationParameters
                    {
                        ValidIssuer = options.IssuerName,
                        ValidAudience = audience,
                        IssuerSigningKey = new X509SecurityKey(options.SigningCertificate),

                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                    };

                    tokenFormat = new JwtFormat(valParams);
                }
                else
                {
                    // use discovery endpoint
                    if (string.IsNullOrWhiteSpace(options.Authority))
                    {
                        throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                    }

                    var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                    discoveryEndpoint += ".well-known/openid-configuration";

                    var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                        discoveryEndpoint,
                        options,
                        loggerFactory);

                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = issuerProvider.Audience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    if (options.IssuerSigningKeyResolver != null)
                    {
                        valParams.IssuerSigningKeyResolver = options.IssuerSigningKeyResolver;
                    }
                    else
                    {
                        valParams.IssuerSigningKeyResolver = ResolveRsaKeys;
                    }

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }


                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;
            }, LazyThreadSafetyMode.PublicationOnly));
        }
        internal static Lazy <OAuthBearerAuthenticationOptions> ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return(new Lazy <OAuthBearerAuthenticationOptions>(() =>
            {
                JwtFormat tokenFormat = null;

                // use static configuration
                if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                    options.SigningCertificate != null)
                {
                    // IdSrv3 hard-codes the value when issuing a token using the pattern below
                    var audience = options.IssuerName.EnsureTrailingSlash() + "resources";

                    // Use the configured values if present, otherwise fallback to the defaulted value
                    List <string> validAudiences;
                    if (options.ValidAudiences != null && options.ValidAudiences.Count() > 0)
                    {
                        validAudiences = new List <string>(options.ValidAudiences);
                    }
                    else
                    {
                        validAudiences = new List <string>()
                        {
                            audience
                        }
                    };

                    var valParams = new TokenValidationParameters
                    {
                        ValidIssuer = options.IssuerName,
                        ValidAudiences = validAudiences,
                        ValidateAudience = true,
                        IssuerSigningKey = new X509SecurityKey(options.SigningCertificate),
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                    };

                    tokenFormat = new JwtFormat(valParams);
                }
                else
                {
                    // use discovery endpoint
                    if (string.IsNullOrWhiteSpace(options.Authority))
                    {
                        throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                    }

                    var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                    discoveryEndpoint += ".well-known/openid-configuration";

                    var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                        discoveryEndpoint,
                        options,
                        loggerFactory);

                    // Use the configured values if present, otherwise fallback to the discovery document's value
                    // (which is actually hard-coded to _issuer + "/resources")
                    List <string> validAudiences;
                    if (options.ValidAudiences != null && options.ValidAudiences.Count() > 0)
                    {
                        validAudiences = new List <string>(options.ValidAudiences);
                    }
                    else
                    {
                        validAudiences = new List <string>()
                        {
                            issuerProvider.Audience
                        }
                    };

                    var valParams = new TokenValidationParameters
                    {
                        ValidAudiences = validAudiences,
                        ValidateAudience = true,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    if (options.IssuerSigningKeyResolver != null)
                    {
                        valParams.IssuerSigningKeyResolver = options.IssuerSigningKeyResolver;
                    }
                    else
                    {
                        valParams.IssuerSigningKeyResolver = IssuerSigningKeyResolver;
                    }

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }


                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;
            }, LazyThreadSafetyMode.PublicationOnly));
        }
        /// <summary>
        /// Adds Windows Azure Active Directory (WAAD) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseWindowsAzureActiveDirectoryBearerAuthentication(this IAppBuilder app, WindowsAzureActiveDirectoryBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (string.IsNullOrWhiteSpace(options.MetadataAddress))
            {
                if (string.IsNullOrWhiteSpace(options.Tenant))
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "Tenant"));
                }
                options.MetadataAddress = string.Format(CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, options.Tenant);
            }

            var cachingSecurityTokenProvider = new WsFedCachingSecurityKeyProvider(options.MetadataAddress,
                                                                                   options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler);

#pragma warning disable 618
            JwtFormat jwtFormat = null;
            if (options.TokenValidationParameters != null)
            {
                if (!string.IsNullOrWhiteSpace(options.Audience))
                {
                    // Carry over obsolete property if set
                    if (string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
                    {
                        options.TokenValidationParameters.ValidAudience = options.Audience;
                    }
                    else if (options.TokenValidationParameters.ValidAudiences == null)
                    {
                        options.TokenValidationParameters.ValidAudiences = new[] { options.Audience };
                    }
                    else
                    {
                        options.TokenValidationParameters.ValidAudiences = options.TokenValidationParameters.ValidAudiences.Concat(new[] { options.Audience });
                    }
                }

                jwtFormat = new JwtFormat(options.TokenValidationParameters, cachingSecurityTokenProvider);
            }
            else
            {
                jwtFormat = new JwtFormat(options.Audience, cachingSecurityTokenProvider);
            }
#pragma warning restore 618
            if (options.TokenHandler != null)
            {
                jwtFormat.TokenHandler = options.TokenHandler;
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = options.Realm,
                Provider           = options.Provider,
                AccessTokenFormat  = jwtFormat,
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }