温馨提示×

C#中OAuth认证的实现方法

c#
小樊
88
2024-09-02 13:34:47
栏目: 编程语言

在C#中,实现OAuth认证通常需要使用第三方库,如IdentityModel或者Microsoft.AspNetCore.Authentication.OAuth。以下是一个简单的示例,展示了如何在ASP.NET Core应用程序中使用Microsoft.AspNetCore.Authentication.OAuth实现OAuth认证。

  1. 首先,安装Microsoft.AspNetCore.Authentication.OAuth NuGet包:
dotnet add package Microsoft.AspNetCore.Authentication.OAuth
  1. 在Startup.cs文件中,配置OAuth认证服务:
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Security.Claims;

namespace OAuthExample
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "OAuth";
                options.DefaultChallengeScheme = "OAuth";
            })
            .AddOAuth("OAuth", options =>
            {
                options.ClientId = Configuration["OAuth:ClientId"];
                options.ClientSecret = Configuration["OAuth:ClientSecret"];
                options.CallbackPath = new PathString("/signin-oauth");
                options.AuthorizationEndpoint = Configuration["OAuth:AuthorizationEndpoint"];
                options.TokenEndpoint = Configuration["OAuth:TokenEndpoint"];
                options.UserInformationEndpoint = Configuration["OAuth:UserInformationEndpoint"];

                options.SaveTokens = true;

                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");

                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        // 获取用户信息
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

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

                        // 添加自定义用户信息
                        context.RunClaimActions(user);
                    }
                };
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
  1. 在appsettings.json文件中,添加OAuth提供商的配置信息:
{
  "OAuth": {
    "ClientId": "your_client_id",
    "ClientSecret": "your_client_secret",
    "AuthorizationEndpoint": "https://example.com/oauth/authorize",
    "TokenEndpoint": "https://example.com/oauth/token",
    "UserInformationEndpoint": "https://example.com/oauth/userinfo"
  }
}
  1. 创建一个控制器,用于处理登录和回调请求:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace OAuthExample.Controllers
{
    [Route("[controller]")]
    public class AccountController : Controller
    {
        [HttpGet("Login")]
        public IActionResult Login()
        {
            return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "OAuth");
        }

        [HttpGet("Logout")]
        public IActionResult Logout()
        {
            return SignOut(new AuthenticationProperties { RedirectUri = "/" }, "OAuth");
        }

        [HttpGet("OAuthCallback")]
        public IActionResult OAuthCallback()
        {
            return LocalRedirect("/");
        }
    }
}
  1. 在视图中,添加登录和注销按钮:
<a asp-controller="Account" asp-action="Login">Login</a>
<a asp-controller="Account" asp-action="Logout">Logout</a>

这样,你就可以在ASP.NET Core应用程序中使用OAuth认证了。请注意,这个示例仅用于演示目的,实际项目中可能需要根据具体需求进行调整。

0