I have a SPA (angular 7) and an API (.Net Core) which I authenticate with Azure AD. I'm using adal-angular4 to integrate my angular application with AAD.
Everything works great, but I'm also using SignalR with the API as server and when I try to connect from my SPA I get 401 Unauthorized on the negotiate "request" and I get this back in the Response Headers:
The request contains my Bearer token in the Authorization header, and when I run the token through jwt.io, I can see that the "aud" value is the Azure AD ClientId for my SPA.
All regular request to the API contains the same token and I have no issues with those. I have [Authorize] on all my Controllers and on my Hub, but it's only the SignalR Hub that causes this issue.
My server Startup:
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
private IHostingEnvironment _env;
public void ConfigureServices(IServiceCollection services)
{
StartupHandler.SetupDbContext(services, Configuration.GetConnectionString("DevDb"));
// Setup Authentication
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options =>
{
Configuration.Bind("AzureAD", options);
});
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add AzureAD object so it can be injected
services.Configure<AzureAdConfig>(Configuration.GetSection("AzureAd"));
services.AddSignalR(options =>
{
options.EnableDetailedErrors = true;
options.KeepAliveInterval = TimeSpan.FromSeconds(10);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseDeveloperExceptionPage();
app.UseHsts();
}
app.UseCookiePolicy();
app.UseHttpsRedirection();
//app.UseCors("AllowAllOrigins");
app.UseCors(builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod().AllowAnyHeader();
builder.AllowCredentials();
});
app.UseAuthentication();
app.UseSignalR(routes => routes.MapHub<MainHub>("/mainhub"));
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(_env.ContentRootPath, "Files")),
RequestPath = new PathString("/Files")
});
app.UseMvc();
}
My SignalR Hub:
[Authorize]
public class MainHub : Hub
{
private readonly IEntityDbContext _ctx;
public MainHub(IEntityDbContext ctx)
{
_ctx = ctx;
_signalRService = signalRService;
}
public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
return base.OnDisconnectedAsync(exception);
}
}
And this is my SignalRService on my angular client. I'm running startConnection() in the constructor of app.component.ts.
export class SignalRService {
private hubConnection: signalR.HubConnection;
constructor(private adal: AdalService) {}
startConnection(): void {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(AppConstants.SignalRUrl, { accessTokenFactory: () => this.adal.userInfo.token})
.build();
this.hubConnection.serverTimeoutInMilliseconds = 60000;
this.hubConnection.on('userConnected', (user) =>
{
console.log(user);
});
this.hubConnection.start()
.then(() => console.log('Connection started'))
.catch(err =>
{
console.log('Error while starting connection: ' + err);
});
}
}
I have tried this solution, but I can't get that to work either.
Edit
When I've implemented the solution from the official docs, the API stops working on regular requests as well and I get back:
I've populate the IssuerSigningKey
property in TokenValidationParameters
with new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
. Am I doing anything wrong here?
/EDIT
Why won't SignalR accept my accesstoken when the API otherwise accept it?
AddAzureADBearer
by setting correct Instance and domain And if usingAddJwtBearer
addoptions.Authority = https://login.microsoftonline.com/Yourtenant
, delete ` IssuerSigningKey = SecurityKey` – Nan Yu/
to endpoint , and confirm that :options.Authority = "https://login.microsoftonline.com/yourtenant.onmicrosoft.com/"
, also any detail exception message ? – Nan Yu