本文整理汇总了C#中UserManager.FindAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UserManager.FindAsync方法的具体用法?C# UserManager.FindAsync怎么用?C# UserManager.FindAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UserManager
的用法示例。
在下文中一共展示了UserManager.FindAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SetupAsync
public async Task SetupAsync()
{
_evnt = new EventViewModel
{
Title = "Title event",
Description = "Test event",
Start = "11:00",
End = "14:27",
Date = "2016-02-01"
};
var userViewModel = new LoginViewModel
{
Email = "[email protected]",
Password = "useruser",
RememberMe = false
};
var context = new DataContext();
var manager = new UserManager(new UserStore(context));
var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
if (user == null)
{
await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
}
_calendarController = new CalendarController(context);
var mockCp = new Mock<IClaimsPrincipal>();
if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
_calendarController.CurrentUser = mockCp.Object;
var mockAuthenticationManager = new Mock<IAuthenticationManager>();
mockAuthenticationManager.Setup(am => am.SignOut());
mockAuthenticationManager.Setup(am => am.SignIn());
_calendarController.AuthenticationManager = mockAuthenticationManager.Object;
}
示例2: Login
public async Task<ActionResult> Login(LoginViewModel model)
{
// password for jwmcpeak is [email protected]
if (!ModelState.IsValid)
{
return View(model);
}
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = await userManager.FindAsync(model.Username, model.Password);
if (user == null)
{
ModelState.AddModelError(string.Empty, "The user with the supplied credentials does not exist.");
return View(model);
}
var authManager = HttpContext.GetOwinContext().Authentication;
var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
authManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);
return RedirectToAction("index", "home");
}
示例3: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
try
{
using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
{
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invaild_grant", "The user name or password is incorrect");
return;
}
}
}
catch (Exception ex)
{
var a = ex;
throw;
}
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
var properties = new AuthenticationProperties(new Dictionary<string, string>
{
{
"audience", context.ClientId ?? string.Empty
}
});
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
}
示例4: GetAuthKey
public async Task<string> GetAuthKey(string username, string password)
{
var store = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(store));
var user =await UserManager.FindAsync(username, password);
var key=Guid.NewGuid().ToString();
user.Logins.Add(new IdentityUserLogin { LoginProvider="app",ProviderKey=key,UserId=user.Id});
store.SaveChanges();
return key;
}
示例5: OnAuthenticated
/// <summary>
/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
/// </summary>
/// <param name="context">Contains information about the login session as well as the LTI request.</param>
/// <param name="claims">Optional set of claims to add to the identity.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
{
// Find existing pairing between LTI user and application user
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
var providerKey = context.LtiRequest.UserId;
var login = new UserLoginInfo(loginProvider, providerKey);
var user = await userManager.FindAsync(login);
if (user == null)
{
var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
await context.Options.Provider.GenerateUserName(usernameContext);
if (string.IsNullOrEmpty(usernameContext.UserName))
{
return;
}
user = await userManager.FindByNameAsync(usernameContext.UserName);
if (user == null)
{
user = new ApplicationUser { UserName = usernameContext.UserName };
var result = await userManager.CreateAsync(user);
if (!result.Succeeded)
{
return;
}
}
// Save the pairing between LTI user and application user
await userManager.AddLoginAsync(user.Id, login);
}
// Create the application identity, add the LTI request as a claim, and sign in
var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
if (claims != null)
{
foreach (var claim in claims)
{
identity.AddClaim(claim);
}
}
context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
// Redirect to original URL so the new identity takes affect
context.RedirectUrl = context.LtiRequest.Url.ToString();
}
示例6: Index
// GET: ClaimsIdentityFactory
public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
{
var context = new MyDbContext();
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<ApplicationUser>();
// Create a User to SignIn
var user = await userManager.FindAsync(model.UserName, model.Password);
//SignIn the User by generating a ClaimsIdentity
var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
// This claimsIdentity should have a claim called LastLoginTime
var authManager = HttpContext.GetOwinContext().Authentication;
authManager.SignIn(claimsIdentity);
return RedirectToLocal(returnUrl);
}
示例7: Register
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var userStore = new UserStore<ApplicationUser>(new DataContext());
var userManager = new UserManager<ApplicationUser>(userStore);
var user = await userManager.FindAsync(model.Email, model.Password);
if (user != null)
{
ModelState.AddModelError(string.Empty, "Пользователь существует");
return View(model);
}
user = new ApplicationUser { UserName = model.Email, Email = model.Email };
await userManager.CreateAsync(user, model.Password);
return RedirectToAction("Index", "Home");
}
示例8: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = new UserManager<User>(new UserStore<User>(new DatabaseContext()));
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 userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
var cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);
var properties = CreateProperties(user.UserName);
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
示例9: Login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var userStore = new UserStore<ApplicationUser>(new DataContext());
var userManager = new UserManager<ApplicationUser>(userStore);
var user = await userManager.FindAsync(model.Email, model.Password);
if (user == null)
{
ModelState.AddModelError(string.Empty, "Пользователь с такой комбинацией пароля и логина не существует");
return View(model);
}
var authManager = HttpContext.GetOwinContext().Authentication;
var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
authManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);
return RedirectToLocal(returnUrl);
}
示例10: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
AuthContext _ctx = new AuthContext();
using (UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))) {
IdentityUser user = await _userManager.FindAsync(context.UserName, context.Password);
if (user == null) {
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
context.Validated(identity);
}
示例11: Login
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
// カスタマイズのポイント:
// UserManagerのインスタンス作成時、
// 型引数:カスタマイズしたユーザー情報
// コンストラクタの引数:カスタマイズしたユーザストアのインスタンス
// をそれぞれ渡す
var userManager = new UserManager<MyAppUser>(new MyAppUserStore());
// カスタマイズのポイント:
// パスワードのハッシュ化アルゴリズムとして、IPasswordHasherを実装したカスタムクラスのインスタンスを設定
userManager.PasswordHasher = new MyPasswordHasher();
var user = await userManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
var authentication = this.HttpContext.GetOwinContext().Authentication;
var identify = await userManager.CreateIdentityAsync(
user,
DefaultAuthenticationTypes.ApplicationCookie);
authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identify);
return Redirect(returnUrl);
}
else
{
ModelState.AddModelError("", "ログインIDまたはパスワードが無効です。");
}
}
// ここで問題が発生した場合はフォームを再表示します
return View(model);
}
示例12: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var dbContext = new InstantDeliveryContext())
{
var userManager = new UserManager<User>(new UserStore<User>(dbContext));
User user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
示例13: Register
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = await userManager.FindAsync(model.Username, model.Password);
if (user != null)
{
ModelState.AddModelError(string.Empty, "The user already exists.");
return View(model);
}
user = new IdentityUser { UserName = model.Username, Email = model.Email };
await userManager.CreateAsync(user, model.Password);
return RedirectToAction("index", "home");
}
示例14: ConfigureUsers
public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
using(var db = new Contexto(options.ConnectionString)) {
if(!db.Users.Any()) {
foreach(var u in users) {
var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
var response = await userManager.CreateAsync(entity, u.Password);
if(!response.Succeeded) {
throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
}
else {
var user = await userManager.FindAsync(u.Username,u.Password);
foreach(var c in u.Claims) {
await userManager.AddClaimAsync(user.Id,c);
}
await userManager.UpdateAsync(user);
}
}
db.SaveChanges();
}
}
}
示例15: Login
public async Task<JsonData> Login(LoginModel model)
{
try
{
using (var db = new DataContext())
{
var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
//get the user by the email address
var us = new UserRepo().GetUserByName(model.UserName, db);
if (us == null) throw new Exception("Please check the login details");
var user = await userMan.FindAsync(us.UserName, model.Password);
if (user == null) throw new Exception("Please check the login details");
if (!user.IsActive) throw new Exception("You can not login because your user is not active");
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await userMan.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, identity);
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
return DataHelpers.ReturnJsonData(user, true, token);
}
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}