首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在特定方面访问当前用户

如何在特定方面访问当前用户
EN

Stack Overflow用户
提问于 2018-10-14 14:55:04
回答 3查看 829关注 0票数 1

如果我在这个论文中采用了最后一个场景:

然后我的主要层会是这样的:

  • UI服务(MVC应用程序)
  • 业务层
  • 安全服务(用作MS标识框架的包装类库)
  • 使用以前的安全服务授权业务层方法的方面。
代码语言:javascript
运行
复制
 public class EditEmployeeData : OnMethodBoundaryAspect
    {

        public override void OnEntry(MethodExecutionArgs args)
        {
            Employee emp = (Employee)args.Instance;
            ((System.Security.Claims.ClaimsIdentity)System.Web.HttpContext.Current.User.Identity).HasClaim("Employee", "EditName");
        }
    } 

我想在运行时设置当前用户。

  • 如何访问当前用户,以便在业务层的特定功能上授权他?
  • 授权应该更接近UI来禁用/隐藏功能并防止调用不允许的操作方法吗?(在首选的场景中,安全层和UI之间没有任何交互!)
EN

回答 3

Stack Overflow用户

发布于 2018-10-22 04:29:23

更新

请看这个答案关于使用索赔.

在控制器中,您可以获得如下所示的当前用户:

代码语言:javascript
运行
复制
using Microsoft.AspNet.Identity.Owin;

public class MyController : Controller
{
    // this code will return 0 if user is not authenticated
    protected long GetUserId()
    {
       // note: I have changed the default UserId type from Guid to long
       return User.Identity.GetUserId<long>(); 

       /* 
        * use this if you are using Guid UserIds (which is the default)     
        * return User.Identity.GetUserId();
        */
    }

如果您想知道如何更改UserId__的类型,请参阅UserId

如果您可以访问HttpContext**,,您可以获得如下用户:**

代码语言:javascript
运行
复制
// note that I have changed UserId from Guid to long
HttpContext.Current.User.Identity.GetUserId<long>()

如果您想获得,请使用此 (这里有更多的信息):

代码语言:javascript
运行
复制
// this is how you get user manager from OwinContext    
var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
// Get ApplicationUser from UserManager 
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());

如何访问当前用户,以便在业务层的特定功能上授权他?

如果您需要访问服务中的当前用户,您可以通过传递它,也可以通过进行注入。使用inject,您可以将UserId注入到服务中:

代码语言:javascript
运行
复制
kernel.Bind<MyService>().ToConstructor(ctorArg => new MyService(
            HttpContext.Current.User.Identity.GetUserId<long>()).InRequestScope(); 

这就是MyService类的样子:

代码语言:javascript
运行
复制
public class MyService
{
    private readonly long _userId;

    public MyService(long userId)
    {
       // this service always has access to current user (if logged in)
        _userId = userId;
    }
    // more code...

我不知道你的授权过程是什么.ASP.NET标识,已经为您实现了授权任务。这是在ApplicationUserManagerApplicationSignInManager中实现的,后者附带了ASP.NET MVC默认模板。您可以在操作/类上使用[Authorize]属性来防止未经授权的访问:

代码语言:javascript
运行
复制
[Authorize] // <-- restricts all action methods of the class, unless marked [AllowAnonymous]
public class MyController : Controller
{
    [HttpPost]
    [Authorize] // <-- restricts this particular action method
    public ActionResult MyAction(long id)
    {
       // do some action which requires authorization
    }

关于DDD层,请看一下这个此链接,它解释了属于每个层的服务。

票数 2
EN

Stack Overflow用户

发布于 2018-10-19 13:32:41

如何访问当前用户以授权他在业务层中的特定功能?

要访问业务层上的用户信息,可以键入名为ICurrentUser的接口。

代码语言:javascript
运行
复制
namespace AOPSample
{
    public interface ICurrentUser
    {
        User GetCurrentUser();
    }

    public class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
        public string Role { get; set; }
    }
}

CurrentUser类必须能够从公共位置读取用户的信息。HttpContext可用于此。

让我们为此编写一个助手类。

代码语言:javascript
运行
复制
using System.Web;

namespace AOPSample
{
    public class ContextHelper
    {
        public T Get<T>()
        {
            T local = default(T);
            string key = typeof(T).GUID.ToString();
            if (HttpContext.Current.Items.Contains(key))
            {
                local = (T)HttpContext.Current.Items[key];
            }
            return local;
        }

        public T Get<T>(string key)
        {
            T local = default(T);
            if (HttpContext.Current.Items.Contains(key))
            {
                local = (T)HttpContext.Current.Items[key];
            }
            return local;
        }

        public void Set<T>(T value)
        {
            string str = typeof(T).GUID.ToString();
            HttpContext.Current.Items[str] = value;
        }

        public void Set<T>(T value, string key)
        {
            HttpContext.Current.Items[key] = value;
        }
    }
}

我们的CurrentUser类将使用助手类返回用户信息。

代码语言:javascript
运行
复制
namespace AOPSample
{
    public class CurrentUser : ICurrentUser
    {
        public User GetCurrentUser()
        {
            return new ContextHelper().Get<User>();
        }
    }
}

现在,用户信息使用HttpContext类写入ContextHelper类,并为此使用正确的位置拦截器类。

代码语言:javascript
运行
复制
public class EditEmployeeData : OnMethodBoundaryAspect
    {

        public override void OnEntry(MethodExecutionArgs args)
        {
            Employee emp = (Employee)args.Instance;
            ((System.Security.Claims.ClaimsIdentity)System.Web.HttpContext.Current.User.Identity).HasClaim("Employee", "EditName");

            new ContextHelper().Set<User>(new User
            {

            });
        }
    } 

您可以使用ICurrentUser从域层访问用户信息。HttpContext对于每个请求和响应都是唯一的。

是否应该更接近UI来禁用/隐藏功能,并防止调用不允许的操作方法?(在首选的场景中,安全层和UI之间没有任何交互!)

这是你的选择

在我看来,您可以获取用户权限并使用缓存记录它们,并将它们用于客户端操作,但根据服务器端使用的技术,您可以以类似的方式存储每个请求的用户信息。例如,wcf存储OperationContext的正确位置。

票数 1
EN

Stack Overflow用户

发布于 2018-10-17 17:52:39

如果使用ASP.NET Identity,可以尝试以下方法以获取当前用户:

代码语言:javascript
运行
复制
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

//If you use int instead of string for primary key, use this:
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.GetUserId()));

希望这能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52803922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档