Signalr手持令牌验证
Posted fger
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Signalr手持令牌验证相关的知识,希望对你有一定的参考价值。
服务端在respose中设置好cookie,浏览器发请求都会自动带上,不需要做额外设置
但是如果客户端是非浏览器,或者要兼容多种客户端,这个方法就不行了
一、Js端
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div class="container"> <div class="row"> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> User..........<input type="text" id="userInput" /> <br /> Message...<input type="text" id="messageInput" /> <input type="button" id="sendButton" value="Send Message" /> </div> </div> <div class="row"> <div class="col-12"> <hr /> </div> </div> <div class="row"> <div class="col-6"> </div> <div class="col-6"> <ul id="messagesList"></ul> </div> </div> </div> <script src="~/lib/signalr/dist/browser/signalr.js"></script> <script type="text/javascript"> "use strict"; var url = "/chatHub"; //本地站点可以直接写"/chat" var loginToken = "token"; // JWT验证码。不带Bearer var connection = new signalR.HubConnectionBuilder().withUrl(url, { accessTokenFactory: () => loginToken }).build(); //Disable send button until connection is established document.getElementById("sendButton").disabled = true; connection.on("ReceiveMessage", function (user, message) { var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); var encodedMsg = user + " says " + msg; var li = document.createElement("li"); li.textContent = encodedMsg; document.getElementById("messagesList").appendChild(li); }); connection.start().then(function () { document.getElementById("sendButton").disabled = false; }).catch(function (err) { return console.error(err.toString()); }); document.getElementById("sendButton").addEventListener("click", function (event) { var user = document.getElementById("userInput").value; var message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(function (err) { return console.error(err.toString()); }); event.preventDefault(); }); </script> </body> </html>
二、Startup.cs配置端
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System; using System.Text; using System.Threading.Tasks; using test.Hubs; //3、引用 处理客户端 - 服务器通信的高级管道 namespace test { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } 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.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); //JWT令牌配置 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }).AddJwtBearer("JwtBearer", options => { options.Audience = "Audience"; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SecurityKey")), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "Issuer", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "Audience", // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain Account of clock drift, set that here ClockSkew = TimeSpan.Zero }; options.Events = new JwtBearerEvents { OnMessageReceived = (context) => { if (!context.HttpContext.Request.Path.HasValue) { return Task.CompletedTask; } //重点在于这里;判断是Signalr的路径 var accessToken = context.HttpContext.Request.Query["access_token"]; var path = context.HttpContext.Request.Path; if (!(string.IsNullOrWhiteSpace(accessToken)) && path.StartsWithSegments("/chatHub")) { context.Token = accessToken; return Task.CompletedTask; } return Task.CompletedTask; } }; }); //1、添加服务 services.AddSignalR(); } // 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.UseCors(builder => { builder.SetIsOriginAllowed(origin => true) .AllowAnyHeader() .WithMethods("GET", "POST") .AllowCredentials(); }); //默认静态资源路径wwwroot app.UseStaticFiles(); //默认启动cookie app.UseCookiePolicy(); //添加授权服务 app.UseAuthentication(); //配置 app.UseSignalR(routes => //2、引用 { //SignalrHub为后台代码中继承Hub的类,"/chatHub"为请求路由地址; routes.MapHub<ChatHub>("/chatHub"); }); //启动MVC app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
以上是关于Signalr手持令牌验证的主要内容,如果未能解决你的问题,请参考以下文章
使用参考令牌的 ASPNETCore SignalR 身份验证
如何使 SignalR 承载身份验证安全或如何不记录查询字符串