<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<httpCookies httpOnlyCookies="true" lockItem="true" />
<authentication mode="Windows" />
<!--<httpCookies httpOnlyCookies="true" requireSSL="true"
/>-->
</system.web>
[AuthFiler1(Roles = "Access2,Moderators")]
[Authentication]
public class HomeController : Controller
{
public ActionResult Index()
{
PrincipleClassDemo pp
= new PrincipleClassDemo();
var vvv = pp.MyFunction();
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description
page.";
return View();
}
[AllowAnonymous]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
public class PrincipleClassDemo
{
//https://www.c-sharpcorner.com/UploadFile/puranindia/system-security-principal-in-net/
[PrincipalPermission(SecurityAction.Demand,
Role = @"Access2")]
public string MyFunction()
{
return "Declarative
control for the role of Role1 is truly successfully. his function can be
executed by you!";
}
[PrincipalPermissionAttribute(SecurityAction.Demand,
Name = "MyUser", Role = "Role1")]
public static void PrivateInfo()
{
//Output of private data
Console.WriteLine("You have access to the private
data!");
}
}
protected void Application_PostAuthenticateRequest(Object
sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies["AppAuthentication"];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var userAuthenticationModel =
JsonConvert.DeserializeObject<UserAuthenticationModel>(authTicket.UserData);
CustomPrincipal principal
= new CustomPrincipal(userAuthenticationModel.UserName);
principal.UserId = userAuthenticationModel.UserId;
principal.UserName = userAuthenticationModel.UserName;
principal.Roles = userAuthenticationModel.Roles.Select(x
=>x.RoleName).ToArray<string>();
principal.SessionExpiration = userAuthenticationModel.ExpiresOn;
HttpContext.Current.User =
principal;
}
}
@if (User.IsInRole("headerH2GettingStarted"))
{
<h2 id="headerH2GettingStarted">Getting started</h2>
}
USE [Authdemo]
GO
/****** Object: StoredProcedure
[dbo].[GetRoleAssetDetails] Script Date: 19-03-2019
18:39:57 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetRoleAssetDetails]') AND type in(N'P', N'PC'))
DROP PROCEDURE [dbo].[GetRoleAssetDetails]
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__33D4B598]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] DROP CONSTRAINT [CK__RoleAsset__IsAct__33D4B598]
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__31EC6D26]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] DROP CONSTRAINT [CK__RoleAsset__IsAct__31EC6D26]
GO
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__300424B4]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] DROP CONSTRAINT [CK__RoleAsset__IsAct__300424B4]
GO
/****** Object: Table
[dbo].[Users] Script Date: 19-03-2019 18:39:57 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
DROP TABLE [dbo].[Users]
GO
/****** Object: Table
[dbo].[UserRoles] Script Date: 19-03-2019 18:39:57
******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserRoles]') AND type in (N'U'))
DROP TABLE [dbo].[UserRoles]
GO
/****** Object: Table
[dbo].[Roles] Script Date: 19-03-2019 18:39:57 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))
DROP TABLE [dbo].[Roles]
GO
/****** Object: Table
[dbo].[RoleAssetMapping] Script Date: 19-03-2019
18:39:57 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]') AND type in(N'U'))
DROP TABLE [dbo].[RoleAssetMapping]
GO
/****** Object: Table
[dbo].[Asset] Script Date: 19-03-2019 18:39:57 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Asset]') AND type in (N'U'))
DROP TABLE [dbo].[Asset]
GO
/****** Object: Table
[dbo].[Asset] Script Date: 19-03-2019 18:39:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Asset]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Asset](
[AssetId]
[int] IDENTITY(1,1) NOT NULL,
[AssetName]
[int] NOT NULL,
CONSTRAINT [PK_dbo.Asset] PRIMARY KEY CLUSTERED
(
[AssetId] ASC,
[AssetName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object: Table
[dbo].[RoleAssetMapping] Script Date: 19-03-2019
18:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]') AND type in(N'U'))
BEGIN
CREATE TABLE [dbo].[RoleAssetMapping](
[AssetId]
[int] IDENTITY(1,1) NOT NULL,
[AssetName]
[nvarchar](max) NOT NULL,
[AssetFileFullPath]
[nvarchar](max) NOT NULL,
[AssetFileFullName]
[nvarchar](max) NOT NULL,
[IsActive]
[bit] NOT NULL DEFAULT ((1)),
[IsActiveForAdmin]
[int] NOT NULL DEFAULT ((0)),
[IsActiveForAccess2]
[int] NOT NULL DEFAULT ((0)),
[IsActiveForAccess1]
[int] NOT NULL DEFAULT ((0)),
CONSTRAINT [PK_dbo.RoleAssetMapping] PRIMARY KEY CLUSTERED
(
[AssetId] ASC,
[IsActive] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
/****** Object: Table
[dbo].[Roles] Script Date: 19-03-2019 18:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Roles](
[RoleId]
[int] IDENTITY(1,1) NOT NULL,
[RoleName]
[nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Roles] PRIMARY KEY CLUSTERED
(
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
/****** Object: Table
[dbo].[UserRoles] Script Date: 19-03-2019 18:39:58
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UserRoles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UserRoles](
[UserRoleId]
[int] IDENTITY(1,1) NOT NULL,
[UserId]
[int] NOT NULL,
[RoleId]
[int] NOT NULL,
CONSTRAINT [PK_dbo.UserRoles] PRIMARY KEY CLUSTERED
(
[UserRoleId] ASC,
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
/****** Object: Table
[dbo].[Users] Script Date: 19-03-2019 18:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Users](
[UserId]
[int] IDENTITY(1,1) NOT NULL,
[Username]
[nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Users] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET IDENTITY_INSERT [dbo].[RoleAssetMapping] ON
GO
INSERT [dbo].[RoleAssetMapping] ([AssetId], [AssetName], [AssetFileFullPath], [AssetFileFullName], [IsActive],[IsActiveForAdmin], [IsActiveForAccess2], [IsActiveForAccess1]) VALUES (2, N'headerH2GettingStarted', N'C:',N'Index.cs', 1, 1, 1, 1)
GO
INSERT [dbo].[RoleAssetMapping] ([AssetId], [AssetName], [AssetFileFullPath], [AssetFileFullName], [IsActive],[IsActiveForAdmin], [IsActiveForAccess2], [IsActiveForAccess1]) VALUES (5, N'headerH2Getmorelibraries', N'C:',N'Index.cs', 1, 1, 0, 0)
GO
SET IDENTITY_INSERT [dbo].[RoleAssetMapping] OFF
GO
SET IDENTITY_INSERT [dbo].[Roles] ON
GO
INSERT [dbo].[Roles] ([RoleId], [RoleName]) VALUES (1, N'Admin')
GO
INSERT [dbo].[Roles] ([RoleId], [RoleName]) VALUES (2, N'Access2')
GO
INSERT [dbo].[Roles] ([RoleId], [RoleName]) VALUES (3, N'Access1')
GO
SET IDENTITY_INSERT [dbo].[Roles] OFF
GO
SET IDENTITY_INSERT [dbo].[UserRoles] ON
GO
INSERT [dbo].[UserRoles] ([UserRoleId], [UserId], [RoleId]) VALUES (1, 2, 2)
GO
INSERT [dbo].[UserRoles] ([UserRoleId], [UserId], [RoleId]) VALUES (2, 1, 1)
GO
INSERT [dbo].[UserRoles] ([UserRoleId], [UserId], [RoleId]) VALUES (3, 2, 3)
GO
SET IDENTITY_INSERT [dbo].[UserRoles] OFF
GO
SET IDENTITY_INSERT [dbo].[Users] ON
GO
INSERT [dbo].[Users] ([UserId], [Username]) VALUES (1, N'User1')
GO
INSERT [dbo].[Users] ([UserId], [Username]) VALUES (2, N'KRAJAP')
GO
SET IDENTITY_INSERT [dbo].[Users] OFF
GO
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__300424B4]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] WITH CHECK ADD CHECK (([IsActiveForAdmin]<=(1)))
GO
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__31EC6D26]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] WITH CHECK ADD CHECK (([IsActiveForAccess2]<=(1)))
GO
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK__RoleAsset__IsAct__33D4B598]') AND parent_object_id = OBJECT_ID(N'[dbo].[RoleAssetMapping]'))
ALTER TABLE [dbo].[RoleAssetMapping] WITH CHECK ADD CHECK (([IsActiveForAccess1]<=(1)))
GO
/****** Object: StoredProcedure
[dbo].[GetRoleAssetDetails] Script Date: 19-03-2019
18:39:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetRoleAssetDetails]') AND typein (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE
[dbo].[GetRoleAssetDetails] AS'
END
GO
-- =============================================
--
Author: <Author,,Name>
-- Create date: <Create Date,,>
--
Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[GetRoleAssetDetails]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra
result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT [AssetId]
,[AssetName]
,'Admin' AS RoleName
,1 AS RoleId
FROM [dbo].[RoleAssetMapping]
WHERE [IsActive] = 1 AND [IsActiveForAdmin] = 1
UNION
SELECT [AssetId]
,[AssetName]
,'Access2' AS RoleName
,2 AS RoleId
FROM [dbo].[RoleAssetMapping]
WHERE [IsActive] = 1 AND [IsActiveForAccess2] = 1
UNION
SELECT [AssetId]
,[AssetName]
,'Access1' AS RoleName
,3 AS RoleId
FROM [dbo].[RoleAssetMapping]
WHERE [IsActive] = 1 AND [IsActiveForAccess1] = 1
END
GO
public class UserRole
{
public Int64 UserId { get; set; }
public string UserName { get; set; }
public List<UserRoleModel> Roles { get; set; }
}
public class UserAuthenticationModel
{
public Guid UserAuthenticationId { get; set; }
public Int64 UserId { get; set; }
public string UserName { get; set; }
public DateTime ExpiresOn { get; set; }
public DateTime CreatedOn { get; set; }
public List<UserRoleModel> Roles { get; set; } = new List<UserRoleModel>();
}
public class UserRoleModel
{
public string UserName { get; set; }
public Int64 UserId { get; set; }
public int RoleId { get; set; }
public string RoleName { get; set; }
}
public class RoleAssetMapping
{
public int AssetId { get; set; }
public string AssetName { get; set; }
public string AssetFileFullPath { get; set; }
public string AssetFileFullName { get; set; }
public bool IsActive { get; set; }
public string RoleName { get; set; }
public int RoleId { get; set; }
}
public class AuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext
filterContext)
{
if (!filterContext.ActionDescriptor.IsDefined
(typeof(AllowAnonymousAttribute), true) &&
!filterContext.ActionDescriptor.ControllerDescriptor.IsDefined
(typeof(AllowAnonymousAttribute), true))
{
// Check for authorization
HttpCookie
getCookieFromRequest = filterContext.HttpContext.Request.Cookies.Get("AppAuthentication");
if (getCookieFromRequest == null)
{
var userNameWithDomain =
filterContext.HttpContext.Request.LogonUserIdentity.Name;
var userName = userNameWithDomain.Substring(
filterContext.HttpContext.Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1);
var conn = new SqlConnection("Data Source=.;Initial
Catalog=Authdemo;Integrated Security=True");
List<UserRoleModel>
userRoles = conn.QuerySql<UserRoleModel>(
"SELECT
Username, US.UserId, UsrRols.RoleId, Rols.RoleName FROM USERS US
INNER JOIN UserRoles UsrRols on US.UserId =
UsrRols.UserId INNER JOIN Roles Rols on UsrRols.RoleId =
Rols.RoleId WHERE Username = @UserName"
, new { UserName = userName }).ToList();
UserAuthenticationModel
userAuthenticationModel = new UserAuthenticationModel();
if (userRoles != null &&
userRoles.Count > 0)
{
var cookieExpirationTime = DateTime.Now.AddHours(1);
userAuthenticationModel.UserName
= userName;
userAuthenticationModel.UserId
= userRoles.FirstOrDefault().UserId;
userAuthenticationModel.UserAuthenticationId
= Guid.NewGuid();
userAuthenticationModel.CreatedOn
= DateTime.Now;
userAuthenticationModel.ExpiresOn
= cookieExpirationTime;
userAuthenticationModel.Roles
= userRoles;
string userData =
JsonConvert.SerializeObject(userAuthenticationModel);
FormsAuthenticationTicket
authTicket = new FormsAuthenticationTicket
(
1,
userAuthenticationModel.UserName, DateTime.Now, cookieExpirationTime, false, userData
);
string encryptedUserData =
FormsAuthentication.Encrypt(authTicket);
HttpCookie
setCookie = new HttpCookie("AppAuthentication");
setCookie.Value
= encryptedUserData;
setCookie.Expires
= cookieExpirationTime;
setCookie.Shareable
= false;
filterContext.HttpContext.Response.Cookies.Add(setCookie);
CustomPrincipal
principal = new CustomPrincipal(userAuthenticationModel.UserName);
principal.UserId
= userAuthenticationModel.UserId;
principal.UserName
= userAuthenticationModel.UserName;
principal.Roles
= userAuthenticationModel.Roles.Select(x => x.RoleName).ToArray<string>();
principal.SessionExpiration
= userAuthenticationModel.ExpiresOn;
HttpContext.Current.User
= principal;
}
}
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext)
{
// throw new
NotImplementedException();
}
}
public class AuthFiler1Attribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase
httpContext)
{
var CurrentUser = HttpContext.Current.User as CustomPrincipal;
var roles = Roles.Split(',');
var result = (from q in CurrentUser.Roles
join a in roles on q equals a
select new { q }).ToList();
if ((CurrentUser == null) ||
CurrentUser != null &&
CurrentUser.SessionExpiration < DateTime.Now)
{
HttpContext.Current.User
= null;
return false;
}
else if (result.Count == 0)
{
return false;
}
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal
myUser = (WindowsPrincipal)System.Threading.Thread.CurrentPrincipal;
GenericIdentity
MyIdentity = newGenericIdentity(httpContext.Request.LogonUserIdentity.Name.ToString());
GenericPrincipal
MyPrincipal = new GenericPrincipal(MyIdentity,
CurrentUser.Roles);
System.Threading.Thread.CurrentPrincipal
= MyPrincipal;
////Return user values
//String Name = MyPrincipal.Identity.Name;
//bool Auth =
MyPrincipal.Identity.IsAuthenticated;
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext
filterContext)
{
var CurrentUser = HttpContext.Current.User as CustomPrincipal;
RedirectToRouteResult
routeData = null;
if (CurrentUser == null)
{
routeData
= new RedirectToRouteResult
(new System.Web.Routing.RouteValueDictionary
(new
{
area
= "UserAccount",
controller
= "UserAccount",
action
= "LogOut",
}
));
}
else
{
routeData
= new RedirectToRouteResult
(new System.Web.Routing.RouteValueDictionary
(new
{
area
= "UserAccount",
controller
= "UserAccount",
action
= "AccessDenied"
}
));
}
filterContext.Result
= routeData;
}
}
public class CustomPrincipal : IPrincipal
{
#region Identity Properties
public Int64 UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime SessionExpiration { get; set; }
public string[] Roles { get; set; }
#endregion
public IIdentity Identity
{
get; private set;
}
//public bool IsInRole(string role)
//{
// if (Roles.Any(r
=> role.Contains(r)))
// {
// return
true;
// }
// else
// {
// return
false;
// }
//}
public bool IsInRole(string assetName)
{
var conn = new SqlConnection("Data Source=.;Initial
Catalog=Authdemo;Integrated Security=True");
List<RoleAssetMapping>
userRoles = conn.QuerySql<RoleAssetMapping>(" [dbo].[GetRoleAssetDetails]").ToList();
var result = (from q in userRoles.Where(w => w.AssetName ==
assetName).Select(s => s.RoleName)
join a in Roles on q equals a
select new { q }).ToList();
if (result.Count > 0)
{
return true;
}
return false;
}
public CustomPrincipal(string username)
{
Identity
= new GenericIdentity(username);
}
}
google adsense calculate revenue
ReplyDeletegoogle adsense income calculator
adsense revenue estimator
adsense revenue estimator
adsense earnings calculator
adsense revenue calculator
google adsense income calculator
Adsense Money Calculator
adsense estimator
adsense income calculator
adsense estimator
google adsense calculate revenue
google adsense revenue calculator
Adsense Money Calculator
google adsense revenue calculator
adsense income calculator
adsense earnings calculator
google adsense income calculator
google adsense calculate revenue
google adsense calculator
website adsense earning checker