Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

custom attribute for auth permission check .net

public class Over18Requirement : AuthorizationHandler<Over18Requirement>, IAuthorizationRequirement
{
  public override void Handle(AuthorizationHandlerContext context, Over18Requirement requirement)
  {
    if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
    {
      context.Fail();
      return;
    }

    var dobVal = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value;
    var dateOfBirth = Convert.ToDateTime(dobVal);
    int age = DateTime.Today.Year - dateOfBirth.Year;
    if (dateOfBirth > DateTime.Today.AddYears(-age))
    {
      age--;
    }

    if (age >= 18)
    {
      context.Succeed(requirement);
    }
    else
    {
      context.Fail();
    }
  }
}


//Then in your ConfigureServices() function you'd wire it up

services.AddAuthorization(options =>
{
    options.AddPolicy("Over18", 
        policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
});

//And finally, apply it to a controller or action method with

[Authorize(Policy = "Over18")]
Comment

custom attribute for auth permission check .net

public enum PermissionItem
{
    User,
    Product,
    Contact,
    Review,
    Client
}

public enum PermissionAction
{
    Read,
    Create,
}


public class AuthorizeAttribute : TypeFilterAttribute
{
    public AuthorizeAttribute(PermissionItem item, PermissionAction action)
    : base(typeof(AuthorizeActionFilter))
    {
        Arguments = new object[] { item, action };
    }
}

public class AuthorizeActionFilter : IAuthorizationFilter
{
    private readonly PermissionItem _item;
    private readonly PermissionAction _action;
    public AuthorizeActionFilter(PermissionItem item, PermissionAction action)
    {
        _item = item;
        _action = action;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        bool isAuthorized = MumboJumboFunction(context.HttpContext.User, _item, _action); // :)

        if (!isAuthorized)
        {
            context.Result = new ForbidResult();
        }
    }
}

public class UserController : BaseController
{
    private readonly DbContext _context;

    public UserController( DbContext context) :
        base()
    {
        _logger = logger;
    }

    [Authorize(PermissionItem.User, PermissionAction.Read)]
    public async Task<IActionResult> Index()
    {
        return View(await _context.User.ToListAsync());
    }
}
Comment

custom attribute for auth permission check .net

public class MyAuthAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //check access 
        if (CheckPermissions())
        {
            //all good, add some code if you want. Or don't
        }
        else
        {
            //DENIED!
            //return "ChallengeResult" to redirect to login page (for example)
            context.Result = new ChallengeResult(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}
That's it. No need to mess with "policies", "claims", "handlers" and other [beep]

Usage:

// GET api/Get/5
[MyAuth]
public ActionResult<string> Get(int id)
{
    return "blahblah";
}
Comment

custom attribute for auth permission check .net

public class PatientAuthorizeAttribute : TypeFilterAttribute
    {
    public PatientAuthorizeAttribute(params PatientAccessRights[] right) : base(typeof(AuthFilter)) //PatientAccessRights is an enum
    {
        Arguments = new object[] { right };
    }

    private class AuthFilter : IActionFilter
    {
        PatientAccessRights[] right;

        IAuthService authService;

        public AuthFilter(IAuthService authService, PatientAccessRights[] right)
        {
            this.right = right;
            this.authService = authService;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var allparameters = context.ActionArguments.Values;
            if (allparameters.Count() == 1)
            {
                var param = allparameters.First();
                if (typeof(IPatientRequest).IsAssignableFrom(param.GetType()))
                {
                    IPatientRequest patientRequestInfo = (IPatientRequest)param;
                    PatientAccessRequest userAccessRequest = new PatientAccessRequest();
                    userAccessRequest.Rights = right;
                    userAccessRequest.MemberID = patientRequestInfo.PatientID;
                    var result = authService.CheckUserPatientAccess(userAccessRequest).Result; //this calls DB service to check from DB
                    if (result.Status == ReturnType.Failure)
                    {
                        //TODO: return apirepsonse
                        context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                    }
                }
                else
                {
                    throw new AppSystemException("PatientAuthorizeAttribute not supported");
                }
            }
            else
            {
                throw new AppSystemException("PatientAuthorizeAttribute not supported");
            }
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: how to change the color of a single line of code in c# 
Csharp :: unity set dictionary value 
Csharp :: Photon Register Callbacks 
Csharp :: 40/100 percentage 
Csharp :: validate preview input number wpf 
Csharp :: ASP.NET C# Catch all exceptions in a class 
Csharp :: c# base vs this 
Csharp :: how to input message ox in c# 
Csharp :: C# dest 
Csharp :: v bux free 
Csharp :: how to navigate between page in wpf 
Csharp :: prevent C# app from lingering after closing in background processes 
Csharp :: how to detach the camera from the player after death unity 
Csharp :: enumerate dictionary c# 
Csharp :: How to add a button to a column in the DataGridView 
Csharp :: c# show existing form 
Csharp :: c# Lucene search - build index 
Csharp :: convert excel to datatable using epplus 
Csharp :: convert iqueryable to list c# 
Csharp :: SerializedObjectNotCreatableException: Object at index 0 is null 
Csharp :: wpf clock conrt 
Csharp :: WPF combobox filter as you type 
Csharp :: c# e-mail send 
Csharp :: object escape player unity 
Csharp :: c# read single key 
Csharp :: custom player spawner mirror 
Csharp :: C# oledb excel select column with space 
Csharp :: c# excel fix first row 
Csharp :: unity 3d animator live link 
Csharp :: unity round image 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =