﻿
{"id":10306,"date":"2019-02-12T23:10:35","date_gmt":"2019-02-12T23:10:35","guid":{"rendered":"https:\/\/www.gencayyildiz.com\/blog\/?p=10306"},"modified":"2019-02-12T23:10:35","modified_gmt":"2019-02-12T23:10:35","slug":"asp-net-core-angular-7-web-api-token-authentication-kullanimi","status":"publish","type":"post","link":"https:\/\/www.gencayyildiz.com\/blog\/asp-net-core-angular-7-web-api-token-authentication-kullanimi\/","title":{"rendered":"Asp.NET Core\/Angular 7 &#8211; Web Api Token Authentication Kullan\u0131m\u0131"},"content":{"rendered":"<div id=\"fb-root\"><\/div>\n<p>Merhaba,<\/p>\n<p>\u00d6nceki yaz\u0131lar\u0131mdan olan <a href=\"https:\/\/www.gencayyildiz.com\/blog\/asp-net-mvc-web-api-token-authentication\/\" rel=\"noopener\" target=\"_blank\">Asp.NET MVC \u2013 Web Api Token Authentication<\/a> ba\u015fl\u0131kl\u0131 i\u00e7eri\u011fimde standart Asp.NET MVC&#8217;de Web API kullan\u0131rken nas\u0131l Token Authentication uyguland\u0131\u011f\u0131n\u0131 incelemi\u015ftik. Bu i\u00e7eri\u011fimizde ise ayn\u0131 g\u00fcvenlik mekanizmas\u0131n\u0131 Asp.NET Core \u00e7ekirde\u011fi \u00fczerinde ger\u00e7ekle\u015ftirmeyi ele alacak, .NET Core mimarisinin yap\u0131s\u0131na uygun bir \u015fekilde durumu de\u011ferlendirecek ve nihai olarak Angular uygulamas\u0131yla yapt\u0131\u011f\u0131m\u0131z \u00e7al\u0131\u015fmay\u0131 test edece\u011fiz.<\/p>\n<p>\u0130lk olarak uygulamam\u0131za talepte bulunan kullan\u0131c\u0131ya \u00f6zel uygulamam\u0131z\u0131n ba\u015flang\u0131\u00e7 noktas\u0131 olan &#8220;Startup.cs&#8221; dosyas\u0131nda gerekli ayarlamalar\u0131 yaparak sistemde \u00f6ncelik olarak authentication kontrol\u00fc yap\u0131laca\u011f\u0131n\u0131 ve oturum i\u015flemine tabi tutulmaks\u0131z\u0131n herhangi bir request&#8217;in ba\u015far\u0131ya eri\u015femeyece\u011fini belirtmemiz gerekmektedir. Bunun i\u00e7in ilgili dosya i\u00e7erisinde tan\u0131mlanm\u0131\u015f olan &#8220;ConfigureServices&#8221; metoduna a\u015fa\u011f\u0131daki gibi tan\u0131mlama yapmam\u0131z gerekiyor.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n        public void ConfigureServices(IServiceCollection services)\r\n        {\r\n            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);\r\n\r\n            var appSettingsSection = Configuration.GetSection(&quot;AppSettings&quot;);\r\n            services.Configure&lt;AppSettings&gt;(appSettingsSection);\r\n            var appSettings = appSettingsSection.Get&lt;AppSettings&gt;();\r\n            var key = Encoding.ASCII.GetBytes(appSettings.Secret);\r\n            services.AddAuthentication(scheme =&gt;\r\n            {\r\n                scheme.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\r\n                scheme.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;\r\n            })\r\n            .AddJwtBearer(options =&gt;\r\n            {\r\n                options.RequireHttpsMetadata = false;\r\n                options.SaveToken = true;\r\n                options.TokenValidationParameters = new TokenValidationParameters\r\n                {\r\n                    ValidateIssuerSigningKey = true,\r\n                    IssuerSigningKey = new SymmetricSecurityKey(key),\r\n                    ValidateIssuer = false,\r\n                    ValidateAudience = false\r\n                };\r\n\r\n                options.Events = new JwtBearerEvents\r\n                {\r\n                    OnTokenValidated = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    },\r\n                    OnAuthenticationFailed = ctx =&gt;\r\n                    {\r\n                        Console.WriteLine($&quot;Exception : {ctx.Exception.Message}&quot;);\r\n                        return Task.CompletedTask;\r\n                    },\r\n                    OnChallenge = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    },\r\n                    OnMessageReceived = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    }\r\n                };\r\n            });\r\n        }\r\n\r\n        public Startup(IConfiguration configuration)\r\n        {\r\n            Configuration = configuration;\r\n        }\r\n\r\n        public IConfiguration Configuration { get; }\r\n<\/pre>\n<p>Yukar\u0131daki kod blo\u011funu detayl\u0131ca incelersek e\u011fer;<\/p>\n<ul>\n<li><strong><em>5. ve 8. Sat\u0131r Aral\u0131\u011f\u0131<\/em><\/strong><br \/>\nToken ile ilgili validasyon yap\u0131lanmas\u0131nda kullan\u0131lacak key de\u011ferini &#8220;appsettings.json&#8221; dosyas\u0131ndan okuyabilmek ve bunu &#8220;AppSettings&#8221; isimli bir s\u0131n\u0131f \u00fczerinden ger\u00e7ekle\u015ftirebilmek i\u00e7in yap\u0131lan klasik konfig\u00fcrasyon \u00e7al\u0131\u015fmas\u0131d\u0131r.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public class AppSettings\r\n    {\r\n        public string Secret { get; set; }\r\n    }\r\n<\/pre>\n<p>\u0130lgili &#8220;appsettings.json&#8221; dosyas\u0131n\u0131n i\u00e7eri\u011fi;<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n{\r\n  &quot;AppSettings&quot;: {\r\n    &quot;Secret&quot;: &quot;secret key&quot;\r\n  }\r\n}\r\n<\/pre>\n<p>\u015eimdi burada dikkatinizi \u00e7ekmek istedi\u011fim bir husus mevcut. Secret key de\u011ferine &#8217;16&#8217; karakterden az say\u0131da de\u011fer girilirse e\u011fer token olu\u015fturulurken a\u015fa\u011f\u0131daki hatayla kar\u015f\u0131la\u015f\u0131lmaktad\u0131r;<\/p>\n<blockquote><p>\n<strong><em>System.ArgumentOutOfRangeException: &#8216;IDX10603: Decryption failed. Keys tried: &#8216;[PII is hidden]&#8217;.<br \/>\nExceptions caught:<br \/>\n &#8216;[PII is hidden]&#8217;.<br \/>\ntoken: &#8216;[PII is hidden]&#8217;<\/em><\/strong>\n<\/p><\/blockquote>\n<p>Hatan\u0131n g\u00f6rsel halinide merak edenler i\u00e7in a\u015fa\u011f\u0131ya alal\u0131m;<br \/>\n<a href=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-Core-Web-Api-Token-Authentication.png\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-Core-Web-Api-Token-Authentication.png\" alt=\"Asp.NET Core - Web Api Token Authentication\" width=\"398\" height=\"118\" class=\"aligncenter size-full wp-image-10343\" srcset=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-Core-Web-Api-Token-Authentication.png 398w, https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-Core-Web-Api-Token-Authentication-300x89.png 300w\" sizes=\"auto, (max-width: 398px) 100vw, 398px\" \/><\/a><br \/>\nDolay\u0131s\u0131yla bu hataya yakalanmamak i\u00e7in &#8220;appsettings.json&#8221; dosyas\u0131n\u0131n i\u00e7eri\u011fini a\u015fa\u011f\u0131daki gibi uzun bir secret key ile d\u00fczenliyorum.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n{\r\n  &quot;AppSettings&quot;: {\r\n    &quot;Secret&quot;: &quot;gazla u\u00e7abilirsin amma frenle konamazs\u0131n...&quot;\r\n  }\r\n}\r\n<\/pre>\n<\/li>\n<li><em><strong>9. ve 13. Sat\u0131r Aral\u0131\u011f\u0131<\/strong><\/em><br \/>\n&#8220;AddAuthentication&#8221; metodu ile uygulamaya kimlik do\u011frulama servisi eklenmekte ve parametre olarak do\u011frulama \u015femalar\u0131 belirtilmektedir.\n<\/li>\n<li><em><strong>14. Sat\u0131r<\/strong><\/em><br \/>\n&#8220;AddJwtBearer&#8221; metodu ile kimlik do\u011frulama servisine JSON Web Token eklenmektedir.\n<\/li>\n<li><em><strong>16. ve 24. Sat\u0131r Aral\u0131\u011f\u0131<\/strong><\/em><br \/>\nClient taraf\u0131ndan g\u00f6nderilen request ile birlikte gelen tokenla ilgili belirli validation ayarlar\u0131, meta data kontrolleri ve kay\u0131t i\u015flemleri vs. ile ilgili ayarlamalar ger\u00e7ekle\u015ftirilmektedir.\n<\/li>\n<li><em><strong>26. ve 45. Sat\u0131r Aral\u0131\u011f\u0131<\/strong><\/em><br \/>\nRequest neticesinde gelen token\u0131n do\u011frulanma, iptal edilme, de\u011fi\u015fme yahut kabul edilme durumlar\u0131ndan haberdar olabilmemiz i\u00e7in ili\u015fkili eventlar tan\u0131mlanm\u0131\u015ft\u0131r. \u0130\u015fleyi\u015f s\u0131ras\u0131na g\u00f6re incelersek e\u011fer;<\/p>\n<ol>\n<li>\n<strong><em>OnMessageReceived<\/em><\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n                    OnMessageReceived = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    }\r\n<\/pre>\n<p>Client&#8217;tan gelen t\u00fcm talepleri, token olsun olmas\u0131n ilk kar\u015f\u0131layan ve kabul eden eventt\u0131r.\n<\/li>\n<li>\n<strong><em>OnTokenValidated<\/em><\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n                    OnTokenValidated = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    }\r\n<\/pre>\n<p>E\u011fer ki, taleple birlikte g\u00f6nderilen token ge\u00e7erliyse buras\u0131 tetiklenmekte ve do\u011frulama ile ilgili i\u015flemler ger\u00e7ekle\u015ftirilmektedir. Ard\u0131ndan requestin as\u0131l hedefi olan controller tetiklenmektedir.\n<\/li>\n<li>\n<strong><em>OnAuthenticationFailed<\/em><\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n                    OnAuthenticationFailed = ctx =&gt;\r\n                    {\r\n                        Console.WriteLine($&quot;Exception : {ctx.Exception.Message}&quot;);\r\n                        return Task.CompletedTask;\r\n                    }\r\n<\/pre>\n<p>Yok e\u011fer taleple birlikte gelen token ge\u00e7ersiz, eskimi\u015f yahut bozuk ise bu event tetiklenecektir.\n<\/li>\n<li>\n<strong><em>OnChallenge <\/em><\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n                    OnChallenge = ctx =&gt;\r\n                    {\r\n                        return Task.CompletedTask;\r\n                    }\r\n<\/pre>\n<p>Hatal\u0131 durumlarda &#8220;OnAuthenticationFailed&#8221; event\u0131n\u0131n ard\u0131ndan bu event tetiklenecektir.\n<\/li>\n<\/ol>\n<\/li>\n<\/ul>\n<p>T\u00fcm bu authentication konfig\u00fcrasyonundan sonra s\u0131ra, yine ayn\u0131 &#8220;Startup.cs&#8221; dosyas\u0131nda bulunan &#8220;Configure&#8221; metodunda yukar\u0131da tan\u0131mlanan ya da bir ba\u015fka deyi\u015fle konfig\u00fcre edilen kimlik do\u011frulama yap\u0131s\u0131n\u0131n uygulama taraf\u0131ndan kullan\u0131lmas\u0131n\u0131 belirtmeye gelmi\u015ftir. Bu i\u015flem i\u00e7in &#8220;UseAuthentication&#8221; middleware&#8217;ini kullanaca\u011f\u0131z.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n        public void Configure(IApplicationBuilder app, IHostingEnvironment env)\r\n        {\r\n            app.UseAuthentication();\r\n            app.UseMvc(routes =&gt;\r\n            {\r\n                routes.MapRoute(\r\n                    name: &quot;default&quot;,\r\n                    template: &quot;{controller}\/{action=Index}\/{id?}&quot;);\r\n            });\r\n        }\r\n<\/pre>\n<p>Art\u0131k uygulamam\u0131zda authentication aktif olacak bir \u015fekilde ayarland\u0131\u011f\u0131 i\u00e7in token \u00fcretimine ge\u00e7ebiliriz.<\/p>\n<p>\u0130lk olarak sisteme giri\u015f yapacak olan kullan\u0131c\u0131y\u0131 kar\u015f\u0131layacak nesnemizi belirleyelim. Ben burada \u00f6rnek olarak &#8220;Employee&#8221; entitysine karar verdim. Sizler ihtiyac\u0131n\u0131z do\u011frultusunda  istedi\u011finiz entityi olu\u015fturabilirsiniz.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public class Employee\r\n    {\r\n        public int Id { get; set; }\r\n        public string UserName { get; set; }\r\n        public string Password { get; set; }\r\n    }\r\n<\/pre>\n<p>Ard\u0131ndan olu\u015fturaca\u011f\u0131m\u0131z token\u0131n de\u011ferlerini tan\u0131mlama g\u00f6revini \u00fcstlenecek olan &#8220;TokenDescriptor&#8221; s\u0131n\u0131f\u0131m\u0131z\u0131 in\u015fa edelim.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public class TokenDescriptor\r\n    {\r\n        public Claim&#x5B;] Claims { get; set; }\r\n        public string Secret { get; set; }\r\n        public DateTime ExpiresValue { get; set; }\r\n    }\r\n<\/pre>\n<p>Yukar\u0131da olu\u015fturdu\u011fumuz &#8220;TokenDescriptor&#8221; s\u0131n\u0131f\u0131n\u0131n memberlar\u0131na g\u00f6z atarsak e\u011fer &#8220;Claims&#8221;, &#8220;Secret&#8221; ve &#8220;ExpiresValue&#8221; elemanlar\u0131 mevcuttur. S\u0131ras\u0131yla ne olduklar\u0131n\u0131 incelersek e\u011fer;<\/p>\n<ul>\n<li><strong><em>Claims<\/em><\/strong><br \/>\nClaim, olu\u015fturulacak token \u00fczerinde belirli bilgileri, verileri, talepleri, yetkileri vs. tutabilmek ve t\u00fcm bunlar\u0131 token de\u011ferine g\u00f6mebilmek i\u00e7in tasarlanm\u0131\u015f bir nesnedir. Dolay\u0131s\u0131yla Claims eleman\u0131 bu nesne tipinden bir koleksiyon g\u00f6revi g\u00f6rmekte ve tokenda tutulacak t\u00fcm harici verileri \u00fczerinden generate s\u00fcrecine dahil etme g\u00f6revini \u00fcstlenmektedir.<\/li>\n<li><em><strong>Secret<\/strong><\/em><br \/>\nToken olu\u015fturulurken kullan\u0131lacak secret key de\u011ferini ta\u015f\u0131maktad\u0131r.\n<\/li>\n<li><em><strong>ExpiresValue<\/strong><\/em><br \/>\nOlu\u015fturulacak token de\u011ferinin aktiflik s\u00fcresini tutacak olan elemand\u0131r.\n<\/li>\n<\/ul>\n<p>Ve son olarak token\u0131 olu\u015fturma operasyonunu ger\u00e7ekle\u015ftirecek olan s\u0131n\u0131f\u0131m\u0131z\u0131da in\u015fa edelim.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    public static class GenerateToken\r\n    {\r\n        public static string Generate(TokenDescriptor descriptor)\r\n        {\r\n            var tokenHandler = new JwtSecurityTokenHandler();\r\n            var tokenDescriptor = new SecurityTokenDescriptor\r\n            {\r\n                Subject = new ClaimsIdentity(descriptor.Claims),\r\n                Expires = descriptor.ExpiresValue,\r\n                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(descriptor.Secret)), SecurityAlgorithms.HmacSha256)\r\n            };\r\n            var token = tokenHandler.CreateToken(tokenDescriptor);\r\n            return tokenHandler.WriteToken(token);\r\n        }\r\n    }\r\n<\/pre>\n<p>Yukar\u0131daki kod blo\u011funa g\u00f6z atarsak e\u011fer static &#8220;GenerateToken&#8221; s\u0131n\u0131f\u0131 olu\u015fturulmu\u015f ve i\u00e7erisine &#8220;Generate&#8221; static metodu eklenmi\u015ftir. Dikkat ederseniz &#8220;Generate&#8221; metodu &#8220;TokenDescriptor&#8221; tipinden bir parametre almaktad\u0131r. \u0130\u00e7erisinde &#8220;SecurityTokenDescriptor&#8221; nesnesi \u00fczerinden &#8220;Claims&#8221;, &#8220;ExpresValue&#8221; ve &#8220;Secret&#8221; de\u011ferleri  belirtilmekte ve &#8220;HmacSha256&#8221; algoritmas\u0131 ile \u015fifreleme ger\u00e7ekle\u015ftirilmektedir. Ard\u0131ndan &#8220;JwtSecurityTokenHandler&#8221; nesnesi \u00fczerinden &#8220;CreateToken&#8221; metodu ile olu\u015fturdu\u011fumuz &#8220;SecurityTokenDescriptor&#8221; nesnesi handler ediliyor ve sonu\u00e7 metinsel olarak &#8220;WriteToken&#8221; metodu ile geriye d\u00f6nd\u00fcr\u00fcl\u00fcyor.<\/p>\n<p>Art\u0131k token altyap\u0131s\u0131yla beraber, generate i\u015flemi i\u00e7inde gerekli olan t\u00fcm yap\u0131lanma haz\u0131r bulunmaktad\u0131r. \u015eimdi token olu\u015fturmak i\u00e7in talep g\u00f6nderilecek Controller ve Action yap\u0131lanmas\u0131n\u0131 sa\u011flayal\u0131m.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    &#x5B;Route(&quot;api\/&#x5B;controller]&quot;)]\r\n    public class TokenController : ControllerBase\r\n    {\r\n        IConfiguration Configuration;\r\n        public TokenController(IConfiguration configuration)\r\n        {\r\n            this.Configuration = configuration;\r\n        }\r\n\r\n        &#x5B;HttpPost(&quot;&#x5B;action]&quot;)]\r\n        public IActionResult GetToken(&#x5B;FromBody]Employee model)\r\n        {\r\n            string secretSection = Configuration.GetSection(&quot;AppSettings&quot;).GetSection(&quot;Secret&quot;).Value;\r\n\r\n            string token = GenerateToken.Generate(new TokenDescriptor\r\n            {\r\n                Claims = new Claim&#x5B;]\r\n                    {\r\n                            new Claim(&quot;id&quot;,&quot;1&quot;),\r\n                            new Claim(&quot;userName&quot;, model.UserName),\r\n                            new Claim(&quot;password&quot;, model.Password),\r\n                            new Claim(&quot;email&quot;, &quot;gncy@gencayyildiz.com&quot;),\r\n                            new Claim(&quot;country&quot;, &quot;T\u00fcrkiye&quot;)\r\n                    },\r\n                ExpiresValue = DateTime.UtcNow.AddMinutes(5),\r\n                Secret = secretSection\r\n            });\r\n            return new JsonResult(new\r\n            {\r\n                Token = token\r\n            });\r\n        }\r\n    }\r\n<\/pre>\n<p>G\u00f6r\u00fcld\u00fc\u011f\u00fc \u00fczere &#8220;TokenController&#8221; isimli controller i\u00e7erisinde tan\u0131mlanan &#8220;GetToken&#8221; metodu olu\u015fturdu\u011fumuz &#8220;GenerateToken&#8221; s\u0131n\u0131f\u0131 \u00fczerinden token\u0131 \u00fcretmekte ve response olarak geriye d\u00f6nd\u00fcrmektedir.<\/p>\n<p>Bu noktadan itibaren token\u0131 \u00fcretecek alt yap\u0131y\u0131 tam teferruatl\u0131 sa\u011flam\u0131\u015f bulunmaktay\u0131z. \u015eimdi herhangi bir Angular uygulamas\u0131 \u00fczerinden Web API&#8217;mize ba\u011flanal\u0131m ve olu\u015fturdu\u011fumuz yap\u0131lanma \u00fczerinden token talep edip gerekli yetkilendirme i\u015flemlerini ger\u00e7ekle\u015ftirelim.<\/p>\n<h3>Angular Uygulamas\u0131 \u00dczerinden Token Talebi ve Authentication \u0130\u015flemleri<\/h3>\n<p>\u0130lk olarak aya\u011fa kald\u0131r\u0131lm\u0131\u015f herhangi bir Angular uygulamas\u0131 \u00fczerinden yukar\u0131da in\u015fa etti\u011fimiz token yap\u0131lanmas\u0131na talepte bulunuyoruz. Ard\u0131ndan elde edilen token ile Web API&#8217;a istekte bulunuyoruz. <\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;input type=&quot;text&quot; #txtKullaniciAdi placeholder=&quot;Kullan\u0131c\u0131 Ad\u0131&quot; \/&gt;&lt;br \/&gt;\r\n&lt;input type=&quot;text&quot; #txtSifre placeholder=&quot;\u015eifre&quot; \/&gt;&lt;br \/&gt;\r\n&lt;button (click)=&quot;Login(txtKullaniciAdi, txtSifre)&quot;&gt;Giri\u015f Yap&lt;\/button&gt;\r\n&lt;br \/&gt;\r\n&lt;div style=&quot;width:1000px;border-width:4px;border-color:brown; border-style:ridge;&quot;&gt;\r\n  &lt;p&gt;\r\n    Token : &lt;input type=&quot;text&quot; &#x5B;(ngModel)]=&quot;tokenKey&quot; style=&quot;width:1000px;&quot; #txtInputToken \/&gt;\r\n  &lt;\/p&gt;\r\n&lt;\/div&gt;\r\n&lt;br \/&gt;\r\n&lt;button (click)=&quot;CheckAuthorize(txtInputToken)&quot;&gt;Oturum Kontrol\u00fc&lt;\/button&gt;\r\n<\/pre>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nimport { Component, OnInit } from '@angular\/core';\r\nimport { HttpClient, HttpHeaders } from '@angular\/common\/http';\r\n\r\n@Component({\r\n  selector: 'app-login',\r\n  templateUrl: '.\/login.component.html',\r\n  styleUrls: &#x5B;'.\/login.component.css']\r\n})\r\nexport class LoginComponent implements OnInit {\r\n\r\n  constructor(private httpClient: HttpClient) { }\r\n\r\n  ngOnInit() {\r\n  }\r\n\r\n  tokenKey: string;\r\n  Login(txtKullaniciAdi: HTMLInputElement, txtSifre: HTMLInputElement) {\r\n    this.httpClient.post(&quot;https:\/\/localhost:5001\/api\/token\/gettoken&quot;, { userName: txtKullaniciAdi.value, password: txtSifre.value }).subscribe((data: { token: string }) =&gt; this.tokenKey = data.token);\r\n  }\r\n\r\n  CheckAuthorize(inputToken: HTMLInputElement) {\r\n    let _header = new HttpHeaders({\r\n      'Content-Type': 'application\/json',\r\n      'Authorization': `Bearer ${inputToken.value}`\r\n    });\r\n    this.httpClient.get(&quot;https:\/\/localhost:5001\/api\/home\/index&quot;, { headers: _header }).subscribe(data =&gt; { });\r\n  }\r\n}\r\n<\/pre>\n<p>Yukar\u0131daki kod bloklar\u0131n\u0131 incelersek e\u011fer &#8220;Giri\u015f Yap&#8221; butonuna t\u0131kland\u0131\u011f\u0131nda &#8220;Login&#8221; fonksiyonu tetiklenecek ve bu fonksiyon arac\u0131l\u0131\u011f\u0131yla Web API&#8217;a girilen kullan\u0131c\u0131 ad\u0131 ve \u015fifre de\u011ferlerine kar\u015f\u0131l\u0131k token iste\u011finde bulunulacakt\u0131r. Gelen token, &#8220;tokenKey&#8221; isimli de\u011fi\u015fkene atanacak ve bu \u015fekilde ilgili de\u011fi\u015fkeni model olarak g\u00f6ren &#8220;txtInputToken&#8221; isimli input i\u00e7erisine de\u011fer getirilecektir.<\/p>\n<p>&#8220;Oturum Kontrol\u00fc&#8221; butonuna t\u0131kland\u0131\u011f\u0131 zaman &#8220;CheckAuthorize&#8221; fonksiyonu tetiklenecektir. Bu fonksiyon, i\u00e7erisinde authentication kontrol\u00fc yap\u0131lan &#8220;HomeController&#8221; i\u00e7erisindeki &#8220;Index&#8221; action\u0131na ilgili token de\u011feri ile talepte bulunacakt\u0131r. E\u011fer token do\u011fruysa ilgili istek sonucunda &#8220;home\/index&#8221; tetiklenecek, aksi taktirde tetiklenmeyecektir.<\/p>\n<p>Yap\u0131lan t\u00fcm i\u015flemleri test etti\u011fimizde a\u015fa\u011f\u0131daki ekran g\u00f6r\u00fcnt\u00fcs\u00fcnde oldu\u011fu gibi bir s\u00fcre\u00e7le kar\u015f\u0131la\u015fmaktay\u0131z;<br \/>\n<div id=\"attachment_10396\" style=\"width: 810px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-CoreAngular-7-Web-Api-Token-Authentication-Kullan\u0131m\u0131.gif\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-10396\" src=\"https:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2019\/02\/Asp.NET-CoreAngular-7-Web-Api-Token-Authentication-Kullan\u0131m\u0131.gif\" alt=\"\" width=\"800\" height=\"462\" class=\"size-full wp-image-10396\" \/><\/a><p id=\"caption-attachment-10396\" class=\"wp-caption-text\">Asp.NET CoreAngular 7 &#8211; Web Api Token Authentication Kullan\u0131m\u0131<\/p><\/div><br \/>\nG\u00f6rsele dikkat ederseniz; kullan\u0131c\u0131 ad\u0131 ve \u015fifre girildikten sonra &#8220;Giri\u015f Yap&#8221; butonuna talep yap\u0131ld\u0131\u011f\u0131nda requesti ilk olarak &#8220;OnMessageReceived&#8221; event\u0131 kar\u015f\u0131lamakta ve ard\u0131ndan gerekli token \u00fcretimi ger\u00e7ekle\u015ftirilmektedir. \u00dcretilen token ile &#8220;Oturum Kontrol\u00fc&#8221; butonuna t\u0131kland\u0131\u011f\u0131nda tekrardan ilk olarak &#8220;OnMessageReceived&#8221; event\u0131 tetiklenmekte, ard\u0131ndan &#8220;OnTokenValidated&#8221; event\u0131n\u0131n tetiklenmesi ile token\u0131n do\u011fruland\u0131\u011f\u0131 anla\u015f\u0131lmaktad\u0131r. Dolay\u0131s\u0131yla hedef ba\u015far\u0131yla tetiklenmekte ve i\u015flem son bulmaktad\u0131r.<\/p>\n<p>Son hamlede ise, \u00fcretilen token\u0131n de\u011fi\u015ftirilmesi, bozulmas\u0131, ya\u015fam s\u00fcresinin sona ermesi durumlar\u0131na istinaden yap\u0131lan istekte her zamanki gibi ilk olarak &#8220;OnMessageReceived&#8221; event\u0131 kar\u015f\u0131lamakta lakin ilgili token do\u011frulanamad\u0131\u011f\u0131ndan dolay\u0131 &#8220;OnAuthenticationFailed&#8221; event\u0131 ile ba\u015far\u0131s\u0131zl\u0131k durumu devreye girmekte ve en son &#8220;OnChallenge&#8221; event\u0131n\u0131 tetikleyerek s\u00fcreci sonland\u0131rmaktad\u0131r.<\/p>\n<p>G\u00f6r\u00fcld\u00fc\u011f\u00fc \u00fczere Asp.NET Core ile Web Api Token Authentication kullan\u0131m\u0131 bu \u015fekilde ceyran etmektedir.<\/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<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>Merhaba, \u00d6nceki yaz\u0131lar\u0131mdan olan Asp.NET MVC \u2013 Web Api Token Authentication ba\u015fl\u0131kl\u0131 i\u00e7eri\u011fimde standart Asp.NET MVC&#8217;de Web API kullan\u0131rken nas\u0131l Token Authentication uyguland\u0131\u011f\u0131n\u0131 incelemi\u015ftik. Bu i\u00e7eri\u011fimizde ise ayn\u0131 g\u00fcvenlik mekanizmas\u0131n\u0131 Asp.NET Core \u00e7ekirde\u011fi \u00fczerinde&#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,2420,2668,2656],"tags":[2757,2679,2758,2759,2761,2762,2763,2760,2406,2405],"class_list":["post-10306","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-net-core","category-angular","category-asp-net-core-2","category-asp-net-core-2-mvc","tag-angular-7","tag-asp-net-core","tag-asp-net-core-token","tag-authentication","tag-onauthenticationfailed","tag-onchallenge","tag-onmessagereceived","tag-ontokenvalidated","tag-token-authentication","tag-web-api-token"],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/10306","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=10306"}],"version-history":[{"count":61,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/10306\/revisions"}],"predecessor-version":[{"id":10402,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/10306\/revisions\/10402"}],"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=10306"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/categories?post=10306"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/tags?post=10306"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}