visual-studio-2013 - 将 Scope "wl.emails"添加到 Startup.Auth.cs 中的 MicrosoftAccountAuthenticationOptions 会导致问题

标签 visual-studio-2013 claims-based-identity asp.net-mvc-5 asp.net-identity owin

请告诉我出了什么问题。

    public void ConfigureAuth(IAppBuilder app)
    {
        var mo = new MicrosoftAccountAuthenticationOptions();
        mo.ClientId = "xxxxxxxxxxxxxxxxx";
        mo.ClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
        mo.Scope.Add("wl.basic"); // No effect if this commented out
        mo.Scope.Add("wl.emails");

        // IF I COMMENT NEXT TWO PROPERTIES, USER IS AUTHENTICATED, BUT THE DB IS NOT
        // UPDATED. LEAVE THEM AND THE REDIRECT FROM MSLIVE ENDS ON LOGIN PAGE

        mo.SignInAsAuthenticationType = "External";
        mo.Provider = new MicrosoftAccountAuthenticationProvider()
        {
            OnAuthenticated = (context) =>
                {
         // Set breakpoint here to see the context.Identity.Claims HAS CLAIMS DESIRED.
         // SO IT APPEARS TO ME Nothing to do here but verify they exist in the debugger.
         //(context.Identity.Claims).Items  ARE:  
         //{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: xxxxxxxxx}
         //{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: yyyy yyyyy} 
         //{urn:microsoftaccount:id: xxxxxxxx}  
         //{urn:microsoftaccount:name: yyyy yyyyy}  
         //{http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: xxxxxxxx@hotmail.com}
                return Task.FromResult(0);
                }
        };
        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        app.UseMicrosoftAccountAuthentication(mo);
    }

合理的期望是,框架将透明地处理将范围添加到默认的*AuthenticationOptions。随后,开发人员使用MVC5模板can extract and persist ClaimsExternalLoginConfirmation 代码中。另一个合理的期望是框架会将传入的标准 ClaimTypes 转换为框架公开的 ClaimsIdentity 中的声明。

我很高兴源代码可用 MicrosoftAccountAutheticationHandler.cs ,我会检查它来解决这个问题;缺乏回应。随着文档和框架的日趋成熟,祝 Katana 一切顺利。框架有没有办法帮助开发人员发现配置问题?

最佳答案

如果我们没有遇到相同的推理逻辑砖墙,我会同意你的观点...... 我认为这与独立的 Owin 安全上下文有关,而 Web 应用程序在单独的上下文中运行,并且您必须“播种”Web 上下文。所以我推断是这样的:

在 Startup.Auth.cs 中

var microsoftOptions =
            new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions
            {
                CallbackPath = new Microsoft.Owin.PathString("/Callbacks/External"),//register at oAuth provider
                ClientId = "xxxx",
                ClientSecret = "yyyyyyyyyyyyyyyyy",
                Provider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider
                {
                    OnAuthenticated = (context) =>
                        {
                            context.Identity.AddClaim(new Claim(providerKey, context.Identity.AuthenticationType));
                            context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Identity.FindFirstValue(ClaimTypes.Name)));
                            return System.Threading.Tasks.Task.FromResult(0);
                        }
                }
            };
        microsoftOptions.Scope.Add("wl.basic");
        microsoftOptions.Scope.Add("wl.emails");
        app.UseMicrosoftAccountAuthentication(microsoftOptions);

在AccountController中:

    [AllowAnonymous]
    public async Task<ActionResult> oAuthCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            if (User.Identity.IsAuthenticated)
                return RedirectToAction("Index", "Manage");
            else
                return RedirectToAction("Login");
        }

        var currentUser = await UserManager.FindAsync(loginInfo.Login);
        if (currentUser != null)
        {
            await StoreExternalTokensOnLocalContext(currentUser);
        }
        //.... rest as same as per AspNet Sample project.
    }


    private async Task StoreExternalTokensOnLocalContext(ApplicationUser user)
    {
        if (user == null)
            return;

        var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
        if (externalIdentity != null)
        {
            // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim 
            var currentClaims = await UserManager.GetClaimsAsync(user.Id);
            //var providerClaim = externalIdentity.FindFirstValue("provider") ?? string.Empty;
            await StoreClaim("provider", user.Id, externalIdentity);
            await StoreClaim("FacebookId", user.Id, externalIdentity);
            await StoreClaim("image", user.Id, externalIdentity);
            await StoreClaim("link", user.Id, externalIdentity);
            await StoreClaim(ClaimTypes.Name, user.Id, externalIdentity);
            await StoreClaim(ClaimTypes.Email, user.Id, externalIdentity);

            var addedClaims = await UserManager.GetClaimsAsync(user.Id);
        }
    }

    private async Task StoreClaim(string typeName, string userId, ClaimsIdentity externalIdentity)
    {
        var providerClaim = externalIdentity.Claims.FirstOrDefault(c => c.Type.Equals(typeName));
        if (providerClaim == null)
            return;
        var previousClaims = await UserManager.GetClaimsAsync(userId);
        if (previousClaims.IndexOf(providerClaim) >= 0)
            return;
        var idResult = await UserManager.AddClaimAsync(userId, providerClaim);
    }

关于visual-studio-2013 - 将 Scope "wl.emails"添加到 Startup.Auth.cs 中的 MicrosoftAccountAuthenticationOptions 会导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20116758/

相关文章:

unit-testing - 如何在VS 2013 Professional Edition上安装Microsoft Fakes(单元测试隔离)

claims-based-identity - 如何使用 Thinktecture.IdentityServer.45 在 token 中返回多个身份?

c# - ASP.NET MVC5 自定义身份验证

c# - 从另一个 Controller 重定向到 Controller 的操作,而两个 Controller 中的操作名称相同

asp.net-mvc - 自定义 500 错误页面在 ASP.NET MVC 5 中不起作用

visual-studio - 如何获取缓存在注册表中的 Visual Studio Online 凭据?

c# - 如何在更新查询中将格式为 test@test1.com 的电子邮件地址传递给 Access DB

cordova - Cordova CTP3 工具在构建时连接 etimedout

asp.net-core - 如何在配置文件更新后从 Identity Server 4 刷新声明?

c# - Asp.Net 在外部程序集中访问声明身份