SignalR client specific with angularjs - asp.net

So I am fairly new with signalR and had worked with it a bit with MVCs. Now I am using it in webapi with angularjs and am a bit confused or have forgotten of what I have done. I am using bearer tokens with webapi and am trying to create a notification system.
What I want to figure out is the proper way of using angularjs with signalR. I see many people use the proxy on/invoke. Is the proxy.on is when I call the hubcontext from the server as so:
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
hubContext.Clients.User(UserId).broadcastNotification("Good morning! The time is " + DateTime.Now.ToString());
and the proxy.invoke method is from the client side? If so, which would be the best way for using notification systems (I would assume the proxy.on)?
My second question is more on sending notifications to specific users. For sending requests to specific users, I would assume you would want to do this on the hub as so:
public void SendNotification(string userId)
{
Clients.User(userId).broadcastNotification("Good morning! The time is " + DateTime.Now.ToString());
}
My startup is something like this:
public class MyProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
var userId = request.User.Identity.Name;
return userId.ToString();
}
}
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
Database.SetInitializer(new MigrateDatabaseToLatestVersion<AuthContext, Travelfy.API.Migrations.Configuration>());
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new MyProvider());
app.MapSignalR("/hubs", new HubConfiguration());
}
When I refresh my pages, I notice that all my userids are all empty strings "". I was reading that maybe it was due to using bearer tokens. If so, how would I use bearer tokens to specific the userId that I would want to send to? When I use the Clients.All everything works fine, so I'm assuming it has to be something with the startup/userIds I am getting.
Thanks

To answer your first question:
Which would be the best way for using notification systems
If you want to push notifications from the server towards the client, you have to define a new handler is to define a method on the client (with the generated proxy) like this:
How to define methods on the client that the server can call
If you want the client to call a method that lies on the server, you have to use this method:
How to call server methods from the client
To answer your second question:
For sending requests to specific users, I would assume you would want
to do this on the hub
You could use the connection ID of the client you wish to target. See this:
Calling client methods

So after a while, I was able to figure out the right answer. Because I was using bearerTokens, I really had to determine another method of obtaining the userId rather than just relying on request.User.Identity.Name. What I needed to do was pass my bearerToken to the connection.qs value.
connection.qs = { Bearer: token };
Once I was able to do that I had to route the find my user based on the token that I had sent in.
var token = request.QueryString.Get("Bearer");
var authenticationTicket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(token);

Related

How do I create a ClaimsPrincipal in my Blazor/.NetCore "Session"?

Background: I have an old MVC app that I'm experimenting with migrating to a shiny new Blazor app. Blazor seems to tick a lot of boxes for me here. Wunderbar. For clarity this is the solution template in VS2022 where there's a WASM, a .Net Core host, and a shared project. I will have plenty of api calls that need to be secured as well as UI that will be affected by various authorization policies (eg show/hide admin features).
I have a table of users with an ID and hashed password.
I can't get Blazor to use its native authentication/authorization processes with my existing store.
My latest attempt was to create an AccountController on the server app (inherits ControllerBase) and put in a Login method that gets the username and password from a json body for the moment. I have successfully ported the old authentication mechanism and I have my user that I have verified the password for. I now want to use Claims and a ClaimsPrincipal to store some of the things about the user, nothing too complex.
How do I put my ClaimsPrincipal into the app such that the WASM UI can see it AND future calls to api controllers (or ControllerBase controllers) will see it?
I have found hundreds of examples that use built-in scaffolding that lets it use EF to create tables and things but I need to use my existing stores and I can't find anything that joins the dots on how to connect the WASM and the server side.
I have read about and implemented and around the place, and tried some #authorize around the place but my WASM just doesn't know about the authenticated user.
In my login controller I have attempted a bunch of different approaches:
I implemented a custom AuthenticationStateProvider, got it into the controller via DI, called the AuthenticationStateChanged() and for the lifecycle of that one controller call I can see my HttpContext.User gets the new identity. But the WASM doesn't, and if I hit the same method again the User is null again
I tried to implement a SignInManager. This never worked well and my reading suggests that it's not compatible
I discovered ControllerBase.SignIn() which hasn't helped either
HttpContext.SignInAsync() with Cookie authentication (because that was the example I found)
I tried setting HttpContext.User directly (and tried combining that one call with the AuthenticationStateProvider implementation simultaneously)
I tried creating a fresh solution from template to pick through it, but it would appear to be reliant on hacking up my EF DataContext. I just want to find how I tell the whole contraption "Here's a ClaimsPrincipal" and have that work in both the WASM and api controllers.
I'm also not excited to have a dependency on the Duende stuff - I don't see what it brings to the table. I don't really need a whole identity provider, I already have my own code for authorizing against the database I just need to get my very boring ClaimsPrincipal into my app.
Am I going at this all wrong? Has my many years of "old school" experience stopped me from seeing a modern way of doing this? Am I trying to force cool new stuff to behave like clunky old stuff? Yes I'd love to switch to Google/Facebook/Twitter/MS authorization but that's not an option, I have passwords in a database.
You need to build a custom AuthenticationHandler.
Here's the relevant bits of one of mine (see credits at bottom for where I lifted some of the code). You'll need to pick out the pieces from the code to make your work. Ask if you have any specific problems.
The custom AuthenticationHandler looks up your user in your database and if authenticated, builds a standard ClaimsPrincipal object and adds it to the security header. You can then use the standard Authorization and AuthenticationStateProvider.
public class AppAuthenticationHandler : AuthenticationHandler<AppAuthOptions>
{
private const string AuthorizationHeaderName = "Authorization";
private const string BasicSchemeName = "BlazrAuth";
//this is my custom identity database
private IIdentityService _identityService;
public AppAuthenticationHandler(IOptionsMonitor<AppAuthOptions> options, IIdentityService identityService, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
_identityService = identityService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
await Task.Yield();
// Check the Headers and make sure we have a valid set
if (!Request.Headers.ContainsKey(AuthorizationHeaderName))
return AuthenticateResult.Fail("No Authorization Header detected");
if (!AuthenticationHeaderValue.TryParse(Request.Headers[AuthorizationHeaderName], out AuthenticationHeaderValue? headerValue))
return AuthenticateResult.Fail("No Authorization Header detected");
if (!BasicSchemeName.Equals(headerValue.Scheme, StringComparison.OrdinalIgnoreCase))
return AuthenticateResult.Fail("No Authorization Header detected");
if (headerValue is null || headerValue.Parameter is null)
return AuthenticateResult.Fail("No Token detected");
// Get the User Guid from the security token
var headerValueBytes = Convert.FromBase64String(headerValue.Parameter);
var userpasswordstring = Encoding.UTF8.GetString(headerValueBytes);
// This will give you a string like this "me#you.com:password"
if (youcantdecodethestring ))
return AuthenticateResult.Fail("Invalid Token submitted");
// Get the user data from your database
var principal = await this.GetUserAsync(userId);
if (principal is null)
return AuthenticateResult.Fail("User does not Exist");
// Create and return an AuthenticationTicket
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
// method to get the user from the database and retuen a ClaimsPrincipal
public async Task<ClaimsPrincipal?> GetUserAsync(Guid Id)
{
// Get the user object from the database
var result = await _identityService.GetIdentityAsync(Id);
// Construct a ClaimsPrincipal object if the have a valid user
if (result.Success && result.Identity is not null)
return new ClaimsPrincipal(result.Identity);
// No user so return null
return null;
}
}
You can construct a ClaimsIdentity like this:
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Sid, record.Id.ToString()),
new Claim(ClaimTypes.Name, record.Name),
new Claim(ClaimTypes.Role, record.Role)
}, "MyIdentityProvider");
public class AppAuthOptions : AuthenticationSchemeOptions
{
public string Realm = "BlazrAuth";
}
The service registration:
public static class AuthServicesCollection
{
public static void AddAppAuthServerServices(this IServiceCollection services)
{
services.AddAuthentication("BlazrAuth").AddScheme<AppAuthOptions, AppAuthenticationHandler>("BlazrAuth", null);
services.AddScoped<IIdentityService, IdentityService>();
}
}
Credits: Some of this code was derived from: https://harrison-technology.net/

