当前位置: 首页 > 编程语言 > C#

MVC5IoC和Authentication分享

时间:2023-04-10 22:57:29 C#

MVC5IoC和Authentication然而,由于我想使用IoC并稍后重用我的用户表,并向其中添加自定义内容,我发现很难看到如何使用MVC5附带的新身份框架。我越来越关注基本的身份验证形式。你的解决方案是什么?我的需要:我一直在寻找答案,但我看到的一切都硬编码在控制器中。你是怎么解决的?您是从头开始编写的,还是可以绑定到可以扩展到其他.NET平台(如WCF和WPF)的东西?以下代码直接来自默认ASP.NETMVC5模板中的AccountController。它做的第一件事是BastardInjection。[授权]publicclassAccountController:Controller{publicAccountController():this(newUserManager(newUserStore(newApplicationDbContext()))){}publicAccountController(UserManageruserManager){UserManager=userManager;接受的答案将提交给那个人,它向我展示了他们所做的,其中包含上述要求由于这是.NET,标准的安全方法是在应用程序边界进行身份验证,并将身份验证信息转换为校长。开箱即用地支持MVC。如果您需要在身份验证期间获得的其他信息,您可以将其收集在组合根中并使用它来组合您的服务。例如,假设您需要在下层使用经过身份验证的用户的电子邮件地址。任何需要用户电子邮件地址的类都可以简单地将其作为具体依赖项进行请求:publicclassEmailThingy{privatereadonlystringuserEmail;publicEmailThingy(stringuserEmail){if(userEmail==null)thrownewArgumentNullException("userEmail");this.userEmail=userEmail;}//othermembersgohere...}在ASP.NETMVC中,CompositionRoot是IControllerFactory。IIRC,您可以从CreateController方法中提取身份验证数据并使用它来组成对象图。这些天,我以相同的方式使用IPrincipal:我将其作为依赖项注入,而不是依赖Thread.CurrentPrincipalAmbientContext,因为当通过构造函数注入一致地注入所有内容时,单元测试更容易。您可能有兴趣查看Thinktecture.IdentityServer.v2https://github.com/thinktecture/Thinktecture.IdentityServer.v2。您的许多问题已经实现和封装。如果你找不到你需要的东西,你就必须弄清楚如何将所有这些抽象出来并自己实现。我最终决定实施IUserStore、IUserStore、IUserPasswordStore、IUserLoginStore,以便能够将UserRepository移动到其适当的数据访问层。但仍然获得Owin的安全和新身份框架。它实现起来非常简单,并且不需要太多的抽象。这是UserStoreWrapper命名空间qubis.booking.WebApp.App_Code.Identity{publicclassUserServiceWrapper:IUserStore,IUserPasswordStore,IUserLoginStore{publicIUserRepositoryUserRepos{get;放;}//我自己的界面。publicUserServiceWrapper(IUserRepositoryuserRepo){UserRepos=userRepo;}publicasyncTaskCreateAsync(ApplicationUserWrapperuser){UserRepos.Insert(user.RealUser);}publicasyncTaskFindByIdAsync(stringuserId){varappUser=UserRepos.FindByUserName(userId);ApplicationUserWrapper包装用户;如果(appUser!=null){wrappedUser=newApplicationUserWrapper(appUser);}否则wrappedUser=null;返回包裹用户;在帐户控制器中,我只是要求它注入:publicAccountController(UserManageruserManager){UserManager=userManager;{AllowOnlyAlphanumericUserNames=false};当我使用Ninject时,我在内核中这样设置:////在这里加载您的模块或注册您的服务!////内核。privatestaticvoidRegisterServices(IKernel内核){kernel.Bind().To();kernel.Bind().ToSelf();要查看身份框架,请参阅本文http://www.asp.net/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider如果你只是需要注入一个自定义的UserStore实现,这篇文章可能会帮助你基本上面你需要注入这个(取决于你是否想使用角色、声明等):编写一个实现IUser接口的用户类publicclassIdentityUser:IUser{publicIdentityUser(){...}publicIdentityUser(stringuserName)(){...}公共字符串ID{得到;放;}publicstring用户名{get;放;}publicstringPasswordHash{得到;放;}publicstringSecurityStamp{get;而上面IUserPasswordStore这个用户存储类就是C#学习教程:MVC5IoC与认证分享的全部内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——publicclassUserStore:IUserStore,IUserClaimStore,IUserLoginStore,IUserRoleStore,IUserPasswordStore{publicUserStore(){...}publicTaskCreateAsync(IdentityUseruser){...}publicTaskFindByIdAsync(stringuserId){...}..}本文来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: