Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

SecurityContext Class - .NET Core

RSS
Modified on Mon, Feb 08, 2021, 10:34 AM by Administrator Categorized as ASP·NET Security, ·Net Framework

Overview

The following class provides a means of maintaining the security context that is, metadata about the user for a .NET Core system, including a website and supporting apps.

It is recommended to place this class in the Data Layer, so that any auditing data (CreatedBy, UpdatedBy) is readily available.

Code

using System;
using System.Collections.Generic;
using System.Linq;

public class SecurityContext
{
    public int? TenantId { get; set; }
    public string UserId { get; set; }
    public string Username { get; set; }
    public List<PermissionEnum> Permissions { get; set; }
    public bool PermissionsAreEnforced { get; set; }

    public bool HasAnyPermission(params PermissionEnum[] permissions)
    {
        var items = new List<PermissionEnum>(permissions);

        return items.Any(x => Permissions.Contains(x));
    }

    private static LocalDataStoreSlot _localSlot;

    static SecurityContext()
    {
        _localSlot = System.Threading.Thread.AllocateDataSlot();
    }

    public static SecurityContext Current
    {
        get
        {
            if (System.Web.HttpContext.Current == null)
            {
                return (SecurityContext)System.Threading.Thread.GetData(_localSlot);
            }

            return (SecurityContext)System.Web.HttpContext.Current?.Items["SecurityContext"];
        }
        set
        {
            if (System.Web.HttpContext.Current != null)
            {
                System.Web.HttpContext.Current.Items["SecurityContext"] = value;
            }
            else
            {
                System.Threading.Thread.SetData(_localSlot, value);
            }
        }
    }

}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.