How can I ensure an API call response completes before an operation in Blazor WASM

I've scoured stackoverflow looking for ways to make synchronous API calls in Blazor WASM, and come up empty. The rest is a fairly length explanation of why I think I want to achieve this, but since Blazor WASM runs single-threaded, all of the ways I can find to achieve this are out of scope. If I've missed something or someone spots a better approach, I sincerely appreciate the effort to read through the rest of this...
I'm working on a Blazor WASM application that targets a GraphQL endpoint. Access to the GraphQL endpoint is granted by passing an appropriate Authorization JWT which has to be refreshed at least every 30 minutes from a login API. I'm using a 3rd party GraphQL library (strawberry-shake) which utilizes the singleton pattern to wrap an HttpClient that is used to make all of the calls to the GraphQL endpoint. I can configure the HttpClient using code like this:
builder.Services
.AddFxClient() // strawberry-shake client
.ConfigureHttpClient((sp, client) =>
{
client.BaseAddress =
new Uri(
"https://[application url]/graphql"); // GraphQL endpoint
var token = "[api token]"; // token retrieved from login API
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
});
The trick now is getting the API token from the login API at least every 30 minutes. To accomplish this, I created a service that tracks the age of the token and gets a new token from the login API when necessary. Pared down, the essential bits of the code to get a token look like this:
public async Task<string> GetAccessToken()
{
if ((_expirationDateTime ?? DateTime.Now).AddSeconds(-300) < DateTime.Now)
{
try
{
var jwt = new
{
token =
"[custom JWT for login API validation]"
};
var payload = JsonSerializer.Serialize(jwt);
var content = new StringContent(payload, Encoding.UTF8, "application/json");
var postResponse = await _httpClient.PostAsync("https://[login API url]/login", content);
var responseString = await postResponse.Content.ReadAsStringAsync();
_accessToken = JsonSerializer.Deserialize<AuthenticationResponse>(responseString).access_token;
_expirationDateTime = DateTime.Now.AddSeconds(1800);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
return _accessToken;
}
So, now I need to wire this up to the code which configures the HttpClient used by the GraphQL service. This is where I'm running into trouble. I started with code that looks like this:
// Add login service
builder.Services.AddSingleton<FxAuthClient>();
// Wire up GraphQL client
builder.Services
.AddFxClient()
.ConfigureHttpClient(async (sp, client) =>
{
client.BaseAddress =
new Uri(
"https://[application url]/graphql");
var token = await sp.GetRequiredService<FxAuthClient>().GetAccessToken();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
});
This "works" when the application is loaded [somewhat surprisingly, since notice I'm not "await"ing the GetAccessToken()]. But the behavior if I let the 30 minute timer run out is that the first attempt I make to access the GraphQL endpoint uses the expired token and not the new token. I can see that GetAccessToken() refreshes expired token properly, and is getting called every time I utilize the FxClient, but except for the first usage of FxClient, the GetAccessToken() code actually runs after the GraphQL request. So in essence, it always uses the previous token.
I can't seem to find anyway to ensure that GetAccessToken() happens first, since in Blazor WASM you are confined to a single thread, so all of the normal ways of enforcing synchronous behavior fails, and there isn't an asynchronous way to configure the FxClient's HttpClient.
Can anyone see a way to get this to work? I'm thinking I may need to resort to writing a wrapper around the strawberry FxClient, or perhaps an asynchronous extension method that wraps the ConfigureHttpClient() function, but so far I've tried to avoid this [mostly because I kept feeling like there must be an "easier" way to do this]. I'm wondering if anyone knows away to force synchronous behavior of the call to the login API in Blazor WASM, sees another approach that would work, or can offer any other suggestion?
Lastly, it occurs to me that it might be useful to see a little more detail of the ConfigureHttpClient method. It is autogenerated, so I can't really change it, but here it is:
public static IClientBuilder<T> ConfigureHttpClient<T>(
this IClientBuilder<T> clientBuilder,
Action<IServiceProvider, HttpClient> configureClient,
Action<IHttpClientBuilder>? configureClientBuilder = null)
where T : IStoreAccessor
{
if (clientBuilder == null)
{
throw new ArgumentNullException(nameof(clientBuilder));
}
if (configureClient == null)
{
throw new ArgumentNullException(nameof(configureClient));
}
IHttpClientBuilder builder = clientBuilder.Services
.AddHttpClient(clientBuilder.ClientName, (sp, client) =>
{
client.DefaultRequestHeaders.UserAgent.Add(
new ProductInfoHeaderValue(
new ProductHeaderValue(
_userAgentName,
_userAgentVersion)));
configureClient(sp, client);
});
configureClientBuilder?.Invoke(builder);
return clientBuilder;
}

WebSockets work without valid authorization token (Spring, SockJS, STOMP, OAuth)

I am integrating with WebSockets in my Spring MVC application. The authentication mechanism for my application is OAuth.
I was able to pass my OAuth token in connection string when connecting to SockJS:
var webSocketUrl = '/websocket' + '?access_token=' + auth.access_token;
var socket = new SockJS(webSocketUrl);
var stompClient = Stomp.over(socket);
Now I can send messages and subscribe to STOMP channels:
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/greetings', function(greeting){
console.log(greeting);
});
stompClient.send("/app/hello", {}, JSON.stringify('John'));
});
In my backend I am able to get user principle injected to my STOMP controller methods (which means that Spring understands that there is an OAuth token in connection string):
#Controller
public class MyWebsocketsController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public String greet(String name, Principal authorizedUser) {
return "Hello, " + name + ", you have authorized as " + authorizedUser.getName();
}
}
Now I would like to require user authorization on all messages and subscriptions, i.e. I would like to make sure that all calls to web sockets return 403 error code if no valid token was provided when connecting to SockJS.
I add this security configuration to my project:
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.simpTypeMatchers(CONNECT, HEARTBEAT, UNSUBSCRIBE, DISCONNECT).permitAll()
.simpDestMatchers("/app/**").authenticated()
.simpSubscribeDestMatchers("/topic/**").authenticated()
.simpTypeMatchers(MESSAGE, SUBSCRIBE).denyAll()
.anyMessage().denyAll();
}
}
But it does not seem to do the job. If I remove access token from connection string, I am still able to send messages to controller and to subscribe to channel.
// This stil works:
var webSocketUrl = '/websocket'; // + '?access_token=' + auth.access_token;
Of course, now I can't get the user principle in my controller, but except for this web sockets work fine.
I would appreciate any ideas how to make this thing work or any explanation why web sockets security configuration is not working for my case. What am I missing? Thanks.

