Oauth身份用户不是.net身份用户

时间:2017-10-03 15:31:00

标签: .net asp.net-core

使用.net核心1 ...当有人使用oauth2注册/登录时,身份ID由oauth提供,即使有本地用户也是如此。有没有办法将oauth用户与本地身份用户联系起来?

遵循此示例 - https://rameshksh.wordpress.com/2016/12/08/linkedin-authentication-in-asp-net-core/您可以使用“身份”登录,也可以使用Oauth登录 - 它们未连接。我错过了一些明显的东西,或者这只是它的工作方式?

1 个答案:

答案 0 :(得分:0)

我能够通过一些试错来解决这个问题......

        app.UseOAuthAuthentication(new OAuthOptions
        {
            AuthenticationScheme = "LinkedIn",
            DisplayName = "LinkedIn",

            ClientId = Configuration["linkedin:clientId"],
            ClientSecret = Configuration["linkedin:clientSecret"],

            CallbackPath = new PathString("/signin-linkedin"),

            AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization",
            TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken",
            UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,formatted-name,email-address,picture-url)",

            Scope = { "r_basicprofile", "r_emailaddress", "w_share" },
            Events = new OAuthEvents
            {
                OnTicketReceived = context =>
                {
                    // Indicate that we handled the login
                    context.HandleResponse();

                    // Default redirect path is the base path
                    if (string.IsNullOrEmpty(context.ReturnUri))
                    {
                        context.ReturnUri = "/";
                    }

                    context.Response.Redirect(context.ReturnUri);

                    return Task.FromResult(0);
                },

                OnCreatingTicket = async context =>
                {
                    // Retrieve user info
                    var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                    request.Headers.Add("x-li-format", "json"); // Tell LinkedIn we want the result in JSON, otherwise it will return XML

                    var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                    response.EnsureSuccessStatusCode();

// Do database stuff to find user using parameters provided through oauth
// Perform identity sign in using sign in manager
                    await signInManager.SignInAsync(dbUser, false);
                }
            }
        });

        app.Map("/login", builder =>
        {
            builder.Run(async context =>
            {
                // Return a challenge to invoke the LinkedIn authentication scheme
                await context.Authentication.ChallengeAsync("LinkedIn", properties: new AuthenticationProperties() { RedirectUri = "/" });
            });
        });

“OnTicketReceived”中的代码阻止中间件丢弃它自己的 LinkedIn身份验证的cookie。