.netcore入門19:aspnetcore集成Swagger並自定義登錄登出功能

環境:

  • .netcore 3.1
  • vs 2019 16.5.1
  • Swashbuckle.AspNetCore 5.3.1

實驗代碼下載: https://download.csdn.net/download/u010476739/12320053

一、關於swagger說明

在使用asp.net core 進行api開發完成後,書寫api說明文檔對於程序員來說想必是件很痛苦的事情吧,但文檔又必須寫,而且文檔的格式如果沒有具體要求的話,最終完成的文檔則完全取決於開發者的心情。或者詳細點,或者簡單點。那麼有沒有一種快速有效的方法來構建api說明文檔呢?答案是肯定的, Swagger就是最受歡迎的REST APIs文檔生成工具之一!

swagger官網:https://swagger.io/
參考:ASP.NET Core WebApi使用Swagger生成api說明文檔看這篇就夠了

二、簡單webapi項目集成swagger

2.1 準備webapi項目

這裏新建一個空白的webapi項目即可。

2.2 安裝swagger的nuget包

在這裏插入圖片描述

2.3 在工程屬性上開啓xml文檔生成

在這裏插入圖片描述

2.4 在方法和模型上添加註釋

在這裏插入圖片描述
在這裏插入圖片描述

2.5 向容器中註冊swagger服務

private readonly IWebHostEnvironment webHostEnvironment;
public Startup(IConfiguration configuration,IWebHostEnvironment webHostEnvironment)
{
    Configuration = configuration;
    this.webHostEnvironment= webHostEnvironment;
}
public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
        var xmlPath = Path.Combine(webHostEnvironment.ContentRootPath, Assembly.GetExecutingAssembly().GetName().Name + ".xml");
        if (File.Exists(xmlPath))
        {
            options.IncludeXmlComments(xmlPath, true);
        }
    });
    services.AddControllers();
}

說明:
注意上面代碼中有指定生成的xml文檔的地址,如果不指定的話,瀏覽器也會顯示接口以及參數名稱,但是就不會顯示你寫的註釋,所以一定要手動將xml文檔的地址配置上去。還有,在生成工程的時候Release模式下是不會輸出xml文檔的,所以要注意這個文件是否存在(上面代碼中已自動判斷)。

2.6 註冊swagger中間件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection();
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        //如果不想帶/swagger路徑訪問的話,就放開下面的註釋
        //options.RoutePrefix = string.Empty;
    });
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

2.7 直接調試運行

瀏覽器中輸入: http://localhost:5000/swagger
在這裏插入圖片描述
由上圖可以看到Action的方法描述都列出來了,此時可以點擊右側Try it out按鈕,然後輸入要傳遞到後臺的參數以進行測試。
在這裏插入圖片描述
由上圖可以看到Schemas中顯示了模型WeatherForecast,之所以顯示它是因爲有方法的參數或返回值引用到了這個模型。

2.8 隱藏某個控制器或Action不顯示

如果你不想針對某個控制器或某個方法就在上面打上標記[ApiExplorerSettings(IgnoreApi = true)]就行,這樣瀏覽器頁面中就不會出現這個控制器或方法了,如下圖:
在這裏插入圖片描述
同理,如果這個方法不顯示的話,那麼因它而顯示的模型也不會再顯示了

三、帶身份認證的webapi項目集成swagger

上面是最簡單的一個示例。一般我們做後臺管理系統都是要有身份認證的,如果我們在swagger上測試後臺方法那麼我們必須在swagger頁面上登錄了纔行!,下面以cookie認證爲例說明。對cookie認證原理不清楚的可以參考:
.netcore入門10:分析aspnetcore自帶的cookie認證原理
.netcore入門11:aspnetcore自帶cookie的認證期限分析
.netcore入門12:aspnetcore中cookie認證之服務端保存認證信息

3.1 給webapi應用添加Cookie認證(先不管Swagger)

3.1.1 在startup.cs中注入認證服務、在管道中加入中間件

最終的代碼如下:

public void ConfigureServices(IServiceCollection services)
{
	services.AddControllers();
	services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
		.AddCookie();
    services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	  if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      app.UseAuthentication();
      app.UseRouting();
      app.UseAuthorization();
      app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllers();
      });
}

