首页 > 解决方案 > 为没有身份的 .net 核心创建定制的第 3 方授权

问题描述

我正在尝试建立 .net 核心站点,它是用另一种语言编写的更大的遗留系统的一部分。在这个阶段我不想重写主系统的登录/授权,所以我需要用户能够通过主系统登录并将他们登录的凭据和授权角色传递到新的 .net 系统中。

我不想在新系统中维护单独的用户数据库,因此将有效地使用旧系统作为第 3 方身份验证服务。我正在努力寻找实现这一目标的最佳方法的示例。我想象我可以在两个系统之间编写一个 OAuth 流程。

我基本上希望新系统与旧系统检查是否有人登录并获得访问权限,如果是,则让他们继续,如果没有则将他们弹回旧系统登录。

在新站点上使用没有身份的 Cookie 身份验证并以某种方式将重定向 / OAuth 过程写入遗留系统是最好的方法吗?有谁知道有关如何执行此操作的任何示例或指南?我所能找到的只是链接到第三方提供商(即谷歌、Facebook 等)的预设列表的示例。

我可以在旧系统上编写 OAuth 部分,只是不确定如何在 .net 核心站点端实现它。与往常一样,任何指导都非常受欢迎。

标签: c#asp.net-coreauthenticationrazoroauth

解决方案


据我所知,asp.net 核心包含可以与 oauth 一起使用的 OAuth 2.0 身份验证中间件。

有关如何使用它的更多详细信息,您可以参考以下示例:

注意:您好像使用了自己的认证服务器,请自行更换参数。

            services.AddAuthentication(options =>
            {
                // If an authentication cookie is present, use it to get authentication information
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                // If authentication is required, and no cookie is present, use Yourauth (configured below) to sign in
                options.DefaultChallengeScheme = "Yourauth";
            })
 .AddCookie() // cookie authentication middleware first
 .AddOAuth("Yourauth", options =>
 {
    // Oauth authentication middleware is second

    var Domain = Configuration.GetValue<string>("yourdomain");

    // When a user needs to sign in, they will be redirected to the authorize endpoint
    options.AuthorizationEndpoint = $"{Domain}/oauth2/default/v1/authorize";

    // if your OAuth server is OpenID compliant, so request the standard openid
    // scopes when redirecting to the authorization endpoint
    options.Scope.Add("openid");
     options.Scope.Add("profile");
     options.Scope.Add("email");

    // After the user signs in, an authorization code will be sent to a callback
    // in this app. The OAuth middleware will intercept it
    options.CallbackPath = new PathString("/authorization-code/callback");

    // The OAuth middleware will send the ClientId, ClientSecret, and the
    // authorization code to the token endpoint, and get an access token in return
    options.ClientId = Configuration.GetValue<string>("ClientId");
     options.ClientSecret = Configuration.GetValue<string>("ClientSecret");
     options.TokenEndpoint = $"{Domain}/oauth2/default/v1/token";

    // Below we call the userinfo endpoint to get information about the user
    options.UserInformationEndpoint = $"{Domain}/oauth2/default/v1/userinfo";

    // Describe how to map the user info we receive to user claims
    options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
     options.ClaimActions.MapJsonKey(ClaimTypes.Name, "given_name");
     options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");

     options.Events = new OAuthEvents
     {
         OnCreatingTicket = async context =>
         {
            // Get user info from the userinfo endpoint and use it to populate user claims
            var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
             request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
             request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

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

             var user = JObject.Parse(await response.Content.ReadAsStringAsync());

             context.RunClaimActions(user);
         }
     };
 });

推荐阅读