public static async Task RenderHomePageAsync(HttpContext context) { if (context?.User?.Identity?.IsAuthenticated == true) { var requirement = new RolesAuthorizationRequirement(new string[] { "ADMIN" }); var authorizationService = context.RequestServices.GetRequiredService <IAuthorizationService>(); var result = await authorizationService.AuthorizeAsync(context.User, null, new IAuthorizationRequirement[] { requirement }); if (result.Succeeded) { await context.Response.WriteAsync( @"<html> <head><title>Index</title></head> <body>" + $"<h3>{context.User.Identity.Name}, you are authorized.</h3>" + @"<a href='Account/Logout'>Sign Out</a> </body> </html>"); } else { await context.ForbidAsync(); } } else { await context.ChallengeAsync(); } }
public static void Main() { Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(builder => builder .ConfigureServices(svcs => svcs .AddDbContext <UserDbContext>(options => options.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=AuthorizationDemo;Trusted_Connection=True;MultipleActiveResultSets=true")) .AddRouting() .AddAuthorization(options => { var requirement = new RolesAuthorizationRequirement(new string[] { "ADMIN" }); var policy = new AuthorizationPolicy(new IAuthorizationRequirement[] { requirement }, new string[0]); options.AddPolicy("HomePage", policy); }) .AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie()) .Configure(app => app .UseAuthentication() .UseRouting() .UseEndpoints(endpoints => { endpoints.Map("", RenderHomePageAsync); endpoints.Map("Account/Login", SignInAsync); endpoints.Map("Account/Logout", SignOutAsync); endpoints.Map("Account/AccessDenied", DenyAccessAysnc); }))) .Build() .Run(); }
public void PoliciesShouldCombine() { const string allowedRole = "test role"; var roleRequirement = new RolesAuthorizationRequirement(new[] { allowedRole }); var rolePolicy = new AuthorizationPolicy(new[] { roleRequirement }, new string[0]); var denyAnonymousRequirement = new DenyAnonymousAuthorizationRequirement(); var denyAnonymousPolicy = new AuthorizationPolicy(new[] { denyAnonymousRequirement }, new string[0]); var combinedPolicy = AuthorizationPolicy.Combine(rolePolicy, denyAnonymousPolicy); var requirements = new HashSet <IAuthorizationRequirement>(combinedPolicy.Requirements); Assert.IsTrue(requirements.Contains(roleRequirement)); Assert.IsTrue(requirements.Contains(denyAnonymousRequirement)); }
public async Task OnlyHandlesAuthZyinRequirement() { var testRole = "TestRole"; var testRoleRequirement = new RolesAuthorizationRequirement(new[] { testRole }); var identity = new ClaimsIdentity(); identity.AddClaim(new Claim(identity.RoleClaimType, testRole)); var principal = new ClaimsPrincipal(identity); var authorizationContext = new AuthorizationHandlerContext(new [] { testRoleRequirement }, principal, null); var handler = new AuthZyinHandler(this.context, this.logger); await handler.HandleAsync(authorizationContext); Assert.Single(authorizationContext.Requirements); Assert.Single(authorizationContext.PendingRequirements); }
public static async Task <AuthorizationResult> Authorize <TRequest>( this IAuthorizationService authService, ClaimsPrincipal claimsPrincipal, TRequest request, object resource) { var attributes = request.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true) .Cast <AuthorizeAttribute>() .ToList(); var policies = attributes.Where(x => x.Policy != null).Select(x => x.Policy).ToList(); var roles = attributes .Where(x => x.Roles != null) .SelectMany(x => x.Roles.Split(',')) .Select(x => x.Trim()) .ToList(); // no authorization needed, proceed if (policies.Any() == false && roles.Any() == false) { return(AuthorizationResult.Success()); } foreach (var policy in policies) { var result = await authService.AuthorizeAsync(claimsPrincipal, resource, policy); if (result.Succeeded == false) { return(result); } } if (roles.Any()) { var requirement = new RolesAuthorizationRequirement(roles); var result = await authService.AuthorizeAsync(claimsPrincipal, request, requirement); if (result.Succeeded == false) { return(result); } } return(AuthorizationResult.Success()); }
public AreaRolesAuthorizationRequirement(string area, IEnumerable <string> allowedRoles) { Area = area; AllowedRoles = allowedRoles; RolesAuthorizationRequirement = new RolesAuthorizationRequirement(allowedRoles); }
private static bool VerifyRolePermission(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement) { var roleClaims = context.User.FindAll(JwtConstants.Strings.JwtClaimIdentifiers.Rol);// FindFirst(c => c.Type == ClaimTypes.DateOfBirth && c.Issuer == "http://contoso.com").Value); var matchClaimCount = roleClaims.Count(roleClaim => requirement.AllowedRoles.Contains(roleClaim.Value)); return(matchClaimCount > 0); }