c#-4.0 - ADFS 2.0 MVC4 获取用户信息

标签 c#-4.0 adfs2.0

我有一个使用 ADFS2 身份验证运行的 .Net 4.5 MVC4 Web 应用程序。当我访问该网站时,我被重定向并通过联合服务器登录,这部分效果很好。

现在在我的应用程序中我想获取有关用户的信息。 发现很多页面描述了我在谷歌搜索时应该如何做这件事,但我一定错过了一些东西,因为无论我怎么做,我都会得到空白/空值。

我创建了一个测试 Controller ,它只打印我在 google 上找到的两个 Claims 对象中的信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Web.Controllers
{
    public class ClaimsController : Controller
    {
        public String Index()
        {
            System.Security.Claims.ClaimsPrincipal cp =
                System.Security.Claims.ClaimsPrincipal.Current;

            Microsoft.IdentityModel.Claims.IClaimsIdentity ci =
                Thread.CurrentPrincipal.Identity as Microsoft.IdentityModel.Claims.IClaimsIdentity;

            var o = new
            {
                cp_IsAuthenticated = cp.Identity.IsAuthenticated,
                cp_AuthenticationType = cp.Identity.AuthenticationType,
                cp_Name = cp.Identity.Name,
                //cp_Claims = (new JavaScriptSerializer()).Serialize(cp.Claims), // circlular reference

                ci_IsAuthenticated = ci.IsAuthenticated,
                ci_Label = ci.Label,
                ci_Name = ci.Name
                //ci_Claims = (new JavaScriptSerializer()).Serialize(cp.Claims) // circular reference
            };

            return (new JavaScriptSerializer()).Serialize(o);
        }
    }
}

结果是:

{
    "cp_IsAuthenticated":true,
    "cp_AuthenticationType":"Federation",
    "cp_Name":null,

    "ci_IsAuthenticated":true,
    "ci_Label":null,
    "ci_Name":null
}

我的印象是 "Name"= "" 应该包含我在 AD 中设置的名称。

关于我做错了什么或可以尝试什么有什么想法吗? 谢谢!

最佳答案

问题在于 ADFS 服务器未在联合请求中发回正确的声明。

正确设置声明后,此代码即可获取登录用户的身份

public string GetIdentityUserEmail()
{
    string result = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f3f2f1f6e2fbe3b9fef3f2f9e3fee3eed7f3f8faf6fef9b9f4f8fa" rel="noreferrer noopener nofollow">[email protected]</a>";

    Microsoft.IdentityModel.Claims.IClaimsIdentity ci =
        Thread.CurrentPrincipal.Identity as Microsoft.IdentityModel.Claims.IClaimsIdentity;

    if (ci != null && ci.Claims != null)
    {
        var accountNameClaim = ci.Claims.Where(x => x.ClaimType.ToLower().EndsWith("windowsaccountname")).FirstOrDefault();
        if (accountNameClaim != null)
            result = accountNameClaim.Value;
    }

    return result;
}

关于c#-4.0 - ADFS 2.0 MVC4 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20567683/

相关文章:

c# - 使用 Mono 的 mcs 使用 Tuple 编译代码

c# - 如何在 asp.net 中打印 UPS 运输服务标签

adfs2.0 - 自定义用户名/密码验证器

asp.net - 将 ADFS token 传递给服务

google-chrome - ADFS 身份验证 - IE8 有效,Chrome 失败

asp.net-mvc-3 - MVC 3 - FormsAuthentication - 无法访问我的登录操作

c# - ASP.Net 请求生命周期 - Application_BeginRequest

c# - 使用单键 c# 创建 JSON 数组

ssl - ADFS 2.0。找出每个 X.509 证书的用途和值(value)

wif - 基于声明的身份验证-SharePoint和一般