Exemplo n.º 1
0
        protected override async System.Threading.Tasks.Task HandleRequirementAsync(
            Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext context,
            PermissionAuthorizationRequirement requirement)
        {
            if (!context.User.Identity.IsAuthenticated)
            {
                throw new ArgumentException("ko có quyền");
                //return;
            }
            // Getting user Id from claims
            string userId = context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;

            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("ko có quyền");
                // return;
            }
            //TODO: Implement caching for this

            var userPermissions = _iUserService.GetPermission(Guid.Parse(userId)).Result.Select(x => x.Key).ToList();
            var intersect       = userPermissions.Intersect(requirement.Permissions).ToList();
            var hasPermission   = false;

            if (intersect != null && intersect.Count() > 0)
            {
                hasPermission = true;
            }
            if (hasPermission)
            {
                context.Succeed(requirement);
            }
        }
        protected override Task HandleRequirementAsync(Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext context,
                                                       AdminNumberRequirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == "http://contoso.com"))
            {
                //TODO: Use the following if targeting a version of
                //.NET Framework older than 4.6:
                //      return Task.FromResult(0);
                return(Task.CompletedTask);
            }

            var dateOfBirth = Convert.ToDateTime(
                context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth &&
                                       c.Issuer == "http://contoso.com").Value);

            int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;

            if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
            {
                calculatedAge--;
            }

            if (calculatedAge >= requirement.MinimumAge && requirement.AdminNumber is 964212)
            {
                context.Succeed(requirement);
            }

            //TODO: Use the following if targeting a version of
            //.NET Framework older than 4.6:
            //      return Task.FromResult(0);
            return(Task.CompletedTask);
        }
 public void Handle_Read_PassesForContributor()
 {
     var survey = new Survey("test survey") { Contributors = new List<SurveyContributor> { new SurveyContributor { UserId = 54321 } } };
     var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
     {
         new Claim(SurveyClaimTypes.SurveyUserIdClaimType, "54321"),
         new Claim(SurveyClaimTypes.SurveyTenantIdClaimType, "12345"),
         new Claim(AzureADClaimTypes.TenantId, "tenantid")
     }));
     var authzContext = new AuthorizationHandlerContext(new IAuthorizationRequirement[] { }, principal, survey);
     var target = new TestableSurveyAuthorizationHandler();
     target.Handle(authzContext, Operations.Read, survey);
     Assert.True(authzContext.HasSucceeded);
 }
 public void Handle_Update_PassesForOwner()
 {
     var survey = new Survey("test survey") { OwnerId = 54321, TenantId = 12345 };
     var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
     {
         new Claim(SurveyClaimTypes.SurveyUserIdClaimType, "54321"),
         new Claim(SurveyClaimTypes.SurveyTenantIdClaimType, "12345"),
         new Claim(AzureADClaimTypes.TenantId, "tenantid"),
         new Claim(ClaimTypes.Role, Roles.SurveyCreator)
     }));
     var authzContext = new AuthorizationHandlerContext(new IAuthorizationRequirement[] { }, principal, survey);
     var target = new TestableSurveyAuthorizationHandler();
     target.Handle(authzContext, Operations.Update, survey);
     Assert.True(authzContext.HasSucceeded);
 }
Exemplo n.º 5
0
        public async Task HandleAsync(AuthorizationHandlerContext context)
        {
            if (context?.User?.Identity?.Name == null)
            {
                return;
            }

            var superUser = (await _siteService.GetSiteSettingsAsync()).SuperUser;

            if (String.Equals(context.User.Identity.Name, superUser, StringComparison.OrdinalIgnoreCase))
            {
                foreach (var requirement in context.Requirements.OfType<PermissionRequirement>())
                {
                    context.Succeed(requirement);
                }
            }
        }
Exemplo n.º 6
0
        protected override Task HandleRequirementAsync(Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext context, MinimumAgePolicyRequirement requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
            {
                return(Task.FromResult(0));
            }
            var dob = context.User.Claims.First(c => c.Type == ClaimTypes.DateOfBirth).Value;

            if (DateTime.TryParse(dob, out var date))
            {
                if (date.AddYears(_age) < DateTime.Now)
                {
                    context.Succeed(requirement);
                }
            }
            return(Task.FromResult(0));
        }
Exemplo n.º 7
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (!context.User.Identity.IsAuthenticated)
            {
                context.Fail();
                return;
            }

            var userId = long.Parse(context.User.Claims.First(x => x.Type == JwtRegisteredClaimNames.Sub).Value);
            //var roles = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role).Value;
            //if (string.IsNullOrWhiteSpace(roles))
            //{
            //    context.Fail();
            //    return;
            //}

            //var roleIds = roles.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => long.Parse(x));
            //if (roleIds.Contains(1))
            //{
            //    context.Succeed(requirement);
            //    return;
            //}
            //else
            //{
            var attribute = (context.Resource as RouteEndpoint).Metadata.GetMetadata <PermissionAttribute>();
            var result    = await CheckUserPermissions(userId, attribute.Codes);

            if (result)
            {
                context.Succeed(requirement);
                return;
            }
            //}
            context.Fail();
            return;
        }
 public Task HandleAsync(Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext context)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 9
0
 /// <summary>
 /// Makes a decision if authorization is allowed based on a specific requirement.
 /// </summary>
 /// <param name="context">The authorization context.</param>
 /// <param name="requirement">The requirement to evaluate.</param>
 protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement);
 internal new void Handle(AuthorizationHandlerContext context, OperationAuthorizationRequirement operation, Survey resource)
 {
     base.HandleRequirementAsync(context, operation, resource);
 }
 public void Handle_Delete_PassesForAdminUserWithOtherRoles()
 {
     var survey = new Survey("test survey") { OwnerId = 54321, TenantId = 12345 };
     var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
     {
         new Claim(SurveyClaimTypes.SurveyUserIdClaimType, "11111"),
         new Claim(SurveyClaimTypes.SurveyTenantIdClaimType, "12345"),
         new Claim(ClaimTypes.Role, Roles.SurveyReader),
         new Claim(ClaimTypes.Role, Roles.SurveyAdmin),
         new Claim(ClaimTypes.Role, Roles.SurveyReader)
     }));
     var authzContext = new AuthorizationHandlerContext(new IAuthorizationRequirement[] { }, principal, survey);
     var target = new TestableSurveyAuthorizationHandler();
     target.Handle(authzContext, Operations.Delete, survey);
     Assert.True(authzContext.HasSucceeded);
 }
 public void Handle_Delete_FailsForAdminOfDifferentTenant()
 {
     var survey = new Survey("test survey") { OwnerId = 54321, TenantId = 12345 };
     var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
     {
         new Claim(SurveyClaimTypes.SurveyUserIdClaimType, "11111"),
         new Claim(SurveyClaimTypes.SurveyTenantIdClaimType, "11111"), // Different tenant from survey
         new Claim(AzureADClaimTypes.TenantId, "tenantid"),
         new Claim(ClaimTypes.Role, Roles.SurveyAdmin)
     }));
     var authzContext = new AuthorizationHandlerContext(new IAuthorizationRequirement[] { }, principal, survey);
     var target = new TestableSurveyAuthorizationHandler();
     target.Handle(authzContext, Operations.Delete, survey);
     Assert.False(authzContext.HasSucceeded);
 }
Exemplo n.º 13
0
 /// <inheritdoc />
 public Task <IEnumerable <IAuthorizationHandler> > GetHandlersAsync(AuthorizationHandlerContext context)
 => Task.FromResult(_handlers);