2017-05-17 3 views
5

Ich habe diese alte MVC5-Anwendung, die Formularauthentifizierung in der einfachsten möglichen Form verwendet. Es gibt nur ein Konto in web.config gespeichert sind, gibt es keine Rollen usw.Asp.Net Core - einfachste Formularauthentifizierung

<authentication mode="Forms"> 
    <forms loginUrl="~/Login/Index" timeout="30"> 
    <credentials passwordFormat="Clear"> 
     <user name="some-user" password="some-password" /> 
    </credentials> 
    </forms> 
</authentication> 

Die Login-Routine ruft nur

FormsAuthentication.Authenticate(name, password); 

Und das ist es. Gibt es etwas ähnliches (in Bezug auf die Einfachheit) in asp.net Kern?

+0

Authentifizierung mit FormAuth ist mit asp.net Kern nicht kompatibel. Eher verwenden Sie die Identität –

Antwort

9

Es ist nicht so einfach :)

  1. Im Startup.cs, Methode konfigurieren.

    app.UseCookieAuthentication(options => 
    { 
        options.AutomaticAuthenticate = true; 
        options.AutomaticChallenge = true; 
        options.LoginPath = "/Home/Login"; 
    }); 
    
  2. hinzufügen Autorisieren Attribut Ressourcen, die Sie sichern möchten, schützen.

    [Authorize] 
    public IActionResult Index() 
    { 
        return View(); 
    } 
    
  3. Im Home Controller, Login Beitrag Aktion-Methode, die folgende Methode schreiben.

    var username = Configuration["username"]; 
    var password = Configuration["password"]; 
    if (authUser.Username == username && authUser.Password == password) 
    { 
        var identity = new ClaimsIdentity(claims, 
         CookieAuthenticationDefaults.AuthenticationScheme); 
    
        HttpContext.Authentication.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme, 
        new ClaimsPrincipal(identity)); 
    
        return Redirect("~/Home/Index"); 
    } 
    else 
    { 
        ModelState.AddModelError("","Login failed. Please check Username and/or password"); 
    } 
    

Hier ist die GitHub Repo für Ihre Referenz: https://github.com/anuraj/CookieAuthMVCSample

+0

Ich benutze Ihren Code, aber es gibt einen Fehler "kann Lambda-Ausdruck nicht in Typ konvertieren" in Startup.cs, konfigurieren Sie die Methode. –

+0

@SanyamiVaidya Welche Version von asp.net Core verwenden Sie? – Anuraj

+0

Ich benutze 1.0.1 Version von asp.net Kern –

Verwandte Themen