如何获得在网络API调用用户上下文? [英] How to get user context during Web Api calls?

查看:116
本文介绍了如何获得在网络API调用用户上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web前端调用一个ASP网页API 2后端。身份验证与ASP身份管理。对于一些我创建的控制器,我需要知道使得呼叫的用户。我不希望有创造一些奇怪的模型,包括用户的身份(我没有在客户端,甚至存储)来传递。

对API的调用使用了承载令牌授权,我的想法是控制器应能确定在此基础上用​​户上下文,但我不知道如何实现。我已经搜查,但我不知道我在寻找准确,没有发现任何有关。我要为类似...

 公共异步任务< IHttpActionResult>邮报(ApplicationIdentity身份,WalkthroughModel数据)

更新

我发现低于看起来非常有前途的......但价值总是空!我从控制器继承ApiController并具有授权的头。

  VAR的userid = User.Identity.GetUserId();

更新2

我也尝试了所有的解决方案在Get当前用户,ApiController操作中,没有通过用户ID作为参数但没有工作。不管是什么,我得到一个身份是有效和auth'd,但有一个空用户名

更新3

下面是我在哪里了。

  [授权]
    [路线(电子邮件)]
    公共异步任务< IHttpActionResult>得到()
    {
        变种种皮= User.Identity.GetType();
        变种TESTB = User.Identity.GetUserId();
        VAR TESTC = User.Identity.AuthenticationType;
        VAR testd = User.Identity.IsAuthenticated;
        返回OK();
    }


 种皮=名称:ClaimsIdentity,
TESTB = NULL,
TESTC =承载,
testd =真


用户显然是验证,但我无法取回自己的用户ID。

更新4

我找到了答案,但我真的很不高兴吧......

  ClaimsIdentity身份=(ClaimsIdentity)User.Identity;
字符串的用户名= identity.Claims.First()值。

这让我的用户名没有任何分贝通话,但它似乎非常janky和痛苦在未来支持。很想如果你有一个更好的答案。

如果我需要什么改变什么债权发行的道路?另外任我实际需要的用户的ID我必须做出一个数据库调用的用户名转换为ID


解决方案

一个常见的​​方法是创建您的ApiControllers一个基类,并采取ApplicationUserManager的优势来获取你所需要的信息。通过这种方法,可以保持逻辑在一个位置访问该用户的信息,并在控制器内重复使用它。

 公共类BaseApiController:ApiController
{
        私人ApplicationUser _member;        公共ApplicationUserManager的UserManager
        {
            {返回HttpContext.Current.GetOwinContext()GetUserManager< ApplicationUserManager>(); }
        }        公共字符串UserIdentityId
        {
            得到
            {
                VAR用户= UserManager.FindByName(User.Identity.Name);
                返回user.Id;
            }
        }        公共ApplicationUser UserRecord
        {
            得到
            {
                如果(_member!= NULL)
                {
                    返回_member;
                }
                _member = UserManager.FindByEmail(Thread.CurrentPrincipal.Identity.Name);
                返回_member;
            }
            集合{_member =价值; }
        }
}

I have an web front end calling an ASP Web Api 2 backend. Authentication is managed with ASP Identity. For some of the controllers I'm creating I need to know the user making the call. I don't want to have to create some weird model to pass in including the user's identity (which I don't even store in the client).

All calls to the API are authorized using a bearer token, my thought is the controller should be able to determine the user context based on this but I do not know how to implement. I have searched but I don't know what I'm searching for exactly and haven't found anything relevant. I'm going for something like...

public async Task<IHttpActionResult> Post(ApplicationIdentity identity, WalkthroughModel data)

Update

I found the below which looked very promising... but the value is always null! My controller inherits from ApiController and has an Authorize header.

var userid = User.Identity.GetUserId();

Update 2

I have also tried all of the solutions in Get the current user, within an ApiController action, without passing the userID as a parameter but none work. No matter what I am getting an Identity that is valid and auth'd, but has a null UserID

Update 3

Here's where I'm at now.

    [Authorize]
    [Route("Email")]
    public async Task<IHttpActionResult> Get()
    {
        var testa = User.Identity.GetType();
        var testb = User.Identity.GetUserId();
        var testc = User.Identity.AuthenticationType;
        var testd = User.Identity.IsAuthenticated;


        return Ok();
    }

testa = Name: ClaimsIdentity,
testb = null,
testc = Bearer,
testd = true

The user is obviously authenticated but I am unable to retrieve their userID.

Update 4

I found an answer, but I'm really unhappy with it...

ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
string username = identity.Claims.First().Value;

That gets me the username without any db calls but it seems very janky and a pain to support in the future. Would love if anyone had a better answer.

What if I need to change what claims are issued down the road? Plus any time I actually need the user's id I have to make a db call to convert username to ID

解决方案

A common approach is to create a base class for your ApiControllers and take advantage of the ApplicationUserManager to retrieve the information you need. With this approach, you can keep the logic for accessing the user's information in one location and reuse it across your controllers.

public class BaseApiController : ApiController
{
        private ApplicationUser _member;

        public ApplicationUserManager UserManager
        {
            get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
        }

        public string UserIdentityId
        {
            get
            {
                var user = UserManager.FindByName(User.Identity.Name);
                return user.Id; 
            }
        }

        public ApplicationUser UserRecord
        {
            get
            {
                if (_member != null)
                {
                    return _member ; 
                }
                _member = UserManager.FindByEmail(Thread.CurrentPrincipal.Identity.Name); 
                return _member ;
            }
            set { _member = value; }
        }
}

这篇关于如何获得在网络API调用用户上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