DB-First与ASP.NETWebAPI2+EF6的认证混淆我需要创建一个已有的MySQL数据库WebAPIC#应用程序。我已经设法使用EntityFramework6将每个数据库表绑定到一个RESTfulAPI(允许CRUD操作)。我想实现一个登录/注册系统(以便我可以在未来实现角色和权限,并限制某些API请求).我必须使用的MySQL数据库有一个用户表(称为用户),其中包含以下不言自明的列:似乎事实上的身份验证标准是ASP.NetIdentity。我花了最后一个小时试图弄清楚如何让Identity与我现有的DB-FirstEntityFramework设置一起工作。如果我尝试构建一个存储用户实例(MySQL数据库中的实体)的ApplicationUser实例来检索用户数据,我会收到以下错误:实体类型ApplicationUser不是当前上下文模型的一部分。我假设我需要将身份数据存储在我的MySQL数据库中,但找不到有关如何执行此操作的任何资源。我已尝试完全删除ApplicationUser类并使我的用户实体类派生自IdentityUser,但调用UserManager.CreateAsync会导致LINQ到实体转换错误。如何使用现有用户实体在WebAPI2应用程序中设置身份验证?你说:我想实现一个登录/注册系统(这样我以后可以实现角色和权限,限制某些API请求)。如何使用现有用户实体在WebAPI2应用程序中设置身份验证?这绝对意味着您不需要ASP.NETIdentity。ASP.NETIdentity是一种处理所有用户配置文件的技术。它实际上并没有“制定”身份验证机制。ASP.NETIdentity使用的是OWIN身份验证机制,这是另外一回事了。您正在寻找的不是“如何将ASP.NET身份与我现有的用户表一起使用”,而是“如何使用我现有的用户表配置OWIN身份验证”要使用OWINAuth,请按照下列步骤操作:安装包:OwinMicrosoft。AspNet.CorsMicrosoft.AspNet.WebApi.ClientMicrosoft.AspNet.WebApi.CoreMicrosoft.AspNet.WebApi.OwinMicrosoft.AspNet.WebApi.WebHostMicrosoft.OwinMicrosoft.Owin.Host.SystemWebMicrosoft.Owin。安全Microsoft.Owin.Security.OAuth在根文件夹中创建一个Startup.cs文件(示例):确保它已正确配置[assembly:OwinStartup][assembly:OwinStartup(typeof(YourProject.Startup))]namespaceYourProject{publicclassStartup{publicvoidConfiguration(IAppBuilderapp){varconfig=newHttpConfiguration();//其他配置ConfigureOAuth(app);app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);app.UseWebApi(配置);}publicvoidConfigureOAuth(IAppBuilderapp){varoAuthServerOptions=newOAuthAuthorizationServerOptions(){AllowInsecureHttp=true,TokenEndpointPath=newPathString("/api/security/token"),AccessTokenExpireTimeSpan=TimeSpan.FromHours(2),Provider=newAuthorizationServerProvider()};app.UseOAuthAuthorizationServer(oAuthServerOptions);app.UseOAuthBearerAuthentication(新的OAuthBearerAuthenticationOptions());}}publicclassAuthorizationServerProvider:OAuthAuthorizationServerProvider{publicoverrideasyncTaskValidateClientAuthentication(OAuthValidateClientAuthenticationContextcontext){context.Validated();}publicoverrideasyncTaskGrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContextcontext){context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[]{"*"});try{//从数据库中检索您的用户。例如:varuser=awaituserService.Authenticate(context.UserName,context.Password);varidentity=newClaimsIdentity(context.Options.AuthenticationType);identity.AddClaim(newClaim(ClaimTypes.Name,user.Name));identity.AddClaim(newClaim(ClaimTypes.Email,user.Email));//角色示例varrolesTechnicalNamesUser=新列表();if(user.Roles!=null){rolesTechnicalNamesUser=user.Roles.Select(x=>x.TechnicalName).ToList();foreach(varroleinuser.Roles)identity.AddClaim(newClaim(ClaimTypes.Role,role.TechnicalName));}varprincipal=newGenericPrincipal(identity,rolesTechnicalNamesUser.ToArray());Thread.CurrentPrincipal=主体;context.Validated(身份);}catch(Exceptionex){context.SetError("invalid_grant","message");}}}}使用[Authorize]属性授权操作使用GrantType、UserName和Password调用api/security/token以获取不记名令牌。像这样:"grant_type=password&username="+username+"&password="password;在HttpHeader授权中作为Bearer“YOURTOKENHERE”的令牌。像这样:headers:{'Authorization':'Bearer'+token}希望有帮助!由于您的数据库架构与默认的UserStore不兼容,因此您必须实现自己的UserStore和UserPasswordStore类,然后将它们注入到UserManager中。考虑这个简单的例子:首先编写一个自定义的User类并实现IUser接口:/一些其他属性}现在创建自定义UserStore和IUserPasswordStore类,如下所示:publicclassMyUserStore:IUserStore,IUserPasswordStore{publicMyUserStore(MyDbContextcontext){_context=context;}publicTaskCreateAsync(AppUseruser){//实现你想要的逻辑,例如//_context.Users.Add(user);}publicTaskDeleteAsync(AppUseruser){//实现你想要的逻辑}publicTaskFindByIdAsync(stringuserId){//实现你想要的逻辑}publicTaskFindByNameAsync(stringuserName){//实现你想要的逻辑}publicTaskUpdateAsync(AppUseruser){//实现你想要的逻辑}publicvoidDispose(){//实现你想要的逻辑}//IUserPasswordStore需要以下3个方法publicTaskGetPasswordHashAsync(AppUseruser){//像这样:returnTask.FromResult(user.Password_hash);}publicTaskHasPasswordAsync(AppUseruser){returnTask.FromResult(user.Password_hash!=null);}publicTaskSetPasswordHashAsync(AppUseruser,stringpasswordHash){user.Password_hash=passwordHash;返回Task.FromResult(0);}}现在你有了自己的用户存储,只需将它注入到UserManager中:));//restofcode}}另请注意,您必须直接从DbContext继承您的DBContext类,DbContext不是IdentityDbContext因为您已经实现以上是C#学习教程:DB-First和ASP.NETWebAPI2+EF6身份混淆共享。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
