溫馨提示×

C# webapi swagger怎樣添加授權

c#
小樊
222
2024-07-31 09:15:17
欄目: 編程語言

要在C# Web API中添加授權,可以使用OAuth 2.0授權框架來實現。首先需要安裝Microsoft.AspNet.WebApi.OAuth包,并在WebApiConfig中配置OAuth授權。

以下是一個簡單的示例:

首先在NuGet包管理器中安裝Microsoft.AspNet.WebApi.OAuth包:

Install-Package Microsoft.AspNet.WebApi.OAuth

然后在WebApiConfig中配置OAuth授權:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // 配置OAuth授權
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // 配置Web API路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

接下來,創建一個繼承自OAuthAuthorizationServerProvider的類來實現OAuth授權邏輯:

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        // 驗證用戶名和密碼
        if (context.UserName == "admin" && context.Password == "admin")
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "The username or password is incorrect.");
            return;
        }
    }
}

最后在Global.asax.cs中注冊OAuth授權服務:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // 配置OAuth授權服務
    var oAuthServerOptions = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new CustomOAuthProvider()
    };

    app.UseOAuthAuthorizationServer(oAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

這樣就可以在C# Web API中添加授權,并使用Swagger進行文檔化。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女