Search code examples
c#asp.netauthenticationsignalrclaims-based-identity

Anonymous users with claims tokens in ASP.NET core?


I'm creating a site for a game where the intention is that users will be able to visit the site and start playing the game without first having to create an account. The game is played by the browser connecting to and communicating with SignalR.

I'd like to be able to use the Context.User.Claims name identifier to persistently identify users, even though they're anonymous. Either the server or the browser would automatically create a GUID/UUID and that would be their username, persisted across browser sessions in local storage or a cookie.

Obviously the user could clear this storage/cookie and get a new anonymous user ID - that's fine, and not a security issue.

But is there an established way to do this with ASP.NET Core Identity? It all seems to be based around the assumption that the user is going to explicitly sign in to be issued their claims token. Is there a way I can use claims with this semi-anonymous user concept?


Solution

  • The easiest way to do it is using a cookie.

    If that is not acceptable for your scenario, you can issue a token on the server-side (from a registration endpoint) that you associate with user's session. You can persist the issued token on client side for sending as authorization header for subsequent calls to your server.

    You can create tokens and poplate them with claims using libraries like Microsoft.AspNetCore.Authentication.JwtBearer

    You can also validate the token and read its claims with every request and populate the Claims collection.