1 Şubat 2020 Cumartesi

asp.net core mvc frameworkde cookie authentication ve authorization

dotnet core 3.1 sürümü ile

Asp.Net Core MVC mimarisinde Cookie tabanlı authentication mekanizması için gerekenler:


Öncelikle Startup.cs dosyasından başlayalım.

ConfigureService methodunda aşağıdaki gibi Authentication ve Authorization bağımlılıklarını IOC ile gönderelim.

        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddDistributedMemoryCache(); //TODO
            services.AddSession(opt => opt.IdleTimeout = TimeSpan.FromMinutes(10));  //TODO

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, 
                opt => 
                    {
                        opt.LoginPath = "/Account/Login";
                        opt.AccessDeniedPath = "/Account/Login";
                        opt.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                        opt.LogoutPath = "/Account/Logout";
                    }); //TODO: 1
            services.AddAuthorization(); //TODO: 2
            services.AddControllersWithViews();
        }
 

Daha sonra Startup.cs dosyasının içinde bulunan Configure methoduna aşağıdaki şekilde Pipeline ları ekliyoruz..



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            
            app.UseCookiePolicy();  //Ekle

            app.UseRouting();

            app.UseSession(); //Ekle

            app.UseAuthentication();  //Ekle
            app.UseAuthorization();


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



Aşağıdaki gibi bir Account controller'ı ekliyoruz ve işimiz tamamlandı.Authentication istediğiniz controllerlara [Authorize] attributeunu eklemeyi unutmayın.

Afiyet olsun :) 



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace SimpleCookieAuthenticationAndAuthorization.Controllers
{
    public class AccountController : Controller
    {
        private readonly IHttpContextAccessor iHttpContextAccessor;

        public AccountController(IHttpContextAccessor iHttpContextAccessor)
        {
            this.iHttpContextAccessor = iHttpContextAccessor;
        }
        
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(string username, string password)
        {

            if (username == "bgokalp" && password == "123456")
            {
                HttpContext.Session.Clear();
                List<Claim> userClaims = new List<Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, "1"),
                    new Claim(ClaimTypes.Name, "burak"),
                    new Claim(ClaimTypes.Surname, "gökalp"),
                    new Claim(ClaimTypes.Role, "ADMIN"),
                    new Claim(ClaimTypes.Role, "USER")
                };
                iHttpContextAccessor.HttpContext.Session.SetInt32("ID", 1);
                iHttpContextAccessor.HttpContext.Session.SetString("NAME", "Burak Gökalp");
                ClaimsIdentity claimsIdentity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties());
                return RedirectToAction("Index", "Home");
            }
            else return RedirectToAction("Index");
            
        }



        public async Task<IActionResult> Logout()
        {
            if(HttpContext.User.Identity.IsAuthenticated)
            {
                iHttpContextAccessor.HttpContext.Session.Clear();
                await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            }
            return RedirectToAction(nameof(AccountController.Login));
        }
    }
}