DerDane
DerDane

Reputation: 31

SignalR .Net-Framework how to implement Authentication

since I am rather new to SignalR and couldn't really find anything online, I want to ask my questions here.

I use SignalR with C# and .Net-Framework and want to Implement a function in which i can login with Username and Password to the Host/Hubs with specific Roles, but I couldn't really find anything helpfull in this regard at the Microsoft Docs. (https://learn.microsoft.com/en-us/aspnet/signalr/overview/security/hub-authorization)

So my Question is:

Thanks for the Help
DerDane

Upvotes: 1

Views: 606

Answers (1)

Victor
Victor

Reputation: 2371

I use an Attribute for that:

public class AuthorizeRolesAttribute : AuthorizeAttribute
{
    public AuthorizeRolesAttribute(params string[] roles)
    {
        this.Roles = string.Join(",", roles);
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException(nameof(httpContext));
        }

        // Make sure the user is authenticated.
        var roles = this.Roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (var role in roles)
        {
            if (httpContext.User.IsInRole(role))
            {
                return true;
            }
        }
        
        return false;
    }
}

Usage:

[AuthorizeRoles("Admin")]
public class ExampleHub...

UPDATE

  1. Authentication is not a trivial topic. If you want to dive deeper into it, take a look at https://learn.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-6.0 to understand how to authenticate a user. Then, at https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-6.0 you can see how roles are associated with a previously authenticated identity. Generally, you will never do this manually. You use existing frameworks, which are already proven. In httpContext.User.Identity you have access to your identity, the logged in user. I think it can be very interesting for you to understand the pipeline of ASP .NET. Search for "asp net pipeline diagram" and also check this https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0 for more information about the middleware. There is a lot going on behind the scenes. You can just use them but it's always interesting to know them to a greater or lesser extent.

  2. You define the roles. If your application is to manage a restaurant, you can create roles such as "waiter", "cook"... while in an educational center they can be "teacher", "student", "director", etc.

You can get a list of roles like this:

var roleStore = new RoleStore<IdentityRole>(context);
var roleMngr = new RoleManager<IdentityRole>(roleStore); 
var roles = roleMngr.Roles.ToList();
  1. To add a role to user, you can use UserManager.AddToRole.

Upvotes: 2

Related Questions