Custom OAuth Provider - When user is created where to assign a role

I have a custom oauth2 provider. It works fine and registers the user if it doesn’t exist and is just based on the standard OAuth2Provider with little customization. Where should I assign the roles for this user?

The way to add roles to an existing user is to either call the /assignroles Service or inside ServiceStack you would call the IAuthRepository.AssignRoles() method.

If you want to add Roles in the same Auth request you could call it after OnAuthenticated() which saves the user to your User Auth repo and populates the existing session with something like:

public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
    // Saves the User to the Auth Repo
    var ret = base.OnAuthenticated(authService, session, tokens, authInfo);

    var addRoles = new List<string> { "TheRole" };

    var authRepo = authService.TryResolve<IAuthRepository>();
    if (session.Roles.IsEmpty()) //Only add roles if they weren't already added
    {
        // Add roles to the existing UserAuth
        var userAuth = authRepo.GetUserAuth(session.UserAuthId); 
        authRepo.AssignRoles(userAuth, roles:addRoles);

        // Add the roles to the existing session
        session.Roles = addRoles;
    }
    
    return ret;
}


1 Like

Worked perfectly with one minor change as session.Roles wasn’t null but an empty list. Thank you.

1 Like