public void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new AuthContext());
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            var issuer   = ConfigurationManager.AppSettings["as:Domain"];
            var audience = ConfigurationManager.AppSettings["as:AudienceId"];
            var secret   = ConfigurationManager.AppSettings["as:AudienceSecret"];

            byte[] arSecrect = TextEncodings.Base64Url.Decode(secret);

            #region Jwt驗證組態

            JwtBearerAuthenticationOptions options = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = Microsoft.Owin.Security.AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, arSecrect) }
            };

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(options);

            #endregion Jwt驗證組態
        }
Beispiel #2
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var authServerOptions = new OAuthAuthorizationServerOptions()
            {
                //请求路径,客户端应用程序将通过该路径重定向用户代理以获取用户对颁发令牌的同意。
                TokenEndpointPath = new PathString("/token"),
                //令牌过期时间 30分钟过期
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                //AccessTokenFormat = new JwtFormat(new TokenValidationParameters()),
                //处理授权服务
                Provider = new MyOAuthAuthorizationServerProvider(),
                //生成Jwt令牌
                AccessTokenFormat = new MyJwtTokenFormat(),
#if DEBUG
                AllowInsecureHttp = true
#endif
            };

            var jwtOptions = new JwtBearerAuthenticationOptions()
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { "ng" },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new MyIIssuerSecurityTokenProvider("mecode")
                }
            };

            //注册Owin中间件发布令牌
            app.UseOAuthAuthorizationServer(authServerOptions);
            //Authentication 中间件 在请求中验证Token并设置用户的身份
            app.UseJwtBearerAuthentication(jwtOptions);
        }
Beispiel #3
0
        protected virtual void UseJwtBearerAuthentication(IAppBuilder owinApp)
        {
            string issuerName = AppEnvironment.GetSsoIssuerName();

            JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences           = new[] { $"{issuerName}/resources" },
                IssuerSecurityKeyProviders = new[]
                {
                    new X509CertificateSecurityKeyProvider(issuerName, AppCertificatesProvider.GetSingleSignOnCertificate())
                }
            };

            if (PlatformUtilities.IsRunningOnMono)
            {
                jwtBearerAuthenticationOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = false,
                    ValidIssuer        = issuerName,
                    ValidAudience      = $"{issuerName}/resources",
                    IssuerSigningKey   = new X509SecurityKey(AppCertificatesProvider.GetSingleSignOnCertificate()),
                    SignatureValidator = (token, parameters) =>
                    {
                        JwtSecurityToken jwt = new JwtSecurityToken(token);

                        return(jwt);
                    }
                };
            }

            owinApp.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
Beispiel #4
0
        public void Configuration(IAppBuilder app)
        {
            string issuer   = "seed.authserver";
            string audience = "60f783b666a94ec79a70b268e9a256df";                                          // public key

            byte[] secret = TextEncodings.Base64Url.Decode("jKQwDwKcutNWEndCiS1hM6GF7cdkr2T-exG_FuY41yg"); // private key

            var options = new JwtBearerAuthenticationOptions()
            {
                AuthenticationMode           = AuthenticationMode.Active,
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                AllowedAudiences = new List <string>()
                {
                    audience
                },
                Provider = new OAuthBearerAuthenticationProvider()
                {
                    // override to add custom claims as needed by your application
                    OnValidateIdentity = ctx => { return(Task.FromResult <object>(null)); }
                }
            };

            app.UseJwtBearerAuthentication(options);
        }
Beispiel #5
0
        public void ConfigurationOAuth(IAppBuilder app)
        {
            var OAuthServerOptions = new OAuthAuthorizationServerOptions {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider          = new SimpleAuthorizationServerProvider(),
                AccessTokenFormat =
                    new CustomJwtFormat(ConfigurationManager.AppSettings["AuthIssuer"],
                                        ConfigurationManager.AppSettings["AuthAudience"],
                                        ConfigurationManager.AppSettings["AuthSecret"])
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            var issuer         = ConfigurationManager.AppSettings["AuthIssuer"];
            var audienceId     = ConfigurationManager.AppSettings["AuthAudience"];
            var audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AuthSecret"]);
            var jwtAuthOptions = new JwtBearerAuthenticationOptions {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            };

            app.UseJwtBearerAuthentication(jwtAuthOptions);
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Beispiel #6
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = "http://Rest.Services";
            var secret = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");

            JwtBearerAuthenticationOptions jwtOpt = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { "Any" },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            };

            app.UseJwtBearerAuthentication(jwtOpt);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (in production should be AllowInsecureHttp = false)
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider          = new AppAuthProvider(),
                AccessTokenFormat = new AppTokenFormat(issuer, secret)
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = ConfigurationManager.AppSettings["issuer"];
            var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            OAuthAuthorizationServerOptions OAuthServerOptions =
                new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider          = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat(issuer)
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { ConfigurationManager.AppSettings["server_audience"] },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            };

            app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
Beispiel #8
0
        protected virtual void UseJwtBearerAuthentication(IAppBuilder owinApp)
        {
            string issuerName = AppEnvironment.GetSsoIssuerName();

            RsaSecurityKey issuerSigningKey = new RsaSecurityKey(AppCertificatesProvider.GetSingleSignOnClientRsaKey());

            JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences          = new[] { $"{issuerName}/resources" },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateTokenReplay      = true,
                    ValidateLifetime         = true,
                    ValidateActor            = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidIssuer      = issuerName,
                    ValidAudience    = $"{issuerName}/resources",
                    IssuerSigningKey = issuerSigningKey
                }
            };

            owinApp.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
Beispiel #9
0
        public void ConfigureOAuthValidation(IAppBuilder app)
        {
            var issuer   = "http://jwtauthzsrv.azurewebsites.net";
            var audience = "099153c2625149bc8ecb3e85e03f0022";
            var secret   = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");

            var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new OAuthBearerAuthenticationProvider
                {
                    OnValidateIdentity = context =>
                    {
                        context.Ticket.Identity.AddClaim(new System.Security.Claims.Claim("newCustomClaim", "newValue"));
                        return(Task.FromResult <object>(null));
                    }
                }
            };

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
        public void Configuration(IAppBuilder app)
        {
            var issuer   = "test";
            var audience = issuer;
            var key      = new AesManaged().Key;
            var options  = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, key) }
            };

            app.UseJwtBearerAuthentication(options);
            app.Map("/Login", subApp =>
            {
                subApp.Run(context =>
                {
                    var tokenHandler    = new JwtSecurityTokenHandler();
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.Sha256Digest),
                        Audience           = audience,
                        Issuer             = issuer,
                        Subject            = new ClaimsIdentity(new[]
                        {
                            new Claim(ClaimTypes.Name, "Serge")
                        })
                    };
                    var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
                    return(context.Response.WriteAsync(token));
                });
            });
        }
        public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, X509Certificate2 signingKey, OAuthBearerAuthenticationProvider location = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            var options = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new X509CertificateSecurityTokenProvider(
                        issuer,
                        signingKey)
                }
            };

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

            app.UseJwtBearerAuthentication(options);

            return(app);
        }
Beispiel #12
0
        public static void ConfigureJwtBearerOptions(JwtBearerAuthenticationOptions options, IConfiguration configuration)
        {
            options.SaveToken = true;

            var secretKey  = configuration["BearerSecretKey"] ?? JwtBearerAuthenticationDefaults.BearerSecretKey;
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var expireTimeSpan = configuration["Authentication:ExpireMinute"] ?? "90";

            options.ExpireTimeSpan = TimeSpan.FromMinutes(int.Parse(expireTimeSpan));

            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                ValidateIssuer           = true,
                ValidIssuer = configuration["ValidIssuer"]
                              ?? JwtBearerAuthenticationDefaults.ValidIssuer,

                ValidateAudience = true,
                ValidAudience    = configuration["ValidAudience"]
                                   ?? JwtBearerAuthenticationDefaults.ValidAudience,


                ValidateLifetime    = true,
                ValidateTokenReplay = false,
                ClockSkew           = TimeSpan.Zero
            };
        }
Beispiel #13
0
        /// <summary>
        /// OAuth configuration
        /// </summary>
        /// <param name="app"></param>
        /// <param name="container"></param>
        public void ConfigureOAuth(IAppBuilder app, UnityContainer container)
        {
            string issuer = "http://localhost/";

            byte[] secret = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider          = new CustomAuthorizationServerProvider(container),
                AccessTokenFormat = new CustomJwtFormat(issuer)
            };

            JwtBearerAuthenticationOptions jwtBearerOptions = new JwtBearerAuthenticationOptions()
            {
                AllowedAudiences           = new[] { "Any" },
                AuthenticationMode         = AuthenticationMode.Active,
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
                }
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseJwtBearerAuthentication(jwtBearerOptions);
        }
Beispiel #14
0
        /// <summary>
        /// Adds 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 UseJwtBearerAuthentication(this IAppBuilder app, JwtBearerAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm              = options.Realm,
                Provider           = options.Provider,
                AccessTokenFormat  = new JwtFormat(options.AllowedAudiences, options.IssuerSecurityTokenProviders),
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description        = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return(app);
        }
        public JwtBearerTokenAuthenticationOptions(JwtOptions jwtOptions)
        {
            if (jwtOptions == null)
            {
                throw new ArgumentNullException("jwtOptions");
            }

            byte[] symmetricKeyBytes    = Encoding.UTF8.GetBytes(jwtOptions.JwtSigningKeyAsUtf8);
            string symmetricKeyAsBase64 = Convert.ToBase64String(symmetricKeyBytes);

            var symmetricKeyIssuerSecurityTokenProvider = new SymmetricKeyIssuerSecurityTokenProvider(
                jwtOptions.Issuer, symmetricKeyAsBase64);

            var providers = new IIssuerSecurityTokenProvider[]
            {
                symmetricKeyIssuerSecurityTokenProvider
            };

            _jwtBearerOptions = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences = new List <string> {
                    jwtOptions.Audience
                },
                IssuerSecurityTokenProviders = providers
            };

            _jwtOptions = jwtOptions;
        }
        public static IAppBuilder UseJsonWebToken(this IAppBuilder app, string issuer, string audience, string signingKey, string type = null, OAuthBearerAuthenticationProvider location = null)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            var options = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(
                        issuer,
                        signingKey)
                }
            };

            if (!string.IsNullOrEmpty(type))
            {
                options.AuthenticationType = type;
            }

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

            app.UseJwtBearerAuthentication(options);

            return(app);
        }
Beispiel #17
0
        public void ConfigureAuth(IAppBuilder app)
        {
            byte[] symmetricKey = Convert.FromBase64String(DLearnConstants.SecretKey);

            var dLearnOAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/login"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToInt32(DLearnInfrastructure.Utilities.Utility.GetAppSettings(DLearnConstants.TokenExpireInMinutes))),
                AccessTokenFormat         = new DLearnJWTFormat(),
                Provider             = new DLearnOAuthProvider(),
                RefreshTokenProvider = new DLearnRTProvider(),
                AllowInsecureHttp    = true,
            };

            var dLearnJWTOptions = new JwtBearerAuthenticationOptions
            {
                TokenValidationParameters = new TokenValidationParameters()
                {
                    RequireExpirationTime = true,
                    ValidateIssuer        = false,
                    ValidateAudience      = false,
                    IssuerSigningKey      = new SymmetricSecurityKey(symmetricKey),
                    ClockSkew             = TimeSpan.FromMinutes(0)
                },
            };

            app.UseOAuthAuthorizationServer(dLearnOAuthOptions);
            app.UseJwtBearerAuthentication(dLearnJWTOptions);
        }
Beispiel #18
0
 public AccountController(IOptions <JwtBearerAuthenticationOptions> authenticationOptions,
                          OAuthConfiguration oAuthConfiguration,
                          IHttpClientFactory clientFactory, IUserService userService, UserManager <ApplicationUser> i)
 {
     _authenticationOptions = authenticationOptions.Value;
     _oAuthConfiguration    = oAuthConfiguration;
     _clientFactory         = clientFactory;
     _userService           = userService;
 }
Beispiel #19
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(DatabaseContext.Create);
            app.CreatePerOwinContext <UserManager>(UserManager.Create);


            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            PublicClientId = "853749170e06bcda85f709b4a5a45c71"; //Also serves as key
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/api/1/login"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TokenTimeSpan,
                //AllowInsecureHttp = !HttpsEnabled,
                AllowInsecureHttp = true,
                AccessTokenFormat = new JwtFormatProvider(TokenTimeSpan)
            };

            var issuer   = "FireBreathingRubberDuckies";
            var audience = "all";
            var key      = Convert.FromBase64String("4a3940a482cbe843ce0b6fefb938bf62");

            JwtOptions = new JwtBearerAuthenticationOptions()
            {
                AuthenticationMode           = Microsoft.Owin.Security.AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, key)
                }
            };
            app.UseOAuthAuthorizationServer(OAuthOptions);

            app.UseJwtBearerAuthentication(JwtOptions);

            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
 public AccountController(UserManager <ApplicationUser> userManager,
                          SignInManager <ApplicationUser> signInManager,
                          IOptions <JwtBearerAuthenticationOptions> authenticationOptions,
                          OAuthConfiguration oAuthConfiguration)
 {
     _userManager           = userManager;
     _signInManager         = signInManager;
     _authenticationOptions = authenticationOptions.Value;
     _oAuthConfiguration    = oAuthConfiguration;
 }
Beispiel #21
0
        /// <summary>
        /// This method of Authentication currently does not support the generatio of the token with an "Login" flow.
        /// The token is expected to have been generated elsewhere and then passed in the headers of any request.
        /// The format of the JWT will be validted as long as the Algo and Secrect used to generate and validate package are the same.
        /// </summary>
        /// <param name="app"></param>
        private static void ConfigureJwtAuth(IAppBuilder app)
        {
            string _jwtSecret;
            TokenValidationParameters tokenParams;

            SetTokenValidationParameters(out _jwtSecret, out tokenParams);

            JwtBearerAuthenticationOptions authOptions = new JwtBearerAuthenticationOptions();

            authOptions.TokenValidationParameters = tokenParams;

            app.UseJwtBearerAuthentication(authOptions);
        }
Beispiel #22
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();
        }
        private static void ConfigureOAuthTokenConsumption(this IAppBuilder app, string issuer, string audienceId, byte[] audienceSecret)
        {
            var authenticationOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            };

            app.UseJwtBearerAuthentication(authenticationOptions);
        }
        protected virtual void UseJwtBearerAuthentication(IAppBuilder owinApp)
        {
            string issuerName = AppEnvironment.GetSsoIssuerName();

            JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences           = new[] { $"{issuerName}/resources" },
                IssuerSecurityKeyProviders = new[]
                {
                    new X509CertificateSecurityKeyProvider(issuerName, AppCertificatesProvider.GetSingleSignOnCertificate())
                }
            };

            owinApp.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
Beispiel #25
0
        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            // Api controllers with an [Authorize] attribute will be validated with JWT
            var oAuthServerOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { _audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(_issuer, _audienceSecret)
                }
            };

            app.UseJwtBearerAuthentication(oAuthServerOptions);
        }
Beispiel #26
0
        public static void Configure(IAppBuilder app)
        {
            var authenticationOptions = new JwtBearerAuthenticationOptions
            {
                Provider                     = new ApplicationOAuthBearerAuthenticationProvider(),
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { JwtHelper.ClientId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(JwtHelper.Issuer, ApplicationSettings.JwtSignKey)
                }
            };

            app.UseJwtBearerAuthentication(authenticationOptions);
        }
Beispiel #27
0
        private static void SetUpMiddleware(IAppBuilder app)
        {
            var jwtOptions = new JwtBearerAuthenticationOptions
            {
                AllowedAudiences = new List <string>
                {
                    IdentityConstants.AllowedAudienceCode
                },
                IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider
                                                           (IdentityConstants.Issuer, IdentityConstants.TokenSigningKey) },
                Provider = new BearerTokenQueryStringInterceptor()
            };

            app.UseJwtBearerAuthentication(jwtOptions);
        }
Beispiel #28
0
        public void Configure(IAppBuilder app)
        {
            var httpConfig = new HttpConfiguration();

            // Build the container
            ContainerConfig.Register(httpConfig);

            // Configure API
            WebApiConfig.Register(httpConfig);

            // configure FluentValidation model validator provider
            FluentValidationModelValidatorProvider.Configure(httpConfig);

            // 1. Use the autofac scope for owin
            app.UseAutofacLifetimeScopeInjector(ContainerConfig.Container);

            // 2. Allow cors requests
            app.UseCors(CorsOptions.AllowAll);

            // 3. Use the readable response middleware
            app.Use <RewindResponseMiddleware>();

            // 4. Register the activty auditing here so that anonymous activity is captured
            app.UseMiddlewareFromContainer <ActivityAuditMiddleware>();

            // Allow Web API to consume bearer JWT tokens.
            var rsaProvider = ContainerConfig.Container.Resolve <IRsaKeyContainerService>();
            var tokenParam  = new System.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidIssuer      = ConfigurationManager.AppSettings["oAuth:Issuer"],
                ValidAudience    = ConfigurationManager.AppSettings["oAuth:Audience"],
                IssuerSigningKey = new System.IdentityModel.Tokens.RsaSecurityKey(rsaProvider.GetRsaCryptoServiceProviderFromKeyContainer())
            };
            var jwtTokenOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = AuthenticationMode.Active,
                TokenValidationParameters = tokenParam,
                Provider = new QueryStringOAuthBearerProvider()
            };

            app.UseJwtBearerAuthentication(jwtTokenOptions);

            // 6. Add SignalR support.
            app.MapSignalR(ContainerConfig.HubConfiguration);

            // 7. Add web api to pipeline
            app.UseWebApi(httpConfig);
        }
Beispiel #29
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            JwtBearerAuthenticationOptions jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode         = AuthenticationMode.Active,
                AllowedAudiences           = new[] { "https://brucefox.resource.com" },
                IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
                {
                    new SymmetricKeyIssuerSecurityKeyProvider("https://scarlet-glove.gov", TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw"))
                }
            };

            app.UseJwtBearerAuthentication(jwtBearerAuthenticationOptions);
        }
        public static AuthenticationBuilder AddJwtBearerSignIn(this AuthenticationBuilder builder, string authenticationScheme,
                                                               string displayName, Action <JwtBearerAuthenticationOptions> configureOptions)
        {
            builder.AddJwtBearer(authenticationScheme + JwtBearerDefaults.AuthenticationScheme, options =>
            {
                // 复制一份给JwtBearerOptions
                var opts = new JwtBearerAuthenticationOptions();
                configureOptions(opts);
                options.Copy(opts, false,
                             //nameof(JwtBearerAuthenticationOptions.ExpireTimeSpan),
                             nameof(JwtBearerAuthenticationOptions.Events)
                             );
            });

            return(builder.AddScheme <JwtBearerAuthenticationOptions, JwtBearerAuthenticationHandler>(authenticationScheme, displayName, configureOptions));
        }