Benutzer:MovGP0/NET/Forms Authentication

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


ASP.NET/Win Forms Authentication

[Bearbeiten | Quelltext bearbeiten]
  • Implement Custom Membership Provider
  • Setup the Membership Provider in web.config
  • Disable anonymous authentication in IIS and enable Forms Authentication
    • can also be done in web.config
    • anonymous authentication authenticates against the Windows user
  • Implement IPrincipal
  • Implement IIdentity
Login
if (Membership.ValidateUser(viewModel.Email, viewModel.Password))
{
    var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();

    var serializeModel = new CustomPrincipal
    {
        Id = user.Id,
        FirstName = user.FirstName,
        LastName = user.LastName
    };

    var userJson = JsonConvert.SerializeObject(serializeModel);

    var authTicket = new FormsAuthenticationTicket(1, viewModel.Email, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);

    var ticket = FormsAuthentication.Encrypt(authTicket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
    Response.Cookies.Add(cookie);
    // ...
}
Authenticate
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (cookie == null)
    return false; // redirect to authentication page 
    
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var userJson = ticket.UserData;
var principal = JsonConvert.DeserializeObject<CustomPrincipal>(userJson);
HttpContext.Current.User = principal;
return true; // user is authenticated