3.1.2 添加AuthController

/// <summary>
/// cookie身份認證
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly IConfiguration configuration;

    public AuthController(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    /// <summary>
    /// 登錄方法
    /// </summary>
    /// <param name="username">用戶名</param>
    /// <param name="password">用戶密碼</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<object> Login([FromForm]string username, [FromForm]string password)
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            return Ok(new
            {
                Success = false,
                Data = "不允許重複登錄!"
            });
        }
        if (username == "admin" && password == "1")
        {
            var claims = new Claim[] { new Claim("id", "1") };
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(principal);
            return new
            {
                success = true,
                data = "登錄成功!"
            };
        }
        else
        {
            return new
            {
                success = false,
                data = "登錄失敗!"
            };
        }
    }

    /// <summary>
    /// 登出
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Authorize]
    public async Task<object> LogOut()
    {
        await HttpContext.SignOutAsync();
        return Ok(new
        {
            Success = true,
            Data = "註銷成功!"
        });
    }
}

3.2 swagger集成cookie認證

首先看一下集成後的效果:
在這裏插入圖片描述

這裏的彈框需要自定義,cookie本身並不支持,所以我們在集成的時候要手寫這個文檔頁面(/swagger/ui/index.html)。

3.2.1 給swagger添加安全描述信息

最終改造後的ConfigureServices方法如下:

public void ConfigureServices(IServiceCollection services)
{
     services.AddSwaggerGen(options =>
     {
         //定義api文檔
         options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "My API", Version = "v1" });
         //包含vs生成的註釋文檔
         var xmlPath = Path.Combine(webHostEnvironment.ContentRootPath, Assembly.GetExecutingAssembly().GetName().Name + ".xml");
         if (File.Exists(xmlPath))
         {
             options.IncludeXmlComments(xmlPath, true);
         }
         //描述安全信息
         options.AddSecurityDefinition(CookieAuthenticationDefaults.AuthenticationScheme, new OpenApiSecurityScheme()
         {
             Name = CookieAuthenticationDefaults.AuthenticationScheme,
             Scheme = CookieAuthenticationDefaults.AuthenticationScheme
         });
     });
     services.AddControllers();
     services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
     services.AddAuthorization();
 }

3.2.2 在http的管道設置中,給swaggerui指定主頁

最終改造後的Configure方法如下:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseStaticFiles();
     app.UseHttpsRedirection();
     app.UseSwagger();
     app.UseSwaggerUI(options =>
     {
         options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
         //如果不想帶/swagger路徑訪問的話,就放開下面的註釋
         //options.RoutePrefix = string.Empty;
         //使用自定義的頁面(主要是增加友好的身份認證體驗)
         string path = Path.Combine(env.WebRootPath, "swagger/ui/index.html");
         if (File.Exists(path)) options.IndexStream = () => new MemoryStream(File.ReadAllBytes(path));
     });

     app.UseAuthentication();
     app.UseRouting();
     app.UseAuthorization();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });
 }

3.2.3 建立wwwroot文件夾,並準備swagger/ui/index.html文件

本案例使用的是webapi項目,沒有自帶wwwroot文件夾,所以需要自己建個文件夾,最終目錄結構如下圖:
在這裏插入圖片描述
我們上一步指定webapi的接口文檔的首頁是index.html頁面,現在我們就來編輯它:
index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>%(DocumentTitle)</title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700"
          rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="./swagger-ui.css">
    <link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
    <style>
        html {
            box-sizing: border-box;
            overflow: -moz-scrollbars-vertical;
            overflow-y: scroll;
        }

        *,
        *:before,
        *:after {
            box-sizing: inherit;
        }

        body {
            margin: 0;
            background: #fafafa;
        }
    </style>
    %(HeadContent)
</head>

