JwtBearerOptions

We found 10 examples in language CSharp for this search. You will see 25 fragments of code.

        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
        {
            builder.Services.Configure(configureOptions);
            builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();
            builder.AddJwtBearer();
            return builder;
        }

            public void Configure(string name, JwtBearerOptions options)
            {
                //options.Audience = _azureOptions.ClientId;
                options.Audience = _azureOptions.Audience;
                options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
            }

            public void Configure(JwtBearerOptions options)
            {
                Configure(Options.DefaultName, options);
            }


        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
        {
            builder.Services.Configure(configureOptions);
            builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();
            builder.AddJwtBearer();
            return builder;
        }

            public void Configure(string name, JwtBearerOptions options)
            {
                options.Audience = _azureOptions.ClientId;
                options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
            }

            public void Configure(JwtBearerOptions options)
            {
                Configure(Options.DefaultName, options);
            }


        public JwtBearerOptions Get(string name)
        {
            var tenant = _tenantProvider.GetCurrentTenant();

            Lazy<JwtBearerOptions> Create() => new Lazy<JwtBearerOptions>(()=> _optionsFactory.Create(name));
            return _cache.GetOrAdd((name, tenant),_=>Create()).Value;
        }

        public IDisposable OnChange(Action<JwtBearerOptions, string> listener) => null;

        public static AuthenticationBuilder AddSchemeJwtBearer(this AuthenticationBuilder builder)
            => builder.AddSchemeJwtBearer(JwtBearerDefaults.AuthenticationScheme, _ => { });

        public static AuthenticationBuilder AddSchemeJwtBearer(this AuthenticationBuilder builder, Action<JwtBearerOptions> configureOptions)
            => builder.AddSchemeJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions);

        public static AuthenticationBuilder AddSchemeJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, Action<JwtBearerOptions> configureOptions)
            => builder.AddSchemeJwtBearer(authenticationScheme, displayName: null, configureOptions: configureOptions);

        public static AuthenticationBuilder AddSchemeJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<JwtBearerOptions> configureOptions)
        {
            builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
            return builder.AddScheme<JwtBearerOptions, SchemeJwtBearerHandler>(authenticationScheme, displayName, configureOptions);
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                    builder
                    .AllowAnyOrigin() 
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
            }));

            services.AddHealthChecks();

            services.AddMvcCore()
            .AddAuthorization()
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddFormatterMappings()
            .AddJsonFormatters().AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            services.AddApiVersioning(o => {
                o.ApiVersionReader = new HeaderApiVersionReader("api-version");
                o.AssumeDefaultVersionWhenUnspecified = true;
            });

            services.AddTransient<IUsuarioService, UsuarioService>();

            var defaultConnection = Environment.GetEnvironmentVariable("DefaultConnection");

            defaultConnection = String.IsNullOrEmpty(defaultConnection) ? Configuration.GetConnectionString("DefaultConnection") : defaultConnection;

            services.AddDbContextPool<GerenciadorFinanceiroContext>(options => options.UseMySql(defaultConnection,
            mySqlOptions =>
            {
                mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql);
            }));

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme = "JwtBearer";            
            })
            .AddJwtBearer("JwtBearer", jwtBearerOptions =>
            {
                var secret = Environment.GetEnvironmentVariable("appsecretkey");
                if(secret == null)
                    secret = "test secret key, please change it";
                
                jwtBearerOptions.Configuration = new OpenIdConnectConfiguration();

                jwtBearerOptions.Audience = "http://localhost:5000/";
                jwtBearerOptions.Authority = "http://localhost:5000/";
                jwtBearerOptions.RequireHttpsMetadata = false;

                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {                            
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),

                    ValidateIssuer = true,
                    ValidIssuer = "backend-gerenciador-financeiro",

                    ValidateAudience = true,
                    ValidAudience = "frontend-gerenciador-financeiro",

                    ValidateLifetime = true, //validate the expiration and not before values in the token
                    ClockSkew = TimeSpan.FromMinutes(5), //5 minute tolerance for the expiration date
                };
            });

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();
            services.AddSingleton(mapper);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, GerenciadorFinanceiroContext context)
        {
            context.Database.Migrate();

            app.UseHealthChecks("/health");

            if (env.IsDevelopment())
            {
                app.UseCors("MyPolicy");
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
                app.UseHttpsRedirection();
            }

            app.UseAuthentication();

            app.UseMvc();
        }

        public static JwtBearerOptions LoadTokenOptions(this JwtBearerOptions jwtBearerOptions,
            IConfiguration configuration)
        {
            JwtTokenOptions jwt = GetJwtOptions(configuration);
            byte[] securityKey = GetSecurityKey(configuration);
            jwtBearerOptions.RequireHttpsMetadata = true;
            jwtBearerOptions.SaveToken = true;
            jwtBearerOptions.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    var accessToken = context.Request.Query["access_token"];

                    // If the request is for our hub...
                    var path = context.HttpContext.Request.Path;
                    if (!string.IsNullOrEmpty(accessToken) &&
                        (path.StartsWithSegments("/socialHub")))
                    {
                        // Read the token out of the query string
                        context.Token = accessToken;
                    }
                    return Task.CompletedTask;
                }
            };
            jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateLifetime = true,
                ValidateIssuer = true,
                ValidIssuer = jwt.Issuer,
                ValidateAudience = true,
                ValidAudience = jwt.Audience,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(securityKey)
            };
            return jwtBearerOptions;
        }

        public static JwtTokenOptions GetJwtOptions(IConfiguration configuration)
        {
            var jwtTokenConfig = new JwtTokenOptions();
            configuration.GetSection(JwtTokenOptions.JwtToken).Bind(jwtTokenConfig);
            return jwtTokenConfig;
        }

        public static byte[] GetSecurityKey(IConfiguration configuration)
        {
            return Encoding.ASCII.GetBytes(configuration["Doppler:TokenIssuerSigningKey"]);
        }

        /// <summary>
        /// Configure an OpenIdConnectOptions object based on user's configuration.
        /// </summary>
        /// <param name="oktaMvcOptions">The <see cref="OktaMvcOptions"/> options.</param>
        /// <param name="oidcOptions">The OpenIdConnectOptions to configure.</param>
        public static void ConfigureOpenIdConnectOptions(OktaMvcOptions oktaMvcOptions, OpenIdConnectOptions oidcOptions)
        {
            var issuer = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);

            oidcOptions.ClientId = oktaMvcOptions.ClientId;
            oidcOptions.ClientSecret = oktaMvcOptions.ClientSecret;
            oidcOptions.Authority = issuer;
            oidcOptions.CallbackPath = new PathString(oktaMvcOptions.CallbackPath);
            oidcOptions.SignedOutCallbackPath = new PathString(OktaDefaults.SignOutCallbackPath);
            oidcOptions.SignedOutRedirectUri = oktaMvcOptions.PostLogoutRedirectUri;
            oidcOptions.ResponseType = OpenIdConnectResponseType.Code;
            oidcOptions.GetClaimsFromUserInfoEndpoint = oktaMvcOptions.GetClaimsFromUserInfoEndpoint;
            oidcOptions.SecurityTokenValidator = new StrictSecurityTokenValidator();
            oidcOptions.SaveTokens = true;
            oidcOptions.UseTokenLifetime = false;
            oidcOptions.BackchannelHttpHandler = new OktaHttpMessageHandler(
                "okta-aspnetcore",
                typeof(OktaAuthenticationOptionsExtensions).Assembly.GetName().Version,
                oktaMvcOptions);
            oidcOptions.BackchannelTimeout = oktaMvcOptions.BackchannelTimeout;

            var hasDefinedScopes = oktaMvcOptions.Scope?.Any() ?? false;
            if (hasDefinedScopes)
            {
                oidcOptions.Scope.Clear();
                foreach (var scope in oktaMvcOptions.Scope)
                {
                    oidcOptions.Scope.Add(scope);
                }
            }

            oidcOptions.TokenValidationParameters = new DefaultTokenValidationParameters(oktaMvcOptions, issuer)
            {
                ValidAudience = oktaMvcOptions.ClientId,
                NameClaimType = "name",
            };

            if (oktaMvcOptions.OpenIdConnectEvents != null)
            {
                oidcOptions.Events = oktaMvcOptions.OpenIdConnectEvents;
            }

            if (oktaMvcOptions.GetClaimsFromUserInfoEndpoint)
            {
                oidcOptions.ClaimActions.Add(new MapAllClaimsAction());
            }

            oidcOptions.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
            oidcOptions.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
            oidcOptions.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
            oidcOptions.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
            oidcOptions.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
        }

        /// <summary>
        /// Configure the JwtBearerOptions based on user's configuration.
        /// </summary>
        /// <param name="oktaWebApiOptions">The <see cref="OktaWebApiOptions"/> options.</param>
        /// <param name="jwtBearerOptions">The jwtBearerOptions to configure.</param>
        public static void ConfigureJwtBearerOptions(OktaWebApiOptions oktaWebApiOptions, JwtBearerOptions jwtBearerOptions)
        {
            var issuer = UrlHelper.CreateIssuerUrl(oktaWebApiOptions.OktaDomain, oktaWebApiOptions.AuthorizationServerId);

            var tokenValidationParameters = new DefaultTokenValidationParameters(oktaWebApiOptions, issuer)
            {
                ValidAudience = oktaWebApiOptions.Audience,
            };

            jwtBearerOptions.Audience = oktaWebApiOptions.Audience;
            jwtBearerOptions.Authority = issuer;
            jwtBearerOptions.TokenValidationParameters = tokenValidationParameters;
            jwtBearerOptions.BackchannelHttpHandler = new OktaHttpMessageHandler("okta-aspnetcore", typeof(OktaAuthenticationOptionsExtensions).Assembly.GetName().Version, oktaWebApiOptions);
            jwtBearerOptions.Events = oktaWebApiOptions.JwtBearerEvents ?? new JwtBearerEvents();
            jwtBearerOptions.SecurityTokenValidators.Clear();
            jwtBearerOptions.SecurityTokenValidators.Add(new StrictSecurityTokenValidator());
            jwtBearerOptions.BackchannelTimeout = oktaWebApiOptions.BackchannelTimeout;
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<DatabaseSettings>(Configuration.GetSection(nameof(DatabaseSettings)));

            services.AddSingleton<IDatabaseSettings>(sp => sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);

            services.AddSingleton<UserService>();

            services.AddControllers();

            JwtBearerOptions options(JwtBearerOptions jwtBearerOptions, string audience) {
                jwtBearerOptions.RequireHttpsMetadata = false;
                jwtBearerOptions.SaveToken = true;
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Superlongsupersecret!")),
                    ValidIssuer = "JwtExample",
                    ValidateAudience = true,
                    ValidAudience = audience,
                    ValidateLifetime = true, //validate the expiration and not before values in the token
                    ClockSkew = TimeSpan.FromMinutes(1) //1 minute tolerance for the expiration date
                };
                if (audience == "access")
                {
                    jwtBearerOptions.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                            {
                                context.Response.Headers.Add("Token-Expired", "true");
                            }
                            return Task.CompletedTask;
                        }
                    };
                }
                return jwtBearerOptions;
            }

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtBearerOptions => options(jwtBearerOptions, "access"))
            .AddJwtBearer("refresh", jwtBearerOptions => options(jwtBearerOptions, "refresh"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        //public static void ConfigureDbContex(this IServiceCollection services, IConfiguration config)
        //{
        //    services.AddDbContext<EVoucherSystemDBContext>(options => options.UseSqlServer(config.GetConnectionString("EVoucherSystemDBString")));
        //}

        public static void ConfigJwtAuthorization(this IServiceCollection services, IConfiguration config)
        {

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme = "JwtBearer";

            }).AddJwtBearer("JwtBearer", jwtBearerOptions =>
            {
                jwtBearerOptions.SecurityTokenValidators.Clear();
                jwtBearerOptions.SecurityTokenValidators.Add(new JwtValidationHandler(config));
                jwtBearerOptions.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        string errorStatus = "";
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                            errorStatus = "Token is Expired.";
                        }
                        else
                        {
                            errorStatus = "Invalid Token!";
                        }
                        Error err = new Error("Unauthorized Request", errorStatus);

                        var message = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(err));
                        context.Response.StatusCode = 401;
                        context.Response.ContentType = "application/json;";
                        context.Response.Body.WriteAsync(message, 0, message.Length);
                        return Task.CompletedTask;
                    }
                };
            });
        }

        public static void ConfigureValidateModel(this IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelAttribute));
            });
            services.Configure<ApiBehaviorOptions>(options => {
                options.SuppressModelStateInvalidFilter = true;
            });
        }

        // Methods
        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, Action<SecurityTokenValidationOptions> configureOptions = null)
        {
            #region Contracts

            if (builder == null) throw new ArgumentException(nameof(builder));

            #endregion

            // Return
            return builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions);
        }

        public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, Action<SecurityTokenValidationOptions> configureOptions = null)
        {
            #region Contracts

            if (builder == null) throw new ArgumentException(nameof(builder));
            if (string.IsNullOrEmpty(authenticationScheme) == true) throw new ArgumentException(nameof(authenticationScheme));

            #endregion

            // AuthenticationOptions
            if (configureOptions != null) builder.Services.Configure(authenticationScheme, configureOptions);

            // JwtBearerAuthenticationOptions
            builder.Services.AddOptions<JwtBearerOptions>(authenticationScheme).Configure<IOptionsMonitor<SecurityTokenValidationOptions>>((jwtBearerOptions, authenticationOptionsMonitor) =>
            {
                // AuthenticationOptions
                var authenticationOptions = authenticationOptionsMonitor.Get(authenticationScheme);
                if (authenticationOptions == null) throw new InvalidOperationException($"{nameof(authenticationOptions)}=null");

                // JwtBearerOptions.SecurityTokenValidators
                {
                    jwtBearerOptions.SecurityTokenValidators.Clear();
                    jwtBearerOptions.SecurityTokenValidators.Add(new SecurityTokenValidationHandler());
                }

                // JwtBearerOptions.ValidationParameters
                {
                    // Setting
                    jwtBearerOptions.TokenValidationParameters.AuthenticationType = "JwtBearer";

                    // Issuer
                    jwtBearerOptions.TokenValidationParameters.ValidateIssuer = true;
                    jwtBearerOptions.TokenValidationParameters.ValidIssuer = authenticationOptions.Issuer;

                    // Audience
                    jwtBearerOptions.TokenValidationParameters.ValidateAudience = false;
                    jwtBearerOptions.TokenValidationParameters.ValidAudience = null;

                    // Lifetime
                    jwtBearerOptions.TokenValidationParameters.ValidateLifetime = true;
                    jwtBearerOptions.TokenValidationParameters.ClockSkew = TimeSpan.Zero;

                    // Signing                        
                    jwtBearerOptions.TokenValidationParameters.ValidateIssuerSigningKey = true;
                    jwtBearerOptions.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationOptions.SignKey));
                }
            });

            // JwtBearerAuthentication
            builder.AddJwtBearer(authenticationScheme, null, null);

            // Return
            return builder;
        }

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions : AuthenticationSchemeOptions

Constructors :

public JwtBearerOptions()

Methods :

public Boolean get_RequireHttpsMetadata()
public Void set_RequireHttpsMetadata(Boolean value = )
public String get_MetadataAddress()
public Void set_MetadataAddress(String value = )
public String get_Authority()
public Void set_Authority(String value = )
public String get_Audience()
public Void set_Audience(String value = )
public String get_Challenge()
public Void set_Challenge(String value = )
public JwtBearerEvents get_Events()
public Void set_Events(JwtBearerEvents value = )
public HttpMessageHandler get_BackchannelHttpHandler()
public Void set_BackchannelHttpHandler(HttpMessageHandler value = )
public TimeSpan get_BackchannelTimeout()
public Void set_BackchannelTimeout(TimeSpan value = )
public OpenIdConnectConfiguration get_Configuration()
public Void set_Configuration(OpenIdConnectConfiguration value = )
public IConfigurationManager<OpenIdConnectConfiguration> get_ConfigurationManager()
public Void set_ConfigurationManager(IConfigurationManager<OpenIdConnectConfiguration> value = )
public Boolean get_RefreshOnIssuerKeyNotFound()
public Void set_RefreshOnIssuerKeyNotFound(Boolean value = )
public IList<ISecurityTokenValidator> get_SecurityTokenValidators()
public TokenValidationParameters get_TokenValidationParameters()
public Void set_TokenValidationParameters(TokenValidationParameters value = )
public Boolean get_SaveToken()
public Void set_SaveToken(Boolean value = )
public Boolean get_IncludeErrorDetails()
public Void set_IncludeErrorDetails(Boolean value = )
public Void Validate()
public Void Validate(String scheme = )
public String get_ClaimsIssuer()
public Void set_ClaimsIssuer(String value = )
public Object get_Events()
public Void set_Events(Object value = )
public Type get_EventsType()
public Void set_EventsType(Type value = )
public String get_ForwardDefault()
public Void set_ForwardDefault(String value = )
public String get_ForwardAuthenticate()
public Void set_ForwardAuthenticate(String value = )
public String get_ForwardChallenge()
public Void set_ForwardChallenge(String value = )
public String get_ForwardForbid()
public Void set_ForwardForbid(String value = )
public String get_ForwardSignIn()
public Void set_ForwardSignIn(String value = )
public String get_ForwardSignOut()
public Void set_ForwardSignOut(String value = )
public Func<HttpContext, String> get_ForwardDefaultSelector()
public Void set_ForwardDefaultSelector(Func<HttpContext, String> value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()