Loading

asp.net Identity 设置自定义登录

添加Startup.Auth.cs###

    public partial class Startup
    {
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 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("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromDays(3)
          });        
            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);
        }
    }

添加Startup.cs###

注意要添加[assembly: OwinStartup(typeof(Startup))]

[assembly: OwinStartup(typeof(Startup))]
namespace testOwin
{
  public partial class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      ConfigureAuth(app);
    }
  }
}

在代码中就可以自己设置登录状态了###

    private ClaimsIdentity ClaimsIdentity(string userName)
    {
      //string[] userRoles = (string[])Session["UserRoles"];

      ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

      identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));

      //userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

      identity.AddClaim(new Claim(ClaimTypes.Name, userName));

      //AuthenticationManager.SignIn(identity);
      AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
      return identity;
    }

    private IAuthenticationManager AuthenticationManager
    {
      get
      {
        return HttpContext.GetOwinContext().Authentication;
      }
    }
posted @ 2017-08-18 19:34  Dhoopu  阅读(517)  评论(0编辑  收藏  举报