<body>
    <div id="swagger-ui"></div>
    <script src="swagger-ui-bundle.js"></script>
    <script src="swagger-ui-standalone-preset.js"></script>
    <script src="ui/auth.js"></script>
    <script>
        window.onload = function () {
            var configObject = JSON.parse('%(ConfigObject)');
            // Apply mandatory parameters
            configObject.dom_id = "#swagger-ui";
            configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
            configObject.layout = "StandaloneLayout";
            configObject.requestInterceptor = function (request) {
                //do something
                return request;
            };
            if (!configObject.hasOwnProperty("oauth2RedirectUrl")) {
                configObject.oauth2RedirectUrl = window.location + "oauth2-redirect.html"; // use the built-in default
            }
            function getAuthorizeButtonText() {
                return auth.hasLogin() ? 'Logout' : 'Authorize';
            }
            function getAuthorizeButtonCssClass() {
                return auth.hasLogin() ? 'cancel' : 'authorize';
            }
            configObject.plugins = [
                function (system) {
                    return {
                        components: {
                            authorizeBtn: function () {
                                return system.React.createElement("button",
                                    {
                                        id: "authorize",
                                        className: "btn " + getAuthorizeButtonCssClass(),
                                        style: {
                                            lineHeight: "normal"
                                        },
                                        onClick: function () {
                                            var authorizeButton = document.getElementById('authorize');
                                            auth.logout(function () {
                                                authorizeButton.innerText = getAuthorizeButtonText();
                                                authorizeButton.className = 'btn ' + getAuthorizeButtonCssClass();
                                            });
                                            if (!auth.hasLogin()) {
                                                auth.openAuthDialog(function () {
                                                    authorizeButton.innerText = getAuthorizeButtonText();
                                                    authorizeButton.className = 'btn ' + getAuthorizeButtonCssClass();
                                                    auth.closeAuthDialog();
                                                });
                                            }
                                        }
                                    }, getAuthorizeButtonText());
                            }
                        }
                    }
                }
            ];
            // Build a system
            SwaggerUIBundle(configObject);
        }
    </script>
</body>

</html>

從index.html頁面中我們看到,我們根據後臺接口的定義渲染了文檔並創建了認證按鈕(Authorize),並且給這個按鈕綁定了事件。
下面看下前端認證的代碼腳本(auth.js):
auth.js:

