Skip to content

Instantly share code, notes, and snippets.

@ErikAndreas
Created March 21, 2019 08:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErikAndreas/72c94a0c8a9e6e632f44522c41be8ee7 to your computer and use it in GitHub Desktop.
Save ErikAndreas/72c94a0c8a9e6e632f44522c41be8ee7 to your computer and use it in GitHub Desktop.
Azure Functions SignalR service authentication using imperative ("dynamic") binding of userId for negotiate, assuming jwt is set from client using accessTokenFactory. Use case when not using app service authentication.
const connection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:7071/api/v1.0/messages/binding',
{ accessTokenFactory: () => "aJwtToken" })
.build();
private const string AUTH_HEADER_NAME = "Authorization";
private const string BEARER_PREFIX = "Bearer ";
/** Test with imperative binding
*/
[FunctionName("MessagesNegotiateBinding")]
public static IActionResult NegotiatBinding(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route="v1.0/messages/binding/negotiate")] HttpRequest req,
IBinder binder,
ILogger log)
{
if (req.Headers.ContainsKey(AUTH_HEADER_NAME) &&
req.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
{
var token = req.Headers["Authorization"].ToString().Substring(BEARER_PREFIX.Length);
log.LogInformation("with binding " + token);
// extract userId from token
var userId = "userIdExctractedFromToken"; // needs real impl...
var connectionInfo = binder.Bind<SignalRConnectionInfo>(new SignalRConnectionInfoAttribute{HubName = "messages", UserId = userId});
log.LogInformation("negotiated "+ connectionInfo);
// connectionInfo contains an access key token with a name identifier claim set to the authenticated user
return (ActionResult) new OkObjectResult(connectionInfo);
}
else
{
return (ActionResult) new BadRequestObjectResult("No access token submitted.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment