【发布时间】:2015-06-03 12:02:00
【问题描述】:
在我的 MVC 应用程序中,我当前正在 Application_PostAuthenticateRequest() 方法中设置 Thread.CurrentPrincipal = HttpContext.Current.User,例如
protected void Application_PostAuthenticateRequest()
{
Thread.CurrentPrincipal = HttpContext.Current.User;
}
这允许我在其他程序集(即服务层)中使用 Thread.CurrentPrincipal。例如:
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.AspNet.Identity;
namespace ServiceLayer
{
public class FinancialAccount
{
public decimal Balance { get; set; }
public string Owner { get; set; }
}
public class FinancialAccountRepository
{
public FinancialAccount GetById(int id)
{
if (id == 1)
return new FinancialAccount {Owner = "ac40fe16-1971-4b0d-b4d5-af850d0c2c05", Balance = 40324234};
return new FinancialAccount {Owner = "3e2d1b43-1c63-4263-8c52-44d050279596", Balance = 100};
}
}
public class FinancialService
{
private readonly FinancialAccountRepository _financialAccountRepository;
public FinancialService()
{
_financialAccountRepository = new FinancialAccountRepository();
}
[PrincipalPermission(SecurityAction.Demand, Role = Constants.RoleNames.AccountHolder)]
[PrincipalPermission(SecurityAction.Demand, Role = Constants.RoleNames.BankManager)]
public string GetFinancialAccountDetails(int accountId)
{
FinancialAccount financialAccount = _financialAccountRepository.GetById(accountId);
ThrowExceptionIfUnauthorized(financialAccount);
return "The account balance of account: " + accountId + " is " + financialAccount.Balance.ToString("C");
}
private void ThrowExceptionIfUnauthorized(FinancialAccount financialAccount)
{
if (financialAccount.Owner != Thread.CurrentPrincipal.Identity.GetUserId() && !Thread.CurrentPrincipal.IsInRole(Constants.RoleNames.BankManager))
throw new SecurityException();
}
}
}
这一切似乎都很完美,尽管我有两个顾虑:
- 可以在 PostAuthenticationRequest 方法中设置 Thread.CurrentPrincipal 吗?
- 可以在我的服务层引用使用 Microsoft.AspNet.Identity 吗?
我需要引用 Microsoft.AspNet.IDentity 的原因是因为 IPrincipal 不包含 userId,它只包含用户名。
如果其中任何一项被认为是不好的做法,我该如何解决当前的问题?
【问题讨论】:
标签: c# asp.net asp.net-mvc security asp.net-identity