var auth = window.auth || {};
//這個'tokenCookieName '可以刪除,本來我是想把登錄返回的cookie值在localstorage中再存一份
auth.tokenCookieName = "aspnetcore.authauth";
auth.loginUrl = "/api/Auth/Login";
auth.logoutUrl = "/api/Auth/Logout";
auth.logout = function (callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var res = JSON.parse(xhr.responseText);
                if (!res.success) {
                    console.warn(res.data);
                    return;
                }
                localStorage.removeItem("auth.hasLogin");
                callback();
            } else {
                console.warn("Logout failed !");
            }
        }
    };
    xhr.open('Get', auth.logoutUrl, true);
    xhr.send();
}
auth.hasLogin = function () {
    return localStorage.getItem("auth.hasLogin");
}
auth.openAuthDialog = function (loginCallback) {
    auth.closeAuthDialog();
    var authAuthDialog = document.createElement('div');
    authAuthDialog.className = 'dialog-ux';
    authAuthDialog.id = 'auth-auth-dialog';
    document.getElementsByClassName("swagger-ui")[1].appendChild(authAuthDialog);
    // -- backdrop-ux
    var backdropUx = document.createElement('div');
    backdropUx.className = 'backdrop-ux';
    authAuthDialog.appendChild(backdropUx);
    // -- modal-ux
    var modalUx = document.createElement('div');
    modalUx.className = 'modal-ux';
    authAuthDialog.appendChild(modalUx);
    // -- -- modal-dialog-ux
    var modalDialogUx = document.createElement('div');
    modalDialogUx.className = 'modal-dialog-ux';
    modalUx.appendChild(modalDialogUx);
    // -- -- -- modal-ux-inner
    var modalUxInner = document.createElement('div');
    modalUxInner.className = 'modal-ux-inner';
    modalDialogUx.appendChild(modalUxInner);
    // -- -- -- -- modal-ux-header
    var modalUxHeader = document.createElement('div');
    modalUxHeader.className = 'modal-ux-header';
    modalUxInner.appendChild(modalUxHeader);
    var modalHeader = document.createElement('h3');
    modalHeader.innerText = 'Authorize';
    modalUxHeader.appendChild(modalHeader);
    // -- -- -- -- modal-ux-content
    var modalUxContent = document.createElement('div');
    modalUxContent.className = 'modal-ux-content';
    modalUxInner.appendChild(modalUxContent);
    modalUxContent.onkeydown = function (e) {
        if (e.keyCode === 13) {
            //try to login when user presses enter on authorize modal
            auth.login(loginCallback);
        }
    };

    //Inputs
    createInput(modalUxContent, 'userName', 'Username or email address');
    createInput(modalUxContent, 'password', 'Password', 'password');

    //Buttons
    var authBtnWrapper = document.createElement('div');
    authBtnWrapper.className = 'auth-btn-wrapper';
    modalUxContent.appendChild(authBtnWrapper);

    //Close button
    var closeButton = document.createElement('button');
    closeButton.className = 'btn modal-btn auth btn-done button';
    closeButton.innerText = 'Close';
    closeButton.style.marginRight = '5px';
    closeButton.onclick = auth.closeAuthDialog;
    authBtnWrapper.appendChild(closeButton);

    //Authorize button
    var authorizeButton = document.createElement('button');
    authorizeButton.className = 'btn modal-btn auth authorize button';
    authorizeButton.innerText = 'Login';
    authorizeButton.onclick = function () {
        auth.login(loginCallback);
    };
    authBtnWrapper.appendChild(authorizeButton);
}
auth.closeAuthDialog = function () {
    if (document.getElementById('auth-auth-dialog')) {
        document.getElementsByClassName("swagger-ui")[1].removeChild(document.getElementById('auth-auth-dialog'));
    }
}
auth.login = function (callback) {
    var usernameOrEmailAddress = document.getElementById('userName').value;
    if (!usernameOrEmailAddress) {
        alert('Username or Email Address is required, please try with a valid value !');
        return false;
    }

    var password = document.getElementById('password').value;
    if (!password) {
        alert('Password is required, please try with a valid value !');
        return false;
    }
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var res = JSON.parse(xhr.responseText);
                if (!res.success) {
                    alert(res.data);
                    return;
                }
                localStorage.setItem("auth.hasLogin", true);
                callback();
            } else {
                alert('Login failed !');
            }
        }
    };
    xhr.open('POST', auth.loginUrl, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send("username=" + encodeURIComponent(usernameOrEmailAddress) + "&password=" + password);
}
function createInput(container, id, title, type) {
    var wrapper = document.createElement('div');
    wrapper.className = 'wrapper';
    container.appendChild(wrapper);
    var label = document.createElement('label');
    label.innerText = title;
    wrapper.appendChild(label);
    var section = document.createElement('section');
    section.className = 'block-tablet col-10-tablet block-desktop col-10-desktop';
    wrapper.appendChild(section);
    var input = document.createElement('input');
    input.id = id;
    input.type = type ? type : 'text';
    input.style.width = '100%';
    section.appendChild(input);
}

從auth.js腳本中我們可以看到:後臺登錄的接口地址、登出的接口地址,以及登錄、登出的邏輯。

3.3 瀏覽器測試

調試運行後,在瀏覽器輸入:https://localhost:5001/swagger/index.html,可以看到按鈕Authorize,,點擊後如下:
在這裏插入圖片描述
輸入用戶名和密碼:(admin 1),回車:
在這裏插入圖片描述
可以看到,已經顯示登錄了,此時你可以打開調試,觀察cookie和localstore:
在這裏插入圖片描述
在這裏插入圖片描述
從上圖中看到,認證後的cookie已保存,並且將是否登錄的標記也保存到了localstorage(爲什麼要存儲這個標記?因爲這個cookie是httponly的,js操作不了。。。),此時你刷新這個頁面會看到一直顯示登錄狀態。
當我們在登錄狀態時,點擊Logout按鈕,我們就退出登錄了,此時再查看cookie和localstorage中的存儲,我們會發現,認證時產生的cookie和標記都被清理了。

四、擴展

從上面的介紹我們知道了怎麼給webapi的接口頁面定製登錄和登出功能,但一般登錄時都會有驗證碼之類的其他選項,此時你只需要在登錄對話框上添加自己需要的即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章