IHttpContextAccessor UserId为null [英] IHttpContextAccessor UserId is null

查看:171
本文介绍了IHttpContextAccessor UserId为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引用StackOverflow中的不同问题之后,还遵循公认的答案:

是我缺少的东西还是设计框架中的问题?

我试图调用 UserId 的示例.

在视图中:

 < div class ="row">< div class ="col-md-12">< asp-action =借阅请求";asp-controller ="Book"asp-route-bookId ="@ Model.Id"class ="btn btn-primary".要求借用</a></div></div> 

在控制器中:

  [HttpGet][授权]公共异步Task< ActionResult>BorrowRequest(int bookId){尝试{var UserId = _currentUserService.UserId;等待Task.Delay(200);返回RedirectToAction(nameof(Index));}抓住{返回View();}} 

解决方案

某处正在将用户ID声明的名称从 ClaimTypes.NameIdentifier 替换为 sub 如图所示.

因此,为了不让Microsoft Identity覆盖我使用的声明名称,

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 在API启动中的 app.UseAuthentication()之前.

引用:为什么ClaimTypes.NameIdentifier没有映射到"sub"?

After referring to different questions in StackOverflow, and also following the accepted answer:

IHttpContextAccessor.HttpContext.User.Identity shows all null properties in CurrentUserService service

But still, I couldn't access the UserId from the IHttpContextAccessor, the value of UserId is null when I am trying to access:

var UserId = _currentUserService.UserId;

My CurrentUserService Looks:

 public class CurrentUserService : ICurrentUserService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CurrentUserService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        private bool _init = false;
        private string _userId;
        public string UserId
        {
            get
            {
                if (!_init)
                {
                    _userId = _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);
                    _init = true;
                }
                return _userId;
            }
        }
        ///public string UserId { get { return _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); } }

        public bool IsAuthenticated => _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;

    }

When I am not logged in and trying to access the controller, it redirects to the login page. And after the login the value of _httpContextAccessor.HttpContext?.User are also being populated as shown in the image below:

Is there something I am missing or it is the problem from the framework by design?

An example where I am trying to invoke the UserId.

In View:

 <div class="row">
        <div class="col-md-12">
            <a asp-action="BorrowRequest" asp-controller="Book" asp-route-bookId="@Model.Id" class="btn btn-primary">
                Request for Borrow
            </a>
        </div>
 </div>

In Controller:

[HttpGet]
[Authorize]
public async Task<ActionResult> BorrowRequest(int bookId)
{
    try
    {
        var UserId = _currentUserService.UserId;

        await Task.Delay(200);
        return RedirectToAction(nameof(Index));
    }
    catch
    {
        return View();
    }
}

解决方案

Something was replacing the name for claims for the user id from ClaimTypes.NameIdentifier to sub, which is shown in the figure.

So, To not let Microsoft Identity override claim names I used:

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); just before the app.UseAuthentication() in the API startup.

Referring: Why is ClaimTypes.NameIdentifier not mapping to 'sub'?

这篇关于IHttpContextAccessor UserId为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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