Asp.Net Core混合使用cookie和JwtBearer認證方案

本身有時搗鼓一些小型演示項目,服務端主要是提供Web Api功能。爲了便於管理,須要在服務端加一些簡單的MVC網頁,用管理員身份登陸,作一些簡單的操做。html

所以須要實現一個功能,在一個Asp.Net Core網站裏,MVC網頁用cookie認證,Web Api用JwtBearer認證。雖然Identity Server 4能夠實現多種認證方案,可是我以爲它過重了,想直接在網站內集成2種認證方案。在網上沒有找到現成的DEMO,本身折騰了一段時間搞定了,因此記錄一下。git

 

建立cookie認證方案的MVC網站

新建Asp.Net Core MVC項目。無身份驗證。無https方便調試。github

 

添加登陸網頁視圖模型類LoginViewModelweb

public class LoginViewModel
    {
        public string UserName { get; set; } = "";

        [DataType(DataType.Password)]
        public string Password { get; set; } = "";
    }

給Home控制器增長登陸和註銷函數,登陸的時候要建立用戶身份標識。api

        [HttpGet]
        public IActionResult Login(string returnUrl = "")
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

        [HttpPost, ActionName("Login")]
        public async Task<IActionResult> LoginPost(LoginViewModel model, string returnUrl = "")
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                bool succee = (model.UserName == "admin") && (model.Password == "123");

                if (succee)
                {
                    //建立用戶身份標識
                    var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    claimsIdentity.AddClaims(new List<Claim>()
                    {
                        new Claim(ClaimTypes.Sid, model.UserName),
                        new Claim(ClaimTypes.Name, model.UserName),
                        new Claim(ClaimTypes.Role, "admin"),
                    });

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "賬號或者密碼錯誤。");
                    return View(model);
                }
            }

            return View(model);
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return Redirect("/Home/Index");
        }

新建一個登陸網頁Login.cshtml瀏覽器

@model MixAuth.Models.LoginViewModel

@{
    ViewData["Title"] = "登陸";
}

<div class="row">
    <div class="col-xs-10 col-sm-8 col-md-6">
        <form asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post">

            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="UserName"></label>
                <input asp-for="UserName" class="form-control" placeholder="請輸入用戶名" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password"></label>
                <input asp-for="Password" class="form-control" placeholder="請輸入密碼" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>

            <button type="submit" class="btn btn-primary">登陸</button>

        </form>
    </div>
</div>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

  

而後在Startup.cs增長cookie認證方案,並開啓認證中間件。cookie

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    //認證失敗,會自動跳轉到這個地址
                    options.LoginPath = "/Home/Login";
                });

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            //app.UseCookiePolicy();

            //開啓認證中間件
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

給Home控制器的About函數增長認證要求。app

        [Authorize]
        public IActionResult About()

把網站跑起來,點擊關於,就會跳轉到登陸頁面,登陸經過後,會調回關於頁面。async

給網頁再增長顯示用戶登陸狀態的功能。修改\Views\Shared\_Layout.cshtml,增長一個分部視圖函數

<div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                @await Html.PartialAsync("_LoginPartial")
            </div>

  

_LoginPartial.cshtml分部視圖內容

@if (User.Identity.IsAuthenticated)
{
    <form asp-controller="Home" asp-action="Logout" method="post" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a href="#">@User.Identity.Name</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">
                    退出登陸
                </button>
            </li>
        </ul>
    </form>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a asp-controller="Home" asp-action="Login" asp-route-returnUrl="/Home">
                登陸
            </a>
        </li>
    </ul>
}

  

如今能夠點擊頁面導航欄的按鈕的登陸和註銷了。

 

至此,網頁用cookie認證方案搞定。下面要在這個基礎上,增長Web Api和JwtBearer認證。

建立JwtBearer認證方案的Web Api控制器

添加一個Web Api控制器,就用默認的value好了。

增長一個JWTTokenOptions類,定義認證的一些屬性。

public class JWTTokenOptions
    {
        //誰頒發的
        public string Issuer { get; set; } = "server";

        //頒發給誰
        public string Audience { get; set; } = "client";

        //令牌密碼
        public string SecurityKey { get; private set; } = "a secret that needs to be at least 16 characters long";

        //修改密碼,從新建立數字簽名
        public void SetSecurityKey(string value)
        {
            SecurityKey = value;

            CreateKey();
        }

        //對稱祕鑰
        public SymmetricSecurityKey Key { get; set; }

        //數字簽名
        public SigningCredentials Credentials { get; set; }

        public JWTTokenOptions()
        {
            CreateKey();
        }

        private void CreateKey()
        {
            Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurityKey));
            Credentials = new SigningCredentials(Key, SecurityAlgorithms.HmacSha256);
        }
    }

  

在startup.cs增長JwtBearer認證方案。

public void ConfigureServices(IServiceCollection services)
        {
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    //認證失敗,會自動跳轉到這個地址
                    options.LoginPath = "/Home/Login";
                })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
                {
                    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = jwtTokenOptions.Key,

                        ValidateIssuer = true,
                        ValidIssuer = jwtTokenOptions.Issuer,

                        ValidateAudience = true,
                        ValidAudience = jwtTokenOptions.Audience,

                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.FromMinutes(5)
                    };
                });

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

給value控制器增長認證方案,注意指定方案名稱爲JwtBearerDefaults.AuthenticationScheme。MVC控制器無需指定方案名稱,由於默認就是CookieAuthenticationDefaults.AuthenticationScheme。

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("api/[controller]")]
    [ApiController]
    public class ValueController : ControllerBase

此時經過瀏覽器訪問Web Api控制器,http://localhost:5000/api/Value,會獲得401錯誤,這是對的,咱們也不打算經過瀏覽器的方式訪問Web Api,而是經過PC或者手機客戶端。爲了讓認證客戶端,須要增長一個獲取Token的函數,暫時放在Home控制器,它的屬性設置爲[AllowAnonymous],容許未認證者訪問。

        [AllowAnonymous]
        [HttpGet]
        public string GetToken(string userName, string password)
        {
            bool success = ((userName == "user") && (password == "111"));
            if (!success)
                return "";

            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions();

            //建立用戶身份標識
            var claims = new Claim[] 
            {
                new Claim(ClaimTypes.Sid, userName),
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.Role, "user"),
            };

            //建立令牌
            var token = new JwtSecurityToken(
                issuer: jwtTokenOptions.Issuer,
                audience: jwtTokenOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: jwtTokenOptions.Credentials
                );

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return jwtToken;
        }

編寫客戶端使用JwtBearer認證

編寫一個WPF客戶端軟件去獲取Token,訪問Web Api。

private async Task GetTokenAsync()
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    //地址
                    string path = $"{webUrl}/Home/GetToken?userName=user&password=111";

                    token = await client.DownloadStringTaskAsync(path);

                    txbMsg.Text = $"獲取到令牌={token}";
                }
            }
            catch (Exception ex)
            {
                txbMsg.Text = $"獲取令牌出錯={ex.Message}";
            }
        }

        private async Task GetValueAsync()
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    //地址
                    string path = $"{webUrl}/api/Value";

                    client.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {token}");

                    string value = await client.DownloadStringTaskAsync(path);

                    txbMsg.Text = $"獲取到數據={value}";
                }
            }
            catch (Exception ex)
            {
                txbMsg.Text = $"獲取數據出錯={ex.Message}";
            }
        }

若是直接獲取數據,可以捕捉到401錯誤。

先獲取令牌。

再獲取數據,就沒問題了。

DEMO代碼參見:

https://github.com/woodsun2018/MixAuth

相關文章
相關標籤/搜索