Skip to main content

Adding Policies ASPNET CORE Identity

Adding Policies ASPNET CORE Identity


@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

include this in viewImports.cshtml page so that this can be accessed across all cshtml pages in that solution

@{
                if ((await AuthorizationService.AuthorizeAsync(User, "AdminOnly")).Succeeded)
                {
                         <delete-confirmation confirm="deleteConfirm(dataItem)" heading="'Delete Client'" content="'All information related to client will be deleted'" item-to-delete="client"></delete-confirmation>
                 }
            }

add this in the view

____________________________________________________________

Extension method to check if a user contains any roles

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Verisk3E.WebHub.WebApp
{
    public static class CheckUserRoles
    {
        public static bool CheckIfUserHasRoles(this ClaimsPrincipal claims, string[] roles)
        {
            try
            {
                ClaimsPrincipal principal = claims as ClaimsPrincipal;
                var x = roles.Any(i => roles.Contains(i));
                return true;
            }
            catch (Exception)
            {
                return false;
            }
           
        }
    }
}

___________________________________________________________________________

 public static class CheckUserRoles
    {
        public static bool CheckIfUserHasRoles(this ClaimsPrincipal claims, string[] roles)
        {
            try
            {
                return claims.Claims.Where(i => i.Type.Equals(ClaimTypes.Role)).Select(i => i.Value)
                    .Any(i => roles.ToList().Contains(i));
            }
            catch (Exception)
            {
                return false;
            }
         
        }
    }

Comments