使用OpenIdConnect进行外部登录的ASP.NET身份(O365) - 无法获得声明?

时间:2018-03-30 04:26:04

标签: c# asp.net-mvc asp.net-mvc-5

我使用OpenIdConnect(O365)将ASP.NET身份与外部登录结合使用。我已在https://apps.dev.microsoft.com/注册了应用并授予了权限。应用程序的流程如下:

  1. 未注册的用户使用OpenId登录
  2. 提示用户注册(到此处工作)
  3. 用于登录O365的电子邮件地址应显示在TextBox中,当要求用户注册时,该文本框将是只读的。 (不工作)
  4. 这里的问题是变量电子邮件始终为空。我在我的范围内包含了User.Read和Email,但它似乎没有返回这些。

    如何使用用户登录O365时使用的电子邮件地址填写电子邮件?

    代码如下:

    Statup.Auth.cs

    app.UseOpenIdConnectAuthentication(
                  new OpenIdConnectAuthenticationOptions
                  {
                      Authority = "https://login.microsoft.com/common/v2.0",
                      ClientId = "clientId",
                      ClientSecret = "clientSecret",
                      Scope = "openid User.Read email offline_access",
                      RedirectUri = "redirectUri",
                      TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidateIssuer = false,
                      }
    

    控制器 - /帐户/ ExternalLoginCallback

    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (loginInfo == null)
                {
                    return RedirectToAction("Login");
                }
    
                // Sign in the user with this external login provider if the user already has a login
                var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
                switch (result)
                {
                    case SignInStatus.Success:
                        return RedirectToLocal(returnUrl);
                    case SignInStatus.LockedOut:
                        return View("Lockout");
                    case SignInStatus.RequiresVerification:
                        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
                    case SignInStatus.Failure:
                    default:
                        // If the user does not have an account, then prompt the user to create an account
                        ViewBag.ReturnUrl = returnUrl;
                        ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                        var email = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.Email);
                        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
    

1 个答案:

答案 0 :(得分:0)

好的......所以我钉了它。这就是问题所在:

修改如下:

Scope = "openid profile email offline_access"

对于电子邮件,我们必须使用preferred_username