SignalR and OpenId Connect

2019-02-27 17:55发布

问题:

I have a server which uses ASP.NET Core Web Api and OpenIddict as authorization framework. Now I've added an SignalR host and want to add authorisation to it.

From different sources I found that SignalR (JS Client) wants that you send the access token in the querystring or by cookie as websockets don't support headers.

As the authentication middleware doesn't check the querystring or cookie container for an authorization entry I need to implement such an provider/retriever/resolver which reads this value by myself.

I've found a solution for IdentityServer but nothing about OpenIddict.

Where/How do I implement such an token resolver with OpenIddict?

回答1:

If you use JwtBearerAuthentication then you can use OnMessageReceived to set token:

Events = new JwtBearerEvents()
{
   OnMessageReceived = async (ctx) =>
   {
        ctx.Token = ctx.Request.Query["<qs-name>"];
   }
}

Or if you use IdentityServerAuthentication then you can use TokenRetriever(not tested but it should be something like this):

   TokenRetriever = (ctx) =>
   {
        return ctx.Request.Query["<qs-name>"];
   }


回答2:

Just like @adem-caglin mentioned, in IdentityserverAuthentication you use TokenRetriever and can go with the built-in functions if what you're after is the standard bearer header or a query string

TokenRetriever = (request) => 
{
    // by default calls TokenRetrieval.FromAuthorizationHeader()(request);
    // check if request is to signalr endpoint and only then apply FromQueryString
    return TokenRetrieval.FromQueryString()(request);
}