请注意 - 这仅适用于服务器端身份的情况(即 IdentityServer4 创建令牌,而不是 Angular)
创建全新的 asp.net core 5 angular spa 应用表单模板:
dotnet new angular --auth Individual
npm i @microsoft/signalr
修改的 Startup.cs
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",builder => builder
.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSignalR();
. . .
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
. . .
endpoints.MapHub<NewsHub>("/newshub");
});
添加集线器类
[Authorize]
public class NewsHub : Hub
{
}
修改的 WeatherForecastController:
private IHubContext<NewsHub> _hub;
public WeatherForecastController(ILogger<WeatherForecastController> logger,IHubContext<NewsHub> hub)
{
_hub = hub;
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var timerManager = new TimerManager(() =>
_hub.Clients.All.SendAsync("servermessage",DateTime.Now.Ticks.ToString()));
修改 fetch-data.component.ts
constructor(http: HttpClient,@Inject('BASE_URL') baseUrl: string) {
http.get<WeatherForecast[]>(baseUrl + 'weatherforecast').subscribe(result => {
this.forecasts = result;
this.hub = new HubConnectionBuilder()
.withUrl("/newshub")
.build();
this.hub.on("servermessage",(m: string) => { console.log(m); });
this.hub.start()
.then(() => console.log('MessageHub Connected'))
.catch(err => console.log('MessageHub Connection Error: ' + err.toString()));
},error => console.error(error));
}
SignalR 集线器的授权失败。输出窗口:
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.UserInfoEndpoint for /connect/userinfo
IdentityServer4.ResponseHandling.UserInfoResponseGenerator: Information: Profile service returned the following claim types: sub preferred_username name
IdentityServer4.Hosting.IdentityServerMiddleware: Information: Invoking IdentityServer endpoint: IdentityServer4.Endpoints.CheckSessionEndpoint for /connect/checksession
[2021-08-01T15:43:11.337Z] Information: normalizing '/newshub' to 'https://localhost:44306/newshub'.
Failed to load resource: the server responded with a status of 401 () [https://localhost:44306/newshub/negotiate?negotiateVersion=1]
[2021-08-01T15:43:11.347Z] Error: Failed to complete negotiation with the server: Error
[2021-08-01T15:43:11.347Z] Error: Failed to start the connection: Error
MessageHub Connection Error: Error
如果我删除 [Authorize] 属性 - 它工作正常
EDIT 给那些说我使用 cookie 但需要不记名令牌的人。这不是真的。当我尝试在集线器类上将 Cookie 指定为授权方案时,出现此错误:
System.InvalidOperationException: No authentication handler is registered for the scheme 'Cookies'.
The registered schemes are: Identity.Application,Identity.External,Identity.TwoFactorRememberMe,Identity.TwoFactorUserId,idsrv,idsrv.external,IdentityServerJwt,IdentityServerJwtBearer.