﻿
{"id":26951,"date":"2024-04-11T22:41:10","date_gmt":"2024-04-11T22:41:10","guid":{"rendered":"https:\/\/www.gencayyildiz.com\/blog\/?p=26951"},"modified":"2024-04-11T22:41:29","modified_gmt":"2024-04-11T22:41:29","slug":"asp-net-coreda-current-useri-elde-etmek","status":"publish","type":"post","link":"https:\/\/www.gencayyildiz.com\/blog\/asp-net-coreda-current-useri-elde-etmek\/","title":{"rendered":"Asp.NET Core&#8217;da Current User&#8217;\u0131 Elde Etmek"},"content":{"rendered":"<div id=\"fb-root\"><\/div>\n<p>Merhaba,<\/p>\n<p>Asp.NET Core ile geli\u015ftirdi\u011fimiz uygulamalar\u0131n \u00e7o\u011funda authentication ve authorization yayg\u0131n olarak kulland\u0131\u011f\u0131m\u0131z g\u00fcvenlik protokolleridir. Genellikle, bu protokoller neticesinde do\u011frulanan kullan\u0131c\u0131lar\u0131n bilgilerine eri\u015fim g\u00f6sterebildikleri noktalarda bizler taraf\u0131ndan ihtiya\u00e7 duyulabilmektedir. Bu konuya dair kaynaklar\u0131 tarad\u0131\u011f\u0131m\u0131zda kimi uygulamalarda kullan\u0131c\u0131 bilgisi i\u00e7in identity provider&#8217;la etkile\u015fim kuruldu\u011funu g\u00f6rmekteyiz. Halbuki her kullan\u0131c\u0131 bilgisi ihtiyac\u0131na kar\u015f\u0131n bu davran\u0131\u015f\u0131n hem maliyetli hem de mimarisel olarak ilke d\u0131\u015f\u0131 bir y\u00f6ntem oldu\u011funu s\u00f6yleyebiliriz. Burada yap\u0131lmas\u0131 gereken claim tabanl\u0131 kullan\u0131c\u0131 bilgisinin client&#8217;a aktar\u0131lmas\u0131 ve ihtiya\u00e7 noktalar\u0131nda bu bilgilerin claim \u00fczerinden elde edilmesidir. Tabi bunun i\u00e7in de bir soyutlama \u00e7al\u0131\u015fmas\u0131 elzemdir. \u0130\u015fte bu i\u00e7eri\u011fimizde bu basit ama etkili y\u00f6ntemi teknik olarak de\u011ferlendiriyor olaca\u011f\u0131z. Buyurun ba\u015flayal\u0131m&#8230;<\/p>\n<p>\u0130lk olarak a\u015fa\u011f\u0131daki gibi bir abstraction yap\u0131s\u0131 olu\u015fturarak ba\u015flayal\u0131m;<\/p>\n<div style=\"font-size:12px;\">\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public interface IUserContext\r\n    {\r\n        bool IsAuthenticated { get; }\r\n        Guid UserId { get; }\r\n        string Username { get; }\r\n    }\r\n<\/pre>\n<\/div>\n<p>Burada mevcut kullan\u0131c\u0131ya dair ihtiyac\u0131m\u0131z olan bilgileri tutuyoruz. Tabi ki de gerekli oldu\u011fu d\u00fc\u015f\u00fcn\u00fclen farkl\u0131 veriler s\u00f6z konusuysa e\u011fer bunlar\u0131 da ekleyerek bu interface geni\u015fletilebilir. \u015eimdi bu abstraction&#8217;\u0131 bir concrete class&#8217;a uygulayarak mevcut kullan\u0131c\u0131n\u0131n claim&#8217;lerini i\u00e7eren <code>ClaimsPrincipal<\/code>&#8216;a eri\u015felim. Tabi bunun i\u00e7in de a\u015fa\u011f\u0131daki gibi extension metot&#8217;lardan istifade edece\u011fiz.<\/p>\n<div style=\"font-size:12px;\">\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public static class ClaimsPrincipalExtensions\r\n    {\r\n        public static Guid GetUserId(this ClaimsPrincipal? claimsPrincipal)\r\n        {\r\n            string? userId = claimsPrincipal?.FindFirstValue(&quot;UserId&quot;);\r\n            return Guid.TryParse(userId, out Guid parsedUserId) ? parsedUserId : throw new ApplicationException();\r\n        }\r\n\r\n        public static string GetUsername(this ClaimsPrincipal? claimsPrincipal)\r\n        {\r\n            string? username = claimsPrincipal?.FindFirstValue(ClaimTypes.NameIdentifier);\r\n            return username;\r\n        }\r\n    }\r\n<\/pre>\n<\/div>\n<p>Ve concrete class&#8217;\u0131 olu\u015fturup, implementasyonu ger\u00e7ekle\u015ftirelim.<\/p>\n<div style=\"font-size:12px;\">\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public sealed class UserContext(IHttpContextAccessor httpContextAccessor) : IUserContext\r\n    {\r\n        public bool IsAuthenticated =&gt;\r\n            httpContextAccessor\r\n            .HttpContext?\r\n            .User\r\n            .Identity?\r\n            .IsAuthenticated ?? false;\r\n\r\n        public Guid UserId =&gt;\r\n            httpContextAccessor\r\n            .HttpContext?\r\n            .User\r\n            .GetUserId() ?? throw new ApplicationException();\r\n\r\n        public string Username =&gt;\r\n            httpContextAccessor\r\n            .HttpContext?\r\n            .User\r\n            .GetUsername() ?? throw new ApplicationException();\r\n    }\r\n<\/pre>\n<\/div>\n<p>Ve bu i\u015flemin ard\u0131ndan a\u015fa\u011f\u0131daki gibi IoC Container tan\u0131mlamas\u0131nda bulunduktan sonra mevcut kullan\u0131c\u0131 bilgilerine istedi\u011fimiz noktadan eri\u015fim g\u00f6sterebiliriz.<\/p>\n<div style=\"font-size:12px;\">\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nbuilder.Services.AddSingleton&lt;IUserContext, UserContext&gt;();\r\n<\/pre>\n<\/div>\n<p>\u015e\u00f6yle ki;<\/p>\n<div style=\"font-size:12px;\">\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\napp.MapGet(&quot;\/get-userid&quot;, (IUserContext userContext) =&gt; userContext.UserId)\r\n    .RequireAuthorization();\r\n\r\napp.MapGet(&quot;\/get-username&quot;, (IUserContext userContext) =&gt; userContext.Username)\r\n    .RequireAuthorization();\r\n<\/pre>\n<\/div>\n<p>Tabi buradaki \u00f6rne\u011fin d\u0131\u015f\u0131nda mevcut kullan\u0131c\u0131 bilgilerine onion architecture gibi profesyonel mimarilerin application katmanlar\u0131ndan ya da CQRS pattern davran\u0131\u015f\u0131n\u0131n uyguland\u0131\u011f\u0131 handle s\u0131n\u0131flar\u0131ndan rahatl\u0131kla eri\u015fim g\u00f6sterebilir ve etkin bir \u015fekilde y\u00f6netebiliriz.<\/p>\n<p>\u0130lgilenenlerin faydalanmas\u0131 dile\u011fiyle&#8230;<br \/>\nSonraki yaz\u0131lar\u0131mda g\u00f6r\u00fc\u015fmek \u00fczere&#8230;<br \/>\n\u0130yi \u00e7al\u0131\u015fmalar&#8230;<\/p>\n<p>Not : \u00d6rnek \u00e7al\u0131\u015fmaya a\u015fa\u011f\u0131daki github adresinden eri\u015febilirsiniz.<br \/>\n<a href=\"https:\/\/github.com\/gncyyldz\/Get.Current.User.Example\" rel=\"noopener\" target=\"_blank\">https:\/\/github.com\/gncyyldz\/Get.Current.User.Example<\/a><\/p>\n<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>Merhaba, Asp.NET Core ile geli\u015ftirdi\u011fimiz uygulamalar\u0131n \u00e7o\u011funda authentication ve authorization yayg\u0131n olarak kulland\u0131\u011f\u0131m\u0131z g\u00fcvenlik protokolleridir. Genellikle, bu protokoller neticesinde do\u011frulanan kullan\u0131c\u0131lar\u0131n bilgilerine eri\u015fim g\u00f6sterebildikleri noktalarda bizler taraf\u0131ndan ihtiya\u00e7 duyulabilmektedir. Bu konuya dair kaynaklar\u0131 tarad\u0131\u011f\u0131m\u0131zda&#46;&#46;&#46;<!-- AddThis Advanced Settings generic via filter on get_the_excerpt --><!-- AddThis Share Buttons generic via filter on get_the_excerpt --><\/p>\n","protected":false},"author":1,"featured_media":9596,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2739,3102],"tags":[2679,5044,5045],"class_list":["post-26951","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-net-core","category-asp-net-core","tag-asp-net-core","tag-asp-net-core-current-user","tag-current-user"],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/26951","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/comments?post=26951"}],"version-history":[{"count":6,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/26951\/revisions"}],"predecessor-version":[{"id":26957,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/26951\/revisions\/26957"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media\/9596"}],"wp:attachment":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media?parent=26951"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/categories?post=26951"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/tags?post=26951"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}