Last active
April 9, 2021 07:46
-
-
Save gistlyn/a9a816ed0f78ccd020e57c903bd2c824 to your computer and use it in GitHub Desktop.
Configure MongoDB Auth Provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dotnet add package ServiceStack.Authentication.MongoDb |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.Extensions.DependencyInjection; | |
using ServiceStack; | |
using ServiceStack.Auth; | |
using ServiceStack.Configuration; | |
using ServiceStack.Authentication.MongoDb; | |
using MongoDB.Driver; | |
namespace MyApp | |
{ | |
public class ConfigureAuthRepository : IConfigureAppHost, IConfigureServices | |
{ | |
public void Configure(IServiceCollection services) | |
{ | |
services.AddSingleton<IAuthRepository>(c => | |
new MongoDbAuthRepository(c.Resolve<IMongoDatabase>(), createMissingCollections:true)); | |
} | |
public void Configure(IAppHost appHost) | |
{ | |
var authRepo = appHost.Resolve<IAuthRepository>(); | |
authRepo.InitSchema(); | |
//CreateUser(authRepo, "[email protected]", "Admin User", "p@55wOrd", roles:new[]{ RoleNames.Admin }); | |
} | |
// Add initial Users to the configured Auth Repository | |
public void CreateUser(IAuthRepository authRepo, string email, string name, string password, string[] roles) | |
{ | |
if (authRepo.GetUserAuthByUserName(email) == null) | |
{ | |
var newAdmin = new UserAuth { Email = email, DisplayName = name }; | |
var user = authRepo.CreateUserAuth(newAdmin, password); | |
authRepo.AssignRoles(user, roles); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment