无法从声明中获取用户名 [英] Unable to get the Username from claims

查看:98
本文介绍了无法从声明中获取用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 

我已经跟着这个 

I have followed this 

嗨 

我有关注此网址docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-asp-webapp  for my web

I have followed this url docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-asp-webapp for my web

我使用以下代码获取用户的电子邮件用户名 

And I have used the following code to get the username which email of the user 

  var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;

            var email = userClaims.FindFirst(ClaimTypes.Upn)?。Value;

 var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
            var email = userClaims.FindFirst(ClaimTypes.Upn)?.Value;

如果我将它保存在一个页面中,这可以正常工作,但是当我在多个页面中使用相同的代码时会导致问题。

This works fine if I keep this in one page but it cause problem when I have the same code in multiple pages.

创建一个循环。

请帮我解决。

我使用以下代码获取用户的电子邮件用户名 

And I have used the following code to get the username which email of the user 

  var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity ;

            var email = userClaims.FindFirst(ClaimTypes.Upn)?。Value;

 var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
            var email = userClaims.FindFirst(ClaimTypes.Upn)?.Value;

如果我将它保存在一个页面中,这可以正常工作,但是当我在多个页面中使用相同的代码时会导致问题。

This works fine if I keep this in one page but it cause problem when I have the same code in multiple pages.

创建一个循环。

请帮我解决。

推荐答案

您好Seshendra,

Hi Seshendra,

请您告诉我们您的例外情况越来越好我相信当您从一个页面重定向到第二个页面时,用户未经过身份验证,并且没有从cookie中获取令牌。在第二页上,if(Request.IsAuthenticated)条件是
返回false。

Could you please show us the exception that you are getting. I believe when you redirect from one page to second page, the user is not authenticated and it is not taking token from cookies. And on second page the if (Request.IsAuthenticated) condition is returning false.

如果在每个视图中使用相同的代码,请确保使用if(Request.IsAuthenticated) )视图顶部的条件或更好地编写包装类并使用它来获取名称,来自声明的电子邮件。

If you using the same code in each view, make sure you use if(Request.IsAuthenticated) condition on top of the view or better to write a wrapper class and use that to get the name, email from claims.

请在startup.cs中添加以下代码 - > ConfigureServices(IServiceCollection服务)方法。

And please add the below code in startup.cs --> ConfigureServices(IServiceCollection services) method.

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();  并运行您的应用程序。有关cookie身份验证的更多信息,请查看以下文档

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); and run your application. For more information on cookie authentication, please check the below documentation

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

我希望这能解决问题。

谢谢。





这篇关于无法从声明中获取用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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