/// <summary> /// Adds a <see cref="AllowAnonymousFilter"/> to the page with the specified name located in the specified area. /// </summary> /// <param name="conventions">The <see cref="PageConventionCollection"/> to configure.</param> /// <param name="areaName">The area name.</param> /// <param name="pageName"> /// The page name e.g. <c>/Users/List</c> /// <para> /// The page name is the path of the file without extension, relative to the pages root directory for the specified area. /// e.g. the page name for the file Areas/Identity/Pages/Manage/Accounts.cshtml, is <c>/Manage/Accounts</c>. /// </para> /// </param> /// <returns>The <see cref="PageConventionCollection"/>.</returns> public static PageConventionCollection AllowAnonymousToAreaPage( this PageConventionCollection conventions, string areaName, string pageName) { if (conventions == null) { throw new ArgumentNullException(nameof(conventions)); } if (string.IsNullOrEmpty(areaName)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(areaName)); } if (string.IsNullOrEmpty(pageName)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(pageName)); } var anonymousFilter = new AllowAnonymousFilter(); conventions.AddAreaPageApplicationModelConvention(areaName, pageName, model => model.Filters.Add(anonymousFilter)); return(conventions); }
public void OnAuthorization_IsAnonymous_ShouldReturnSuccess() { // Arrange var allowAnonymousFilter = new AllowAnonymousFilter(); filtersMetadata.Add(allowAnonymousFilter); // Act authorizationFilter.OnAuthorization(authorizationContext); var actualActionResult = authorizationContext.Result; // Assert Assert.AreEqual(expectedActionResult, actualActionResult); Assert.IsNull(actualActionResult); }
/// <summary> /// Adds a <see cref="AllowAnonymousFilter"/> to all pages under the specified folder. /// </summary> /// <param name="conventions">The <see cref="PageConventionCollection"/> to configure.</param> /// <param name="folderPath">The folder path.</param> /// <returns>The <see cref="PageConventionCollection"/>.</returns> public static PageConventionCollection AllowAnonymousToFolder(this PageConventionCollection conventions, string folderPath) { if (conventions == null) { throw new ArgumentNullException(nameof(conventions)); } if (string.IsNullOrEmpty(folderPath)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(folderPath)); } var anonymousFilter = new AllowAnonymousFilter(); conventions.AddFolderApplicationModelConvention(folderPath, model => model.Filters.Add(anonymousFilter)); return(conventions); }
/// <summary> /// Start method /// </summary> /// <param name="context"></param> public async void OnActionExecuting(ActionExecutingContext context) { AllowAnonymousFilter allowAnonymousFilter = (AllowAnonymousFilter)context.Filters.FirstOrDefault(x => x.GetType() == typeof(AllowAnonymousFilter)); if (allowAnonymousFilter != null) { return; } StringValues bearer = new StringValues(); try { var userId = Convert.ToInt32(context.HttpContext.User.Claims.FirstOrDefault().Value); context.HttpContext.Request.Headers.TryGetValue("Authorization", out bearer); if (userId <= 0 || bearer.ToString().Split(' ')[1] == null) { await UnAuthorized(context); return; } } catch (Exception) { await UnAuthorized(context); return; } if (allowAnonymousFilter == null) { context.HttpContext.Request.Headers.TryGetValue("Authorization", out bearer); if (bearer == "{}" || String.IsNullOrEmpty(bearer)) { await UnAuthorized(context); } } }
/// <summary> /// configure services to be used by the asp.net runtime /// </summary> /// <param name="services">service collection</param> /// <returns>service provider instance (Autofac provider)</returns> public IServiceProvider ConfigureServices(IServiceCollection services) { try { services.AddApplicationInsightsTelemetry(_telemetrySettings.InstrumentationKey); services.Configure <ServiceConfigurationOptions>(_configuration.GetSection("ServiceConfigurationOptions")); var serviceConfigurationOptions = services.BuildServiceProvider() .GetService <IOptions <ServiceConfigurationOptions> >(); services.AddMvc(options => { var filter = #if (DEBUG) new AllowAnonymousFilter(); #else var policy = ScopePolicy.Create(serviceConfigurationOptions.Value.RequiredScopes.ToArray()); (IFilterMetadata) new AuthorizeFilter(policy) : #endif options.Filters.Add(filter); }); services.AddApiVersioning(); //Get XML documentation var path = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"); //if not generated throw an event but it's not going to stop the app from starting if (!File.Exists(path)) { BigBrother.Write(new Exception("Swagger XML document has not been included in the project")); } else { services.AddSwaggerGen(c => { c.IncludeXmlComments(path); c.DescribeAllEnumsAsStrings(); c.SwaggerDoc("v1", new OpenApiInfo { Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(), Title = "ISummonNoobs" }); c.CustomSchemaIds(x => x.FullName); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Type = UseOpenApiV2 ? SecuritySchemeType.ApiKey : SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT", }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, }, new string[0] } }); }); } services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddIdentityServerAuthentication( x => { x.ApiName = serviceConfigurationOptions.Value.ApiName; x.ApiSecret = serviceConfigurationOptions.Value.ApiSecret; x.Authority = serviceConfigurationOptions.Value.Authority; x.RequireHttpsMetadata = serviceConfigurationOptions.Value.IsHttps; //TODO: this requires Eshopworld.Beatles.Security to be refactored //x.AddJwtBearerEventsTelemetry(bb); }); var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterInstance(_bb).As <IBigBrother>().SingleInstance(); // add additional services or modules into container here var container = builder.Build(); return(new AutofacServiceProvider(container)); } catch (Exception e) { _bb.Publish(e.ToExceptionEvent()); throw; } }