DDD认证服务
本文关键字:认证服务 DDD | 更新日期: 2023-09-27 18:01:51
我遵循专业ASP的案例研究。Scott Millet的。NET设计模式。在案例研究中,身份验证是在Infrastructure项目中处理的。它包含了像AspFormsAuthentication: IFormsAuthentication, AspMembershipAuthentication: ILocalAuthenticationService这样的实现。
这很好,因为他正在使用内置的成员资格提供程序,但是,我没有,所以我需要访问我的存储库。在我的场景中,将我的ILocalAuthenticationService和AspMembershipAuthentication实现放在Services项目中不是更好吗?
我在别处问过这个问题,有人回答:
我仍然会将提取凭证的功能放在基础设施层中,因为该层与其他水平层垂直对齐,并且所有层都可以访问它。由于您没有使用ASP。. NET会员资格提供程序,并可能使用一些自定义的东西,可能只使用加密的凭据,您仍然可以使用基础设施层来包装这些凭据的访问,并允许存储库在需要时使用它们。你可以让服务层获取它们并向下传递它们,但是这样你就有太多的层来理解数据将如何被检索/持久化以及需要哪些授权访问,这在试图分层和分离关注点时是不好的。
好了。这是有道理的。但我不知道该怎么办。案例研究中的代码:
public class AspMembershipAuthentication : ILocalAuthenticationService
{
public User Login(string email, string password)
{
User user = new User();
user.IsAuthenticated= false;
if (Membership.ValidateUser(email, password))
{
MembershipUser validatedUser = Membership.GetUser(email);
user.AuthenticationToken = validatedUser.ProviderUserKey.ToString();
user.Email = email;
user.IsAuthenticated = true;
}
return user;
}
public User RegisterUser(string email, string password)
{
MembershipCreateStatus status;
User user = new User();
user.IsAuthenticated = false;
Membership.CreateUser(email, password, email,
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
true, out status);
if (status == MembershipCreateStatus.Success)
{
MembershipUser newlyCreatedUser = Membership.GetUser(email);
user.AuthenticationToken = newlyCreatedUser.ProviderUserKey.ToString();
user.Email = email;
user.IsAuthenticated = true;
}
else
{
switch (status)
{
case MembershipCreateStatus.DuplicateEmail:
throw new InvalidOperationException(
"There is already a user with this email address.");
case MembershipCreateStatus.DuplicateUserName:
throw new InvalidOperationException(
"There is already a user with this email address.");
case MembershipCreateStatus.InvalidEmail:
throw new InvalidOperationException(
"Your email address is invalid");
default:
throw new InvalidOperationException(
"There was a problem creating your account. Please try again.");
}
}
return user;
}
}
如果我没有使用会员资格提供程序,我如何连接到数据库来检查用户名和密码是否匹配,以及其他可能的检查?
在你的基础结构层创建一个类来实现ILocalAuthenticationService并进行你需要的调用。
或者,如果ILocalAuthenticationService太ASP。. NET-y(带有它的User返回类型),你可能需要滚动你自己的ilocalauthenticationservice变体并实现它。
然后在需要时使用您的IoC容器来解析ILocalAuthenticationService