gpt4 book ai didi

redis - 如何从 Redis 中的值填充 UserAuth?

转载 作者:IT王子 更新时间:2023-10-29 06:11:50 25 4
gpt4 key购买 nike

这是我在 global.asax 文件中的自定义用户身份验证设置,但我目前在 Configure 方法中手动提供用户;是否可以从 Redis 服务器获取值?

例如如果用户存在且密码没问题,是否可以自动填写这些详细信息?

Plugins.Add(new AuthFeature(()=> 
new AuthUserSession(),
new IAuthProvider[]{ new BasicAuthProvider() }
));

container.Register<ICacheClient>(new MemoryCacheClient());
var userRepo = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRepo);

string hash, salt;
new SaltedHash().GetHashAndSaltString("password", out hash, out salt);

userRepo.CreateUserAuth(new UserAuth
{
Id = 1,
DisplayName = "Haluk",
Email = "hal",
UserName = "haluk",
FirstName = "haluk",
LastName = "yılmaz",
PasswordHash = hash,
Salt = salt
}, "password");

最佳答案

是的,您可以针对 Redis 数据源进行身份验证。您可以使用内置的 RedisAuthRepository 代替 InMemoryAuthRepository,或者如果您有想要使用的现有 Redis 数据集而不是内置的 IAuthRepository 模式,我为此提供了一个解决方案,您可以借此扩展 BasicAuthProvider。第一种方法最直接:

使用RedisAuthRepository:

  1. 因此,您需要与 Redis 建立连接。
  2. 然后注册您的身份验证提供商。
  3. 注册 RedisAuthRepository,身份验证提供程序将根据它检查凭据,并且与 RegistrationFeature
  4. 兼容
private IRedisClientsManager redisClientsManager;

public override void Configure(Funq.Container container)
{
// Configure ServiceStack to connect to Redis
// Replace with your connection details
redisClientsManager = new PooledRedisClientManager("127.0.0.1:6379");
container.Register<IRedisClientsManager>(c => redisClientsManager);
container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);

// Setup the authorisation feature
Plugins.Add(new AuthFeature(()=>
new AuthUserSession(),
new IAuthProvider[]{ new BasicAuthProvider() }
));

// Use a RedisAuthRepository
var userRepo = new RedisAuthRepository(redisClientsManager);
container.Register<IUserAuthRepository>(userRepo);

// You can then register users as required using the RegistrationFeature
}

或者(如果您在 Redis 中已有用户身份验证数据集)

您可以通过创建自定义身份验证提供程序来做到这一点 extends the existing BasicAuthProvider .

对于此代码,您还应确保熟悉 the ServiceStack.Redis client .

扩展BasicAuthProvider:

MyRedisBasicAuthProvider 扩展了现有的 BasicAuthProvider,而不是从示例代码中给出的 IUserAuthRepository 执行凭据查找,它使Redis 连接并将用户名与 Redis 中的条目匹配。

代码已完全注释,但如果您希望进一步解释任何内容,请告诉我。

public class MyRedisBasicAuthProvider : BasicAuthProvider
{
// The key at which we will store the user profile. i.e user:john.smith or user:homer.simpson
// Replace this key with your format as required
public const string UserKeyFormat = "user:{0}";

MyUser CurrentUser;

// Gets an instance of a redis client
static IRedisClient GetRedisClient()
{
// Get the RedisClientsManager from the Container
var redisClientManager = HostContext.TryResolve<IRedisClientsManager>();
if(redisClientManager == null)
throw new Exception("Redis is not configured");

// Return a client
return redisClientManager.GetClient();
}

// This method is used to verify the credentials provided
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
// Get a Redis client connection
using(var redisClient = GetRedisClient())
{
// Get a typed Redis Client
var userClient = redisClient.As<MyUser>();

// Try to find a matching user in Redis
CurrentUser = userClient.GetValue(string.Format(UserKeyFormat, userName));

// Check the user exists & their password is correct (You should use a hashed password here)
return CurrentUser != null && password == CurrentUser.Password;
}
}

// This method is used to populate the session details from the user profile and other source data as required
public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary<string, string> authInfo)
{
// Populate the session with the details of the current user
session.PopulateWith<IAuthSession, MyUser>(CurrentUser);

// Save the session
authService.SaveSession(session);

return null;
}

public static void AddUserToRedis(MyUser user)
{
using(var redisClient = GetRedisClient())
{
// Get a typed Redis Client
var userClient = redisClient.As<MyUser>();

// Add the user to Redis
userClient.SetEntry(string.Format(UserKeyFormat, user.Username), user);
}
}
}

在上面的代码中,我使用了一个类 MyUser 来表示我存储在 Redis 中的用户配置文件,您当然可以自定义此类以满足您的用户配置文件要求。所以这是基本的用户配置文件类:

public class MyUser
{
public string Username { get; set; }
public string Password { get; set; } // Replace with a hashed password
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

使用 Redis 和您的自定义身份验证提供程序设置 ServiceStack:

您需要配置 ServiceStack 以使用 Redis 并告诉它使用您的自定义身份验证提供程序。为此,您可以将以下内容添加到 AppHost 中的 Configure 方法:

public override void Configure(Funq.Container container)
{
// Configure ServiceStack to connect to Redis
// Replace with your connection details
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("127.0.0.1:6379"));
container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);

// Add your custom credentials provider
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new MyRedisBasicAuthProvider()
}
));

// Add some test users. (If you have an existing Redis user source, you won't need to add test users.)
MyRedisBasicAuthProvider.AddUserToRedis(new MyUser {
Username = "john.smith",
Password = "test",
Email = "john.smith@email.com",
FirstName = "John",
LastName = "Smith",
});

MyRedisBasicAuthProvider.AddUserToRedis(new MyUser {
Username = "homer.simpson",

Password = "donuts",
Email = "homer.simpsons@springfield.com",
FirstName = "Homer",
LastName = "Simpson",
});

// Your other configuration settings ...
}

注意事项:

在示例中,我没有使用散列密码,以保持示例简单明了,但这很容易做到。添加另一个字段 public string Salt { get;放; }MyUser 然后不是将纯密码存储在 MyUser 上,而是将其存储为密码和盐的散列,即 hashedPassword = HashAlgorithm(password + 盐)。您已经有了它的代码:

string hash, salt;
new SaltedHash().GetHashAndSaltString("password", out hash, out salt);

因此,当使用 [Authenticate] 属性保护服务时,此解决方案现在将使用 Redis 数据源对用户进行身份验证。与标准基本提供程序一样,凭据在标准 /auth/basic 路由中进行身份验证。

使用 Credentials provider 而不是 Basic:
如果您想为表单发布使用凭据提供程序,而不是基本身份验证,您可以简单地将上面代码中的单词 Basic 替换为 Credentials

希望对您有所帮助。

关于redis - 如何从 Redis 中的值填充 UserAuth?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com