design

ASP.NET Core Uygulamasında Kullanıcı Çıkışı (Logout)

July 21, 2024

Authentication Middleware Ayarları

Startup.cs dosyasını aç ve ConfigureServices ve Configure metodlarını güncelle:

-----

Startup.cs

cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";
        });

    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
} 

Account Controller'ına Logout Action'ı Ekle

Controllers/AccountController.cs dosyasını aç ve Logout action'ını ekle:

-----

AccountController.cs

cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using UserLoginApp.Models;

namespace UserLoginApp.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Bu kısımda kullanıcı doğrulama işlemleri yapılır
                if (model.Username == "admin" && model.Password == "password")
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, model.Username)
                    };

                    var claimsIdentity = new ClaimsIdentity(
                        claims, CookieAuthenticationDefaults.AuthenticationScheme);

                    var authProperties = new AuthenticationProperties
                    {
                        // Gerekirse buraya ek ayarlar ekleyebilirsiniz
                    };

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity),
                        authProperties);

                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError(string.Empty, "Geçersiz kullanıcı adı veya şifre.");
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Login", "Account");
        }
    }
} 

Logout View'ı ve Logout Butonu Ekleyin

Bir Logout view'ı oluşturmamıza gerek yok; ancak bir logout butonu eklememiz gerekecek.

Örneğin, Views/Shared/_Layout.cshtml dosyasına bir logout butonu ekleyebiliriz:

-----

_Layout.cshtml

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - UserLoginApp</title>
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                <li><a asp-area="" asp-controller="Account" asp-action="Login">Login</a></li>
                <li>
                    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm">
                        <button type="submit">Logout</button>
                    </form>
                </li>
            </ul>
        </nav>
    </header>
    <div class="container">
        <main role="main" class="pb-3">
            @RenderBody()
        </main>
    </div>

    <footer>
        <p>&copy; 2023 - UserLoginApp</p>
    </footer>

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js"></script>
    @RenderSection("Scripts", required: false)
</body>
</html> 

Kullanıcı Girişini ve Çıkışını Test Et

Uygulamayı çalıştır:

-----

sh

sh
dotnet run 

Tarayıcında https://localhost:5001/Account/Login adresine giderek giriş yapmayı dene. Giriş yaptıktan sonra logout butonunu kullanarak çıkış yapabilirsin.

Bu adımlar, ASP.NET Core uygulamasında kullanıcı girişi ve çıkış işlemlerini temel düzeyde nasıl gerçekleştirebileceğin konusunda sana rehberlik edecektir. Gerçek bir uygulamada, kullanıcı doğrulama ve oturum yönetimi için daha güvenli yöntemler ve veri saklama çözümleri kullanman gerekecektir.

8 + 1 =