SignalR polling database for updates

I'm hoping to use SignalR to provide updates to the client, the updates are going to come from a message table which is updated when things happen across the application..
My problem is that the application will have around 500-600 concurrent users and I cant have all them having a connection to the database and constantly polling against the table..
What id like to do is have a single thing{?} polling the table and then updating the hubs rather than each connection polling.. I was thinking of using a singleton for this? so maybe when the application starts something is created that will then do all the work really..
My question is - say I had a singleton that had an event which was fired every time there was an update.. what would the performance be like for say 500 controllers subscribing to this event?
Also.. if there is a better way to do this then pleases say.. this is my first and only idea sadly!
any help would be fantastic!
EDIT: the data is bring provided by a legacy application and I have no control over how the data is entered so database polling will be needed.
ste.
I'd rather not to poll the database as it would be wasteful. I would approach this problem by opening only one single point of entry for my data (an HTTP API, etc) and then broadcast the update to all connected clients through the SignalR Hub. Brad Wilson has a super cool presentation which demonstrate this approach:
Brad Wilson - Microsoft’s Modern Web Stack, Starring ASP.NET Web API
Here is a code sample for this approach which uses ASP.NET Web API technology for data entry. It uses in-memory dictionary for data store but the data storage technique is not the concern here:
// This hub has no inbound APIs, since all inbound communication is done
// via the HTTP API. It's here for clients which want to get continuous
// notification of changes to the ToDo database.
[HubName("todo")]
public class ToDoHub : Hub { }
public abstract class ApiControllerWithHub<THub> : ApiController
where THub : IHub {
Lazy<IHubContext> hub = new Lazy<IHubContext>(
() => GlobalHost.ConnectionManager.GetHubContext<THub>()
);
protected IHubContext Hub {
get { return hub.Value; }
}
}
public class ToDoController : ApiControllerWithHub<ToDoHub> {
private static List<ToDoItem> db = new List<ToDoItem> {
new ToDoItem { ID = 0, Title = "Do a silly demo on-stage at NDC" },
new ToDoItem { ID = 1, Title = "Wash the car" },
new ToDoItem { ID = 2, Title = "Get a haircut", Finished = true }
};
private static int lastId = db.Max(tdi => tdi.ID);
// Lines removed for brevity
public HttpResponseMessage PostNewToDoItem(ToDoItem item) {
lock (db) {
// Add item to the "database"
item.ID = Interlocked.Increment(ref lastId);
db.Add(item);
// Notify the connected clients
Hub.Clients.addItem(item);
// Return the new item, inside a 201 response
var response = Request.CreateResponse(HttpStatusCode.Created, item);
string link = Url.Link("apiRoute", new { controller = "todo", id = item.ID });
response.Headers.Location = new Uri(link);
return response;
}
}
// Lines removed for brevity
}
The full source code for the application which Brad demoed is also available: https://github.com/bradwilson/ndc2012.
The other option, which you don't prefer, is make your database to fire notifications as soon as data is changed. Then, you can pick that up and broadcast it through SignalR. Here is an example:
Database Change Notifications in ASP.NET using SignalR and SqlDependency
Sorry that this solution is not signalR, but maybe you can get ideas from it.
Here is the full example for download on GitHub

Use Signalr to have a facebook like notification system

I want to implement a facebook like notification system in ASP.NET MVC 3 : notifications are sent to a specific user to notify him for an action on one of his items.
Is signalr suited for such requirement?
How could i send a notification to a specific user (all opened sessions of this user) using SignalR?
Edit
Ok, Here what i did
In the client side
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
var username = '#Html.ViewContext.HttpContext.User.Identity.Name';
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
$('#messages').append('<li>' + message + '</li>');
};
// Start the connection
$.connection.hub.start(function (){
chat.join(username);
});
});
In the server side
public class Chat : Hub
{
public void Join(string username)
{
AddToGroup(username);
}
}
And every time i need to notify a user in the controller i do the following:
IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
dynamic clients = connectionManager.GetClients<Chat>();
clients[username].addMessage("test");
Yes, SignalR is a good choice for that. Take a look at the documentation regarding Hubs (server and JS client).
You need to implement the server logic to associate your client's session with SignalR's session. You can use groups to notify all the open sessions of each user.
It is appropriate for this or you use polling, those are the two choices.
Heres a brand new video from today on this:
http://channel9.msdn.com/Shows/Web+Camps+TV/Damian-Edwards-and-David-Fowler-Demonstrate-SignalR?utm_source=dlvr.it&utm_medium=twitter

Resources