public bool IsAuthorized <T>(int userId, int companyId, Permissions requiredPermission) where T : Entity { var policy = AuthorizationPolicies.GetPolicyFor <T>(requiredPermission); if (policy == null) { return(true); } var authorized = true; foreach (var rule in policy.Rules) { var permission = this.GetPermissionsOf(userId, companyId, rule.EntityType, rule.Permission) .OrderByDescending(p => p.IsDenied) .FirstOrDefault(); if (permission == null) { return(false); } authorized = authorized && !permission.IsDenied; } return(authorized); }
public bool IsAuthorized <T>(int userId, int companyId, T entity, Permissions requiredPermission) where T : Entity { var policy = AuthorizationPolicies.GetPolicyFor <T>(requiredPermission); if (policy == null) { return(true); } var authorized = true; foreach (var rule in policy.Rules) { var id = rule.GetEntityIdOf(entity); if (id == null) { id = securityRepository.LoadRuleEntityId(rule, entity); } var permission = this.GetPermissionsOf(userId, companyId, rule.EntityType, rule.Permission) .OrderByDescending(p => p.IsDenied) .FirstOrDefault(p => p.EntityId == null || p.EntityId == id); if (permission == null) { return(false); } authorized = authorized && !permission.IsDenied; } return(authorized); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(config => { config.AddPolicy(AuthorizationPolicies.ADMIN, AuthorizationPolicies.AdminPolicy()); config.AddPolicy(AuthorizationPolicies.USER, AuthorizationPolicies.UserPolicy()); }); }
public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddInMemoryApiResources(IdentityServerConfig.ApiResources) .AddInMemoryClients(IdentityServerConfig.Clients) .AddTestUsers(IdentityServerConfig.TestUsers) .AddDeveloperSigningCredential(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:5001"; options.ApiName = "foo-api"; }); services.AddSingleton <IAuthorizationHandler, BlacklistUsersHandler>(); services.AddSingleton <IAuthorizationHandler, AllowAnonymousBasedOnConfigHandler>(); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .RequireNoBlacklistedUsers() .Build(); options.AddPolicy(nameof(AuthorizationPolicies.AtLeastEditor), AuthorizationPolicies.AtLeastEditor()); options.AddPolicy(nameof(AuthorizationPolicies.AllowAnonymousBasedOnConfig), AuthorizationPolicies.AllowAnonymousBasedOnConfig()); }); services.AddControllers(); }
public static IServiceCollection AddAppSecurity(this IServiceCollection services, IConfiguration configuration) { var swaggerSection = new SwaggerSection(); configuration.Bind(SwaggerSection.SectionName, swaggerSection); services.AddIdentityServer() .AddApiAuthorization <ApplicationUser, ApplicationDbContext>(c => { c.Clients.Add(new Client { ClientId = "EventHub.Swagger", ClientName = "Swagger UI for EventHub API", AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = { new Uri(new Uri(swaggerSection.UIServer), "/swagger/oauth2-redirect.html").ToString() }, AllowedScopes = { "EventHub.Web.ApiAPI" }, RequireConsent = false, }); }); services.AddAuthentication() .AddGoogle(options => { var googleAuth = configuration.GetSection(GoogleAuthSection.SectionName).Get <GoogleAuthSection>(); options.ClientId = googleAuth.ClientId; options.ClientSecret = googleAuth.ClientSecret; }) .AddIdentityServerJwt(); services.Configure <JwtBearerOptions>( IdentityServerJwtConstants.IdentityServerJwtBearerScheme, options => { var onMessageReceived = options.Events.OnMessageReceived; options.Events.OnMessageReceived = async context => { var accessToken = context.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs/chat")) { context.Token = accessToken; } await onMessageReceived(context); }; }); services.AddAuthorization(options => { AuthorizationPolicies.AddPolicies(options); }); return(services); }
public IActionResult GetGroups() { var groups = User .Identities .SelectMany(identity => identity.FindAll(x => identity.RoleClaimType.Equals(x.Type)).Select(x => new { x.Issuer, x.Value })) .ToLookup(x => x.Issuer) .ToDictionary(x => x.Key, x => x.Select(g => AuthorizationPolicies.GetIdentityNameForSid(g.Value)).ToArray()); return(Ok(groups)); // 200 }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <RootConfigurations>(Configuration.GetSection("RootConfigurations")); services.AddSession(); #region Identity services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = Configuration.GetSection("RootConfigurations:AuthorityConfiguration:AuthorityURL").Value; options.ApiName = Configuration.GetSection("RootConfigurations:AuthorityConfiguration:ApiName").Value; options.ApiSecret = Configuration.GetSection("RootConfigurations:AuthorityConfiguration:ApiSecret").Value; options.RequireHttpsMetadata = false; }); // ======================Policies =============================================================== services.AddDistributedMemoryCache(); AuthorizationPolicies.LoadAuthorizationInjection(services); services.AddAuthorization(authorizationOption => AuthorizationPolicies.LoadPolicies(authorizationOption)); //=========================================================================================================== #endregion services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IPrincipal>(provider => provider.GetService <IHttpContextAccessor>().HttpContext.User); services.AddDbContext <IAppDbContext, AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), opt => opt.EnableRetryOnFailure()) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).EnableSensitiveDataLogging()); // =======================All Services============== services.SetAllConfiguration(Configuration); //================================================ services.AddAutoMapper(typeof(Startup)); services.Configure <FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart }); services.Configure <RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture("ar-SA"); options.SupportedCultures = new List <CultureInfo> { new CultureInfo("ar-SA"), new CultureInfo("en-US") }; options.RequestCultureProviders.Clear(); }); services.AddMemoryCache(); services.AddControllers(o => { o.EnableEndpointRouting = false; o.Filters.Add(new CultureSettingResourceFilter()); }) .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddBearerAuthentication(Configuration); services.AddAuthorization(config => { config.AddPolicy(AuthorizationPolicies.Admin, AuthorizationPolicies.AdminPolicy()); config.AddPolicy(AuthorizationPolicies.User, AuthorizationPolicies.UserPolicy()); }); services.AddSwaggerBearerAuthentication(); services.AddAuthTraining(); }
public override void CopyFrom(ServiceModelExtensionElement from) { var e = (ServiceAuthorizationElement)from; foreach (AuthorizationPolicyTypeElement ae in e.AuthorizationPolicies) { AuthorizationPolicies.Add(new AuthorizationPolicyTypeElement(ae.PolicyType)); } ImpersonateCallerForAllOperations = e.ImpersonateCallerForAllOperations; PrincipalPermissionMode = e.PrincipalPermissionMode; RoleProviderName = e.RoleProviderName; ServiceAuthorizationManagerType = e.ServiceAuthorizationManagerType; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <WebApiCoreSeedContext>(options => options.UseInMemoryDatabase(Environment.MachineName)); // Add framework services. services.AddMvc(); IAuthorizationPolicies authorizationPolicies = new AuthorizationPolicies(); services.AddSingleton(authorizationPolicies); services.AddAuthorization(options => { options.AddPolicy(nameof(AuthorizationPolicies.AdminOnly), authorizationPolicies.AdminOnly); }); //Registers the use of a jwt token services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(option => { option.Audience = Configuration["auth0:clientId"]; option.Authority = $"https://{Configuration["auth0:domain"]}/"; }); //Creates the swagger json based on the documented xml/attributes of the endpoints services.AddSwaggerGen(c => { //Metadata of the api c.SwaggerDoc("v1", GetSwaggerDoc()); var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.OperationFilter <ValidateModelResponseOperationFilter>(); }); // Register Infrastructure dependencies services.AddScoped <IRestClient>(sp => new RestClient($"https://{Configuration["auth0:domain"]}", new HttpClient())); services.AddSingleton <IAuthZeroClient>(sp => new AuthZeroClient(sp.GetRequiredService <IRestClient>(), Configuration["auth0:NonInteractiveClientId"], Configuration["auth0:NonInteractiveClientSecret"], Configuration["auth0:domain"])); services.AddTransient <IAuthZeroService>(sp => new AuthZeroService(sp.GetRequiredService <IAuthZeroClient>())); // Register Services services.AddTransient <IUserService>(sp => new UserService(sp.GetRequiredService <WebApiCoreSeedContext>())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <WebApiCoreSeedContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add framework services. services.AddMvc(); IAuthorizationPolicies authorizationPolicies = new AuthorizationPolicies(); services.AddSingleton(authorizationPolicies); services.AddAuthorization(options => { options.AddPolicy(nameof(AuthorizationPolicies.AdminOnly), authorizationPolicies.AdminOnly); }); // Register Infrastructure dependencies services.AddScoped <IRestClient>(sp => new RestClient($"https://{Configuration["auth0:domain"]}", new HttpClient())); services.AddSingleton <IAuthZeroClient>(sp => new AuthZeroClient(sp.GetRequiredService <IRestClient>(), Configuration["auth0:NonInteractiveClientId"], Configuration["auth0:NonInteractiveClientSecret"], Configuration["auth0:domain"])); services.AddTransient <IAuthZeroService>(sp => new AuthZeroService(sp.GetRequiredService <IAuthZeroClient>())); // Register Services services.AddTransient <IUserService>(sp => new UserService(sp.GetRequiredService <WebApiCoreSeedContext>())); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <MSLunchesContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add framework services. services.AddMvc().AddJsonOptions( options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); IAuthorizationPolicies authorizationPolicies = new AuthorizationPolicies(); services.AddSingleton(authorizationPolicies); services.AddAuthorization(options => { options.AddPolicy(nameof(AuthorizationPolicies.AdminOnly), authorizationPolicies.AdminOnly); }); //Registers the use of a jwt token services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(option => { option.Audience = Configuration["auth0:audience"]; option.Authority = $"https://{Configuration["auth0:domain"]}/"; }); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); //Creates the swagger json based on the documented xml/attributes of the endpoints services.AddSwaggerGen(c => { //Metadata of the api c.SwaggerDoc("v1", GetSwaggerDoc()); var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.OperationFilter <ValidateModelResponseOperationFilter>(); }); // Register Infrastructure dependencies services.AddScoped <IRestClient>(sp => new RestClient($"https://{Configuration["auth0:domain"]}", new HttpClient())); services.AddSingleton <IAuthZeroClient>(sp => new AuthZeroClient(sp.GetRequiredService <IRestClient>(), Configuration["auth0:NonInteractiveClientId"], Configuration["auth0:NonInteractiveClientSecret"], Configuration["auth0:domain"])); services.AddTransient <IAuthZeroService>(sp => new AuthZeroService(sp.GetRequiredService <IAuthZeroClient>())); // Register Services services.AddTransient <IMealService>(sp => new MealService(sp.GetRequiredService <MSLunchesContext>())); services.AddTransient <IUserLunchService>(sp => new UserLunchService(sp.GetRequiredService <MSLunchesContext>())); services.AddTransient <ILunchService>(sp => new LunchService(sp.GetRequiredService <MSLunchesContext>())); services.AddTransient <IMealTypeService>(sp => new MealTypeService(sp.GetRequiredService <MSLunchesContext>())); // Add automapper services.AddAutoMapper(new[] { typeof(LunchProfile), typeof(MealProfile), typeof(UserLunchProfile), typeof(MealTypeProfile) }); }
public IQueryable <T> Relation <T>() where T : Entity { var result = this.context.Relation <T>(); var policy = AuthorizationPolicies.GetPolicyFor <T>(Permissions.Read); if (policy == null) { return(result); } //TODO: Si el usuario no esta loggeado y existe algun tipo de policy para hacer lecturas, va a tirar unauthorized. //Ver como resolver las politicas de seguridad para usuarios anonimos var user = securityService.GetCurrentUserPrincipal(); if (user == null) { throw new UnauthorizedException(string.Empty, Permissions.Read, EntityTypes.Parse(typeof(T).Name)); } foreach (var rule in policy.Rules) { var permissions = securityService.GetPermissionsOf(user.UserId, user.CompanyId, rule.EntityType, rule.Permission) .OrderByDescending(p => p.IsDenied) .ThenBy(p => p.EntityId); var all = permissions.FirstOrDefault(p => p.EntityId == null); var allowedIds = permissions.Where(p => !p.IsDenied && p.EntityId != null) .Select(p => p.EntityId) .ToList(); var deniedIds = permissions.Where(p => p.IsDenied && p.EntityId != null) .Select(p => p.EntityId) .ToList(); Expression allowed = this.BuildAlwaysTrueExpression(); Expression denied = this.BuildAlwaysTrueExpression(); Expression isNull = this.BuildIsNullExpression(rule.EntityIdExpression); if (all != null) { if (all.IsDenied) { allowed = this.BuildExpresionFor(allowedIds, rule.EntityIdExpression); isNull = this.BuildAlwaysFalseExpression(); } else { denied = Expression.Not(this.BuildExpresionFor(deniedIds, rule.EntityIdExpression)); } } else { denied = Expression.Not(this.BuildExpresionFor(deniedIds, rule.EntityIdExpression)); allowed = this.BuildExpresionFor(allowedIds, rule.EntityIdExpression); } if (!allowedIds.Any()) { allowed = this.BuildAlwaysTrueExpression(); } if (!deniedIds.Any()) { denied = this.BuildAlwaysTrueExpression(); } var filter = Expression.AndAlso(allowed, denied); filter = Expression.OrElse(isNull, filter); result = result.Where(Expression.Lambda <Func <T, bool> >(filter, rule.EntityIdExpression.Parameters)); } return(result); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "EmployeeDetails API", Version = "v1", Description = "Description for the API goes here.", Contact = new OpenApiContact { Name = "S", Email = string.Empty, Url = new Uri("https://localhost:44336/"), }, }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(config => { config.AddPolicy(AuthorizationPolicies.ADMIN, AuthorizationPolicies.AdminPolicy()); config.AddPolicy(AuthorizationPolicies.USER, AuthorizationPolicies.UserPolicy()); }); services.AddDbContext <MainContext>(options => { //options.UseSqlServer options.UseSqlServer(Configuration["ConnectionStrings:DbConnectionString"]); } ); }
public static void ConfigureAuthentication(this IServiceCollection services, IConfiguration configuration) { AuthorizationPolicies.LoadAuthorizationInjection(services); services.AddAuthorization(authorizationOption => AuthorizationPolicies.LoadPolicies(authorizationOption)); //services.AddDistributedMemoryCache(); services.AddAuthentication(option => { option.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultChallengeScheme = "oidc"; }) .AddCookie((options) => { //options.SlidingExpiration = true; //// Expire the session of 15 minutes of inactivity //options.ExpireTimeSpan = TimeSpan.FromMinutes(3); options.AccessDeniedPath = configuration.GetSection("RootConfiguration:AuthorityConfiguration:AccessDeniedPath").Value; }) .AddOpenIdConnect("oidc", option => { option.Authority = configuration.GetSection("RootConfiguration:AuthorityConfiguration:AuthorityURL").Value; option.ClientSecret = configuration.GetSection("RootConfiguration:AuthorityConfiguration:ClientSecret").Value; option.ClientId = configuration.GetSection("RootConfiguration:AuthorityConfiguration:ClientId").Value; var changeValidateIssuer = configuration.GetSection("RootConfiguration:AuthorityConfiguration:ChangeValidateIssuer").Value.ToLower() == "true"; option.ResponseType = "code id_token token"; option.Scope.Add("openid"); option.Scope.Add("offline_access"); option.Scope.Add("profile"); option.Scope.Add("roles"); option.Scope.Add("MonafasatApi"); option.SaveTokens = true; option.RequireHttpsMetadata = false; option.GetClaimsFromUserInfoEndpoint = true; option.SignedOutCallbackPath = new PathString("/signout-callback-oidc"); //option.SignedOutRedirectUri = new PathString("/signin-oidc"); option.SignedOutRedirectUri = new PathString("/Account/Logout"); if (changeValidateIssuer) { option.TokenValidationParameters.ValidateIssuer = false; } option.Events.OnAuthorizationCodeReceived = async(opt) => { if (opt.Principal.UserRoles().Count == 0) { return; } await SyncUserWithRolesAsync(opt); }; option.Events.OnAuthenticationFailed = async(context) => { context.HandleResponse(); await context.Response.WriteAsync("option.Events.OnAuthenticationFailed: " + context.Exception.Message + "\n" + context.Exception.StackTrace); }; option.Events.OnRemoteFailure = (context) => { return(Task.CompletedTask); }; //option.Events.OnTicketReceived = async (context) => //{ // context.Properties.ExpiresUtc = DateTime.UtcNow.AddMinutes(3); //}; }); }