public WorkContext( IHttpContextAccessor contextAccessor, UserManager <User> userManager, IRepository <User> userRepository, AuthenticationConfig config, IStaticCacheManager cacheManager) { _userManager = userManager; _httpContext = contextAccessor.HttpContext; _userRepository = userRepository; _config = config; _cacheManager = cacheManager; }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); AuthenticationConfig.ConfigureGlobal(GlobalConfiguration.Configuration); DependencyConfig.Configure(GlobalConfiguration.Configuration); CorsConfig.RegisterGlobal(GlobalConfiguration.Configuration); TraceConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
// ReSharper disable once UnusedMember.Global public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { var auth = new AuthenticationConfig(); this._configuration.GetSection("Authentication").Bind(auth); app.UseForwardedHeaders(); app.UseSwagger(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseSwagger(c => { c.RouteTemplate = "auth/swagger/{documentName}/swagger.json"; c.PreSerializeFilters.Add((swagger, httpReq) => { swagger.Servers = new List <OpenApiServer> { new OpenApiServer { Url = $"http://{httpReq.Host.Value}" }, new OpenApiServer { Url = $"https://{httpReq.Host.Value}" } }; }); }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/auth/swagger/v1/swagger.json", "Sensate Auth API v1"); c.RoutePrefix = "auth/swagger"; }); app.UseCors(p => { p.SetIsOriginAllowed(host => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); app.UseMiddleware <RequestLoggingMiddleware>(); app.UseAuthentication(); app.UseAuthorization(); app.UseMiddleware <UserFetchMiddleware>(); app.UseEndpoints(ep => { ep.MapControllers(); }); }
public GetUserTokenHandler( IOptionsSnapshot <AuthenticationConfig> authenticationConfigOptions, IUsersRepository usersRepository, IDateTimeProvider dateTimeProvider, IUserClaimsPrincipalFactory <User> claimsPrincipalFactory, ILogger <GetUserTokenHandler> logger ) { _authenticationConfig = authenticationConfigOptions != null ? authenticationConfigOptions.Value : throw new ArgumentNullException(nameof(authenticationConfigOptions)); _usersRepository = usersRepository ?? throw new ArgumentNullException(nameof(usersRepository)); _dateTimeProvider = dateTimeProvider ?? throw new ArgumentNullException(nameof(dateTimeProvider)); _claimsPrincipalFactory = claimsPrincipalFactory ?? throw new ArgumentNullException(nameof(claimsPrincipalFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
public static void ConfigureAuthentication(this IServiceCollection services, AuthenticationConfig configuration) { var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration.JWT_SECRET_KEY)); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidIssuer = configuration.JWT_ISSUER_TOKEN, ValidAudience = configuration.JWT_AUDIENCE_TOKEN, ValidateIssuer = false, ValidateAudience = false }; x.Events = new JwtBearerEvents { OnMessageReceived = context => { if (context.Request.Query.TryGetValue("access_token", out var token)) { context.Token = token; } return(Task.CompletedTask); } }; }); services.AddAuthorization(options => { options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme); policy.RequireClaim(ClaimTypes.NameIdentifier); policy.RequireClaim(ClaimTypes.GivenName); }); }); services.AddSingleton(signingCredentials); services.AddSingleton(configuration); }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Methods for internal implementation /// <include file='doc\PassportAuthenticationModule.uex' path='docs/doc[@for="PassportAuthenticationModule.OnEnter"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> void OnEnter(Object source, EventArgs eventArgs) { if (_fAuthChecked && !_fAuthRequired) { return; } HttpApplication app; HttpContext context; app = (HttpApplication)source; context = app.Context; if (!_fAuthChecked) { AuthenticationConfig settings = (AuthenticationConfig)context.GetConfig("system.web/authentication"); _fAuthRequired = (settings.Mode == AuthenticationMode.Passport); _LoginUrl = settings.PassportUrl; _fAuthChecked = true; } if (!_fAuthRequired) { return; } //////////////////////////////////////////////////////// // Step 1: See if this request is valid or not if (context.Response.StatusCode == 401 || context.Response.StatusCode == 400 || context.Response.StatusCode == 500 || context.User != null) // Some module has already verified that the credentials are invalid { return; } //////////////////////////////////////////////////////// // Step 2: Create a Passport Identity from the credentials // from IIS PassportIdentity identity = new PassportIdentity(); //////////////////////////////////////////////////////// // Step 4: Call OnAuthenticate virtual method to create // an IPrincipal for this request OnAuthenticate(new PassportAuthenticationEventArgs(identity, context)); //////////////////////////////////////////////////////// // Skip AuthZ if accessing the login page context.SkipAuthorization = AuthenticationConfig.AccessingLoginPage(context, _LoginUrl); }
private AuthenticationConfig DeserializeAuthenticationConfig(XmlNode root) { var section = root.SelectSingleNode("authentication"); if (section == null) { return(AuthenticationConfig.Default); } var config = new AuthenticationConfig(); config.LoadFrom(section); return(config); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { CorsConfig.Add(ref services, Configuration); APIControllersConfig.Add(ref services, Configuration); EntityFrameworkConfig.Add(ref services, Configuration); AuthenticationConfig.Add(ref services, Configuration); var mapper = AutoMapperConfig.Add(ref services, Configuration); APIVersioningConfig.Add(ref services, Configuration); SwaggerConfig.Add(ref services, Configuration); DependencyInjectionConfig.Add(ref services, Configuration, ref mapper); HealthChecksConfig.Add(ref services, Configuration); SignalRConfig.Add(ref services, Configuration); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); AuthenticationConfig.ConfigureGlobal(GlobalConfiguration.Configuration); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); FederatedAuthentication.FederationConfigurationCreated += FederatedAuthentication_FederationConfigurationCreated; }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Methods for internal implementation /// <internalonly/> /// <devdoc> /// </devdoc> void OnEnter(Object source, EventArgs eventArgs) { if (_fAuthChecked && !_fAuthRequired) { return; } HttpApplication app; HttpContext context; app = (HttpApplication)source; context = app.Context; if (!_fAuthChecked) { AuthenticationSection settings = RuntimeConfig.GetAppConfig().Authentication; _fAuthRequired = (AuthenticationConfig.Mode == AuthenticationMode.Passport); _LoginUrl = settings.Passport.RedirectUrl; _fAuthChecked = true; } if (!_fAuthRequired) { return; } //////////////////////////////////////////////////////// // Step 1: See if this request is valid or not // VSWhidbey 442515: We no longer need to do this check, always proceed //////////////////////////////////////////////////////// // Step 2: Create a Passport Identity from the credentials // from IIS PassportIdentity identity = new PassportIdentity(); //////////////////////////////////////////////////////// // Step 4: Call OnAuthenticate virtual method to create // an IPrincipal for this request OnAuthenticate(new PassportAuthenticationEventArgs(identity, context)); //////////////////////////////////////////////////////// // Skip AuthZ if accessing the login page context.SetSkipAuthorizationNoDemand(AuthenticationConfig.AccessingLoginPage(context, _LoginUrl), false /*managedOnly*/); if (!context.SkipAuthorization) { context.SkipAuthorization = AssemblyResourceLoader.IsValidWebResourceRequest(context); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { AuthenticationConfig config = AuthenticationConfig.GetConfig(PortalId); SettingsEditor.DataSource = config; SettingsEditor.DataBind(); } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } }
static Configurations() { _adminUI = new AdminUIConfig(); _providers = new ProvidersConfig(); _pages = new PagesConfig(); _webData = new WebDataConfig(); _authentication = new AuthenticationConfig(); _imageCompressor = new ImageCompressorConfig(); _autoUpdate = new AutoUpdateConfig(); _logSystem = new LogSystemConfig(); _netProxy = new NetProxyConfig(); _userOptions = new UserOptionsConfig(); _userAccessControlConfig = new UserAccessControlConfig(); ReadSettings(); }
public static void ConfigureAuth(IAppBuilder app, AuthenticationConfig config) { // Configure the db context, user manager and role manager to use a single instance per request app.CreatePerOwinContext(DexCMSContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie if (config.UseCookies) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString(config.LoginUrl), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); } if (config.UseTwoFactor) { // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); } if (config.SigininOptionConfigs != null) { foreach (var signinConfig in config.SigininOptionConfigs) { ProcessSiginOption(app, signinConfig); } } }
public void ConfigureServices(IServiceCollection services) { services.AddDirectoryBrowser(); services.AddSignalR(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); AuthenticationConfig.AuthenticationConfigServices(services, Configuration); CORS.CORSServices(services); DependencyInjection.DependencyInjectionServices(services); Swagger.StartUpSwaggerConfigureServices(services); }
private static async Task RunAsync() { AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); // You can run this sample using ClientSecret or Certificate. The code will differ only when instantiating the IConfidentialClientApplication bool isUsingClientSecret = AppUsesClientSecret(config); // Even if this is a console application here, a daemon application is a confidential client application IConfidentialClientApplication app; app = ConfidentialClientApplicationBuilder.Create(config.ClientId) .WithClientSecret(config.ClientSecret) .WithAuthority(new Uri(config.Authority)) .Build(); // With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the // application permissions need to be set statically (in the portal or by PowerShell), and then granted by // a tenant administrator string[] scopes = new string[] { config.TodoListScope }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopes) .ExecuteAsync(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Token acquired \n"); Console.ResetColor(); } catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")) { // Invalid scope. The scope has to be of the form "https://resourceurl/.default" // Mitigation: change the scope to be as expected Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Scope provided is not supported"); Console.ResetColor(); } if (result != null) { var httpClient = new HttpClient(); var apiCaller = new ProtectedApiCallHelper(httpClient); await apiCaller.CallWebApiAndProcessResultASync($"{config.TodoListBaseAddress}/api/todolist/all", result.AccessToken, Display); } }
private static void ConfigureApis(HttpSelfHostConfiguration configuration) { // authentication var authConfig = AuthenticationConfig.CreateConfiguration(); authConfig.ClaimsAuthenticationManager = new ConsultantsClaimsTransformer(); configuration.MessageHandlers.Add(new AuthenticationHandler(authConfig)); // authorization configuration.SetAuthorizationManager(new GlobalAuthorizationManager(DefaultPolicy.Deny)); // CORS CorsConfig.RegisterGlobal(configuration); // dependency resolver for authorization manager configuration.DependencyResolver = new AuthorizationDependencyResolver(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddDbContext <TDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TDbContext"))); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); AuthenticationConfig.Configure(services, Configuration); DependencyRegistrar.Register(services); }
public void SetUp() { authenticationConfig = AuthenticationConfig.Builder.RedirectUri("test://example.com").Build(); keycloakConfig = new KeycloakConfig(kcConfig); credentialManagerMock = new Mock <ICredentialManager>(); httpModuleMock = new Mock <IHttpServiceModule>(); var httpRequestMock = new Mock <IHttpRequest>(); var requestToBeExecuted = new Mock <IHttpRequestToBeExecuted>(); var httpResponse = new Mock <IHttpResponse>(); httpResponse.Setup(response => response.StatusCode).Returns(200); requestToBeExecuted.Setup(arg => arg.Execute()).Returns(Task.FromResult(httpResponse.Object)); httpRequestMock.Setup(request => request.Get(It.IsAny <string>())).Returns(requestToBeExecuted.Object); httpModuleMock.Setup(arg => arg.NewRequest()).Returns(httpRequestMock.Object); authenticatorToTest = new OIDCAuthenticator(authenticationConfig, keycloakConfig, credentialManagerMock.Object, httpModuleMock.Object, logger.Object); }
private void OnEnter(object source, EventArgs eventArgs) { this._fOnEnterCalled = true; HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; this.OnAuthenticate(new FormsAuthenticationEventArgs(context)); CookielessHelperClass cookielessHelper = context.CookielessHelper; if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl)) { context.SetSkipAuthorizationNoDemand(true, false); cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode); } if (!context.SkipAuthorization) { context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false); } }
public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddTransient <IImagePickDbContext, ImagePickDbContext>(); services.AddDbContext <ImagePickDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); IdentityConfig.CreateIdentityIfNotCreated(services); AuthenticationConfig.ConfigureAuthenticationSettings(services, Configuration); IoCRegister.AddRegistration(services); SwaggerConfig.AddRegistration(services); services.AddControllers(options => options.RespectBrowserAcceptHeader = true) .AddNewtonsoftJson(); }
public void NoAuthentication(string configurationName, AuthenticationConfig authenticationConfig) { var indexedDictionary = new IndexDictionary <string, WebhookConfig> { { configurationName, new WebhookConfig { Name = configurationName, AuthenticationConfig = authenticationConfig } } }; var factory = new AuthenticationHandlerFactory(indexedDictionary, new Mock <IBigBrother>().Object); var handler = factory.Get(configurationName); Assert.Null(handler); }
public void GetTokenProvider(string configurationName, AuthenticationConfig authenticationConfig, IAcquireTokenHandler expectedHandler) { var indexedDictionary = new IndexDictionary <string, WebhookConfig> { { configurationName, new WebhookConfig { Name = configurationName, AuthenticationConfig = authenticationConfig } } }; var factory = new AuthenticationHandlerFactory(indexedDictionary, new Mock <IBigBrother>().Object); var handler = factory.Get(configurationName); Assert.Equal(expectedHandler.GetType(), handler.GetType()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <FFOContext>(options => options.UseSqlServer(Configuration.GetConnectionString("FFOConnections"))); var authenticationConfig = new AuthenticationConfig(); Configuration.GetSection("AuthenticationService").Bind(authenticationConfig); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authenticationConfig.JWTSigningKey)), ValidateIssuer = false, ValidateAudience = false }; }); services.AddControllers().AddNewtonsoftJson(s => { s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); services.AddRazorPages(); services.AddSingleton(authenticationConfig); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddScoped <IMasterService, MasterService>(); services.AddScoped <IServantService, ServantService>(); services.AddScoped <IFamiliarService, FamiliarService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <ITokenService, TokenService>(); services.AddScoped(typeof(IBaseService <>), typeof(BaseService <>)); services.AddHttpClient("familiar", config => config.BaseAddress = new System.Uri("https://localhost:44389/")); }
public void TestDefaultConfig() { AuthenticationConfig defaultAuthConfig = AuthenticationConfig .Builder .RedirectUri("org.aerogear.mobile.example:/callback") .Build(); var expectedRedirectUri = new Uri("org.aerogear.mobile.example:/callback"); var actualRedirectUri = defaultAuthConfig.RedirectUri; var expectedScopes = "openid"; var actualScopes = defaultAuthConfig.Scopes; var expectedMinTimeBetweenJwksRequests = 24 * 60; var actualMinTimeBetweenJwksRequests = defaultAuthConfig.MinTimeBetweenJwksRequests; Assert.AreEqual(expectedRedirectUri, actualRedirectUri); Assert.AreEqual(expectedScopes, actualScopes); Assert.AreEqual(expectedMinTimeBetweenJwksRequests, actualMinTimeBetweenJwksRequests); }
/// <summary> /// Verify if app is using a client secret or certificate /// </summary> /// <param name="config"></param> /// <returns>True if you're using client secrets; False if you're using certificates</returns> private static bool AppUsesClientSecret(AuthenticationConfig config) { string clientSecretPlaceholderValue = "[Enter here a client secret for your application]"; string certificatePlaceholderValue = "[Or instead of client secret: Enter here the name of a certificate (from the user cert store) as registered with your application]"; if (!String.IsNullOrWhiteSpace(config.ClientSecret) && config.ClientSecret != clientSecretPlaceholderValue) { return(true); } else if (!String.IsNullOrWhiteSpace(config.CertificateName) && config.CertificateName != certificatePlaceholderValue) { return(false); } else { throw new Exception("You must choose between using client secret or certificate. Please update appsettings.json file."); } }
public UserService( ILoggerAdapter <UserService> logger, IMetricService metrics, IEncryptionService encryptionService, IUserRepo userRepo, TimeTrackerConfig config) { // TODO: [TESTS] (UserService) Add tests _logger = logger; _encryptionService = encryptionService; _userRepo = userRepo; _metrics = metrics; _config = config.Authentication; if (string.IsNullOrWhiteSpace(_config.Secret)) { // TODO: [HANDLE] (UserService.UserService) Handle this throw new Exception("Auth Secret is missing!"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var authConfig = new AuthenticationConfig(); Configuration.Bind("Authentication", authConfig); Action <IdentityServerAuthenticationOptions> options = o => { o.Authority = authConfig.Authority; o.ApiName = authConfig.ApiName; o.SupportedTokens = SupportedTokens.Both; o.ApiSecret = authConfig.ApiSecret; }; services.AddAuthentication() .AddIdentityServerAuthentication(authConfig.AuthenticationProviderKey, options); services .AddOcelot(Configuration) .AddConsul(); }
private Stream GetStreamForOneDrive() { var config = AuthenticationConfig.ReadFromJsonFile("graphsettings.json"); config.CheckParameters(); _graphServiceClient = GraphClientFactory.GraphClientFactory.GetGraphServiceClient ( config.ClientId, config.Authority, config.RedirectUri, config.Scopes ); var request = _graphServiceClient.Me.Drive.Root.ItemWithPath(_fileName).Content .Request() .GetAsync(); return(request .GetAwaiter() .GetResult()); }
public static void AddHttpClients( this IServiceCollection services, AuthenticationConfig authConfig, UserManagementConfig userManagementConfig) { services.AddTransient <BaseHttpMessageHandler>(); services.AddHttpClient(HttpClientNames.AUTHENTICATION_CLIENT, c => { c.BaseAddress = new Uri(authConfig.Authority); }).AddHttpMessageHandler <BaseHttpMessageHandler>(); services.AddTransient <IServiceAuthenticator, ServiceToServiceAuthenticator>(); var serviceProvider = services.BuildServiceProvider(); var serviceAuth = serviceProvider.GetRequiredService <IServiceAuthenticator>(); services.AddTransient <UserManagerErrorResponseHandler>(); services.AddHttpClient(HttpClientNames.USER_MANAGEMENT_CLIENT, async http => { var token = await serviceAuth.AuthenticateAsync(); http.BaseAddress = new Uri(userManagementConfig.BaseUrl); http.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); }) .AddHttpMessageHandler <UserManagerErrorResponseHandler>(); }
internal static void AddAuthentication(this IServiceCollection services, AuthenticationConfig config) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(option => { option.Authority = config.Authority; option.Audience = config.Audience; option.IncludeErrorDetails = false; option.SaveToken = true; option.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidAudience = config.Audience, ValidateIssuer = true, ValidIssuer = config.Authority, ValidateLifetime = true, ValidateIssuerSigningKey = true }; }); }
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // default API route routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // API route with claims transformation routes.MapHttpRoute( name: "DefaultApiWithTransformation", routeTemplate: "api2/identity", defaults: new { controller = "Identity" }, constraints: null, handler: new ClaimsTransformationHandler(new ConsultantsClaimsTransformer(), GlobalConfiguration.Configuration) ); // API route with per-route authentication routes.MapHttpRoute( name: "DefaultApiPerRouteAuthN", routeTemplate: "api3/identity", defaults: new { controller = "Identity" }, constraints: null, handler: new AuthenticationHandler(AuthenticationConfig.CreateConfiguration(), GlobalConfiguration.Configuration) ); // default MVC route routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
//////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> private void OnEnter(Object source, EventArgs eventArgs) { _fOnEnterCalled = true; HttpApplication app; HttpContext context; app = (HttpApplication)source; context = app.Context; #if DBG Trace("*******************Request path: " + context.Request.RawUrl); #endif //////////////////////////////////////////////////////// // Step 2: Call OnAuthenticate virtual method to create // an IPrincipal for this request OnAuthenticate(new FormsAuthenticationEventArgs(context)); //////////////////////////////////////////////////////// // Skip AuthZ if accessing the login page // We do this here to force the cookieless helper to fish out and // remove the token from the URL if it's present there. CookielessHelperClass cookielessHelper = context.CookielessHelper; if (AuthenticationConfig.AccessingLoginPage(context, FormsAuthentication.LoginUrl)) { context.SetSkipAuthorizationNoDemand(true, false /*managedOnly*/); cookielessHelper.RedirectWithDetectionIfRequired(null, FormsAuthentication.CookieMode); } if (!context.SkipAuthorization) { context.SetSkipAuthorizationNoDemand(AssemblyResourceLoader.IsValidWebResourceRequest(context), false /*managedOnly*/); } }