使用aspnet.identity 身份验证的框架中,怎么对现有用户进行删除

 我来答
百度网友836ae77
2017-10-28 · 超过37用户采纳过TA的回答
知道答主
回答量:109
采纳率:55%
帮助的人:51.1万
展开全部
首先让我先更新 API 项目

我先 API 项目进行必要修改修改完再切换 Web 项目客户端进行更新

第1步:我需要数据库

能做任何操作前我需要先创建数据库本例使用 SQL Server Express没安装载 SQL Server Express安装完创建名 CallingWebApiFromMvc 数据库第步要做

Api 项目需要数据库连接字符串否则我寸步难行面段代码插入 Api 项目Web.config 文件:

认证(Identity)框架自创建我管理用户所需要员关系表现需要担提前创建

第2步:添加相关Nuget包

接我添加用于OWINWindows认证Nuget包打包管理控制台切换Api项目缺省项目输入命令:

Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.AspNet.Identity.EntityFramework
Install-Package Microsoft.AspNet.Identity.Owin

使用些包我应用启OWIN服务器通EntityFramework我用户保存SQL Server

第3步:添加管理用户Identity类

我使用基于Windows认证机制Entity框架管理数据库相关业务首先我需要添加些用于处理类Api项目添加Identity目录作我要添加类命名空间添加类:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext
{ public ApplicationDbContext() : base("ApiFromMvcConnection") {}
public static ApplicationDbContext Create()
{ return new ApplicationDbContext();
}
}

注意我传给基类构造函数参数ApiFromMvcConnection要Web.config连接字符串name相匹配

public class ApplicationUserManager : UserManager
{ public ApplicationUserManager(IUserStore store) : base(store)
{
} public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context)
{ var manager = new ApplicationUserManager(new UserStore (context.Get ()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator (manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
}; var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider (dataProtectionProvider.Create("ASP.NET Identity"));
} return manager;
}
}

第4步:添加OWIN启类

让我应用程序作OWIN服务器运行我需要应用程序启初始化我通启类做点我装点类
OwinStartup属性应用程序启触发意味着我摆脱Global.asax移
Application_Start代码转换我新启类

using Microsoft.Owin;

[assembly: OwinStartup(typeof(Levelnis.Learning.CallingWebApiFromMvc.Api.Startup))]
namespace Levelnis.Learning.CallingWebApiFromMvc.Api
{
using System;
using System.Web.Http;
using Identity;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Providers;
public class Startup
{ public void Configuration(IAppBuilder app)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext (ApplicationUserManager.Create); var oAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/token"),
Provider = new ApplicationOAuthProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
}
}
}

应用程序启我建立自服务器我配置令牌端点并设置自自定义提供商我用我用户进行身份验证我例我使用ApplicationOAuthProvider类让我看看现:

第5步:添加OAuth提供商

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{ public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult (null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager ();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect."); return;
}
var oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); var cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); var properties = CreateProperties(user.UserName); var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
private static AuthenticationProperties CreateProperties(string userName)
{
var data = new Dictionary
{
{
"userName", userName
}
};
return new AuthenticationProperties(data);
}
}

我兴趣2种第ValidateClientAuthentication验证客户端我客户端所返
功异步签名没异步调用发我离异步修改我必须返任务自我增加名
GenerateUserIdentityAsyncApplicationUser看起像:

public class ApplicationUser : IdentityUser
{ public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType)
{
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
return userIdentity;
}
}

第6步:注册新用户 - API端
所我位所Identity类管理用户让我看看RegisterController新用户保存我数据库接受RegisterApi模式简单:

public class RegisterApiModel
{
[Required]
[EmailAddress] public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password {
get; set;
}

[Required]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

控制器本身注册功返200 OK响应验证失败则返401错误请求响应

public class RegisterController : ApiController
{ private ApplicationUserManager UserManager
{ get
{ return Request.GetOwinContext().GetUserManager ();
}
} public IHttpActionResult Post(RegisterApiModel model)
{ if (!ModelState.IsValid)
{ return BadRequest(ModelState);
} var user = new ApplicationUser
{
Email = model.Email,
UserName = model.Email,
EmailConfirmed = true
};
var result = UserManager.Create(user, model.Password);
return result.Succeeded ? Ok() : GetErrorResult(result);
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (result.Errors != null)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式