我试图通过一些在WebForms中使用Microsoft.AspNet.Identity和Microsoft.Asp.Identity.Owin的示例。我已经能够在我当前的数据库中创建数据库表(我选择将用户,商店和角色管理器中的AspNet表保存在与我的应用程序相同的数据库中)并且具有模型,控制器,视图和App_Start文件夹放置所需文件。
我遇到问题的一行是在我的代码隐藏文件中,用于帐户文件夹中的ForgetPassword:var manager = Context.GetOwinContext()。GetUserManager();
以下是我设置文件的方法: App_Start:IdentityConfig.cs
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using FHSF_4_DEV.Models;
namespace FHSF_4_DEV
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
base(userManager, authenticationManager) { }
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
App_Start:Startup.Auth.cs
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Google;
using Owin;
using FHSF_4_DEV.Models;
namespace FHSF_4_DEV
{
public partial class App_Start_Startup {
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301883
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("~/Default.aspx"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
}
帐户:ForgotPassword.aspx
<%@ Page Title="Forgot password" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ForgotPassword.aspx.cs" Inherits="FHSF_4_DEV.Account.ForgotPassword" Async="true" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div style="width: 20%; text-align: center; color: white; margin-left: 40%; margin-right: 40%;">
<div class="row">
<div class="col-md-8">
<asp:PlaceHolder ID="loginForm" runat="server">
<div class="form-horizontal">
<h2>Forgot your password?</h2>
<hr />
<asp:PlaceHolder runat="server" ID="ErrorMessage" Visible="false">
<p class="text-danger">
<asp:Literal runat="server" ID="FailureText" />
</p>
</asp:PlaceHolder>
<div class="form-group" style="align-content:center">
<asp:Label runat="server" AssociatedControlID="Email" CssClass="col-md-2 control-label">Email</asp:Label>
<div class="col-md-10" style="margin-left:28%; margin-right:28%;">
<asp:TextBox runat="server" ID="Email" CssClass="form-control" TextMode="Email" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Email"
CssClass="text-danger" ErrorMessage="The email field is required." />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" OnClick="Forgot" Text="Email Link" CssClass="btn btn-default" />
</div>
</div>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="DisplayEmail" Visible="false">
<p class="text-info">
Please check your email to reset your password.
</p>
</asp:PlaceHolder>
</div>
</div>
</div>
</asp:Content>
帐户:ForgotPassword.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using FHSF_4_DEV.Models;
using SendGrid;
using System.Net;
using System.Configuration;
using System.Diagnostics;
using FHSF_4_DEV;
namespace FHSF_4_DEV.Account
{
public partial class ForgotPassword : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Forgot(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user's email address
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.FindByName(Email.Text);
if (user == null || !manager.IsEmailConfirmed(user.Id))
{
FailureText.Text = "The user either does not exist or is not confirmed.";
ErrorMessage.Visible = true;
return;
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send email with the code and the redirect to reset password page
string code = manager.GeneratePasswordResetToken(user.Id);
string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request);
manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>.");
loginForm.Visible = false;
DisplayEmail.Visible = true;
}
}
}
}
似乎我需要设置东西,但是我从var manager返回= Context.GetOwinContext()。GetUserManager(); ForgotPassword.aspx.cs中的行为空,即使我在AspNetUser表中设置了用户。
任何帮助导致我为什么我得到一个空值以及如何获得正确的参考将不胜感激!