﻿
{"id":8407,"date":"2018-07-01T14:55:36","date_gmt":"2018-07-01T14:55:36","guid":{"rendered":"http:\/\/www.gencayyildiz.com\/blog\/?p=8407"},"modified":"2018-07-01T14:55:45","modified_gmt":"2018-07-01T14:55:45","slug":"angular-ile-token-authentication-uygulanan-web-api-tetikleme","status":"publish","type":"post","link":"https:\/\/www.gencayyildiz.com\/blog\/angular-ile-token-authentication-uygulanan-web-api-tetikleme\/","title":{"rendered":"Angular \u0130le Token Authentication Uygulanan Web API Tetikleme"},"content":{"rendered":"<div id=\"fb-root\"><\/div>\n<p>Merhaba,<\/p>\n<p>Bir \u00f6nceki <a href=\"http:\/\/www.gencayyildiz.com\/blog\/angular-ile-web-api-tetikleme\/\" rel=\"noopener\" target=\"_blank\">Angular \u0130le Web API Tetikleme<\/a> ba\u015fl\u0131kl\u0131 makalemde Angular uygulamalar\u0131nda Web Apilerin nas\u0131l tetiklendi\u011fini incelemi\u015ftik lakin e\u011fer kullan\u0131lacak web apinin <a href=\"http:\/\/www.gencayyildiz.com\/blog\/asp-net-mvc-web-api-token-authentication\/\" rel=\"noopener\" target=\"_blank\">token authentication<\/a> ile g\u00fcvenli\u011fi sa\u011flanm\u0131\u015fsa nas\u0131l bir \u00e7al\u0131\u015fma yap\u0131lmas\u0131 gerekti\u011fini g\u00f6z ard\u0131 etmi\u015ftik. \u0130\u015fte bu i\u00e7eri\u011fimizde Angular uygulamalar\u0131nda token authentication ile g\u00fcvenlik \u00f6nlemi al\u0131nan web apilerin nas\u0131l tetiklenece\u011fini inceliyor olaca\u011f\u0131z.<\/p>\n<p>Yaz\u0131m\u0131za ba\u015flamadan \u00f6nce yukar\u0131da adresini vermi\u015f oldu\u011fum bir \u00f6nceki makalenin i\u00e7eri\u011finin bir devam\u0131 niteli\u011finde seyredece\u011fimizi bilmenizi isterim&#8230;<\/p>\n<p>\u0130lk olarak olu\u015fturdu\u011fumuz Web Apiyi Token Authentication ile g\u00fcvenlik kontrol\u00fcnden ge\u00e7irelim.(<span style=\"font-size:10px;\"><a href=\"http:\/\/www.gencayyildiz.com\/blog\/asp-net-mvc-web-api-token-authentication\/\" rel=\"noopener\" target=\"_blank\">token authentication<\/a> makalesini inceleyiniz.<\/span>)<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    &#x5B;Authorize]\r\n    public class PersonelController : ApiController\r\n    {\r\n        NorthwindEntities db = new NorthwindEntities();\r\n        public IEnumerable&lt;Personel&gt; GetAll() =&gt; db.Personeller.Select(p =&gt; new Personel\r\n        {\r\n            PersonelID = p.PersonelID,\r\n            Adi = p.Adi,\r\n            SoyAdi = p.SoyAdi,\r\n            Unvan = p.Unvan\r\n        }).ToList();\r\n        public Personel GetSingle(int id) =&gt; db.Personeller.FirstOrDefault(p =&gt; p.PersonelID == id);\r\n        public IHttpActionResult PostAdd(Personel p)\r\n        {\r\n            if (p != null)\r\n            {\r\n                db.Personeller.Add(p);\r\n                db.SaveChanges();\r\n                return Ok(p);\r\n            }\r\n            return Ok(&quot;Personel ekleme ba\u015far\u0131s\u0131z.&quot;);\r\n        }\r\n        public IHttpActionResult PutUpdate(Personel p)\r\n        {\r\n            if (p != null)\r\n            {\r\n                Personeller updatePersonel = db.Personeller.FirstOrDefault(u =&gt; u.PersonelID == p.PersonelID);\r\n                updatePersonel.Adi = p.Adi;\r\n                updatePersonel.SoyAdi = p.SoyAdi;\r\n                updatePersonel.Unvan = p.Unvan;\r\n                db.SaveChanges();\r\n                return Ok(updatePersonel);\r\n            }\r\n            return Ok(&quot;Personel g\u00fcncelle\u015ftirme ba\u015far\u0131s\u0131z.&quot;);\r\n        }\r\n        &#x5B;HttpDelete]\r\n        public IHttpActionResult Remove(int id)\r\n        {\r\n            Personeller deletePersonel = db.Personeller.FirstOrDefault(p =&gt; p.PersonelID == id);\r\n            db.Personeller.Remove(deletePersonel);\r\n            db.SaveChanges();\r\n            return Ok($&quot;\\&quot;{deletePersonel.Adi} {deletePersonel.SoyAdi}\\&quot; isimli personel ba\u015far\u0131yla silinmi\u015ftir.&quot;);\r\n        }\r\n    }\r\n<\/pre>\n<p>Bu \u015fekilde web apideki t\u00fcm metotlara eri\u015filebilmesi i\u00e7in token do\u011frulamas\u0131 mecburiyetini getirmi\u015f olduk.<\/p>\n<p>Ard\u0131ndan Angular uygulamam\u0131zda Token do\u011frulamas\u0131 neticesinde gelecek olan verileri kar\u015f\u0131layacak nesnemizi olu\u015ftural\u0131m.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nexport class Token {\r\n    access_token: string;\r\n    token_type: string;\r\n    expires_in: number;\r\n}\r\n<\/pre>\n<p>Akabinde Token do\u011frulamas\u0131 i\u00e7in post edece\u011fimiz veriyi temsil edecek nesneyide olu\u015ftural\u0131m.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nexport class PostToken {\r\n    username: string;\r\n    password: string;\r\n    grant_type: string;\r\n}\r\n<\/pre>\n<p>Bu verilerin neler oldu\u011funa dair kayna\u011f\u0131 belirtilen adresteki i\u00e7erikte detayl\u0131 a\u00e7\u0131klamalarda bulunmu\u015ftuk. <\/p>\n<p>\u015eimdi ise token do\u011frulmas\u0131n\u0131 tetikleyecek olan servisimizi olu\u015ftural\u0131m. Ben bu servise &#8220;AuthService&#8221; ismini yak\u0131\u015ft\u0131r\u0131yorum.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nimport { Injectable, Inject } from '@angular\/core';\r\nimport { HttpClient, HttpHeaders } from &quot;@angular\/common\/http&quot;;\r\nimport { PostToken } from '..\/classes\/posttoken';\r\nimport { Token } from '@angular\/compiler';\r\n\r\n\r\n@Injectable()\r\nexport class AuthService {\r\n\r\n  constructor(private httpClient: HttpClient, @Inject(&quot;url&quot;) private url: string) { }\r\n\r\n  GetToken(postToken: PostToken) {\r\n    let data = &quot;username=&quot; + postToken.username + &quot;&amp;password=&quot; + postToken.password + &quot;&amp;grant_type=&quot; + postToken.grant_type;\r\n    let headers = new HttpHeaders({ 'Content-Type': 'application\/x-www-form-urlencoded' });\r\n    return this.httpClient.post(this.url + &quot;token&quot;, data, { headers: headers });\r\n  }\r\n}\r\n<\/pre>\n<p>Burada dikkat edilmesi gereken husus, token i\u00e7in post edilecek datan\u0131n yukar\u0131daki formatta parse edilmi\u015f olmas\u0131 gerekmektedir. Ayr\u0131ca &#8220;HttpHeaders&#8221; nesnesi ile yapaca\u011f\u0131m\u0131z post i\u015fleminin &#8220;Content-Type&#8221; \u00f6zelli\u011fini &#8220;application\/x-www-form-urlencoded&#8221; \u015feklinde belirtmemiz gerekmektedir. Gerisi bu de\u011fi\u015fken ve nesneleri post fonksiyonunda ilgili alanlara belirtmektir.<\/p>\n<p>Hat\u0131rlarsan\u0131z bir \u00f6nceki yaz\u0131m\u0131zda &#8220;PersonelComponent&#8221; isminde bir componentimiz vard\u0131. Register i\u015flemleri i\u00e7in bu componentimize a\u015fa\u011f\u0131daki gibi ilgili fonksiyonu ekliyorum. Dolay\u0131s\u0131yla elde edilen token\u0131 &#8220;HttpHeaders&#8221; tipinden bir global de\u011fi\u015fkene at\u0131yorum ve t\u00fcm metotlar\u0131mda bu &#8220;HttpHeaders&#8221; nesnesini kullanarak al\u0131nan token ile gerekli i\u015flemleri ger\u00e7ekle\u015ftiriyorum.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nimport { Component, OnInit } from '@angular\/core';\r\nimport { Personel } from '..\/..\/classes\/personel';\r\nimport { PersonelService } from '..\/..\/services\/personel.service';\r\nimport { AuthService } from '..\/..\/services\/auth.service';\r\nimport { PostToken } from '..\/..\/classes\/posttoken';\r\nimport { Token } from '..\/..\/classes\/token';\r\nimport { HttpHeaders } from '@angular\/common\/http';\r\n\r\n@Component({\r\n  selector: 'app-personel',\r\n  templateUrl: '.\/personel.component.html',\r\n  styleUrls: &#x5B;'.\/personel.component.css']\r\n})\r\nexport class PersonelComponent implements OnInit {\r\n  personelList: Personel&#x5B;];\r\n  personel: Personel;\r\n  constructor(private personelService: PersonelService, private authService: AuthService) { }\r\n  headers: HttpHeaders;\r\n\r\n  ngOnInit() {\r\n  }\r\n  Register(username: HTMLInputElement, password: HTMLInputElement) {\r\n    let postToken: PostToken = {\r\n      username: username.value,\r\n      password: password.value,\r\n      grant_type: &quot;password&quot;\r\n    };\r\n    this.authService.GetToken(postToken).subscribe((response: Token) =&gt; {\r\n      this.headers = new HttpHeaders({ 'Authorization': 'Bearer ' + response.access_token });\r\n    });\r\n  }\r\n\r\n  GetAll() {\r\n    this.personelService.GetAll(this.headers).subscribe((response: Personel&#x5B;]) =&gt; this.personelList = response);\r\n  }\r\n  GetSingle(id: number) {\r\n    this.personelService.GetSingle(id, this.headers).subscribe((response: Personel) =&gt; this.personel = response);\r\n  }\r\n  PostAdd(adi: HTMLInputElement, soyAdi: HTMLInputElement, unvan: HTMLInputElement) {\r\n    let postPersonel: Personel = {\r\n      Adi: adi.value,\r\n      SoyAdi: soyAdi.value,\r\n      Unvan: unvan.value\r\n    };\r\n\r\n    this.personelService.PostAdd(postPersonel, this.headers).subscribe((response: Personel) =&gt; {\r\n      if (response) {\r\n        this.personelList.unshift(response);\r\n        this.personel = response;\r\n      }\r\n    });\r\n  }\r\n  PutUpdate(id: HTMLInputElement, adi: HTMLInputElement, soyAdi: HTMLInputElement, unvan: HTMLInputElement) {\r\n    let updatePersonel: Personel = {\r\n      PersonelID: Number(id.value),\r\n      Adi: adi.value,\r\n      SoyAdi: soyAdi.value,\r\n      Unvan: unvan.value\r\n    };\r\n    this.personelService.PutUpdate(updatePersonel, this.headers).subscribe((response: Personel) =&gt; {\r\n      if (response) {\r\n        this.GetAll();\r\n        this.personel = response;\r\n      }\r\n    });\r\n  }\r\n  Remove(id: number) {\r\n    this.personelService.Remove(id, this.headers).subscribe(response =&gt; {\r\n      alert(response);\r\n      this.GetAll();\r\n    });\r\n  }\r\n}\r\n<\/pre>\n<p>Tabi &#8220;PersonelService&#8221; isimli servis i\u00e7erisindeki fonksiyonlar\u0131m\u0131 buradaki imzalara uygun bir hale ve i\u015flevselli\u011fe getiriyorum.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nimport { Injectable, Inject } from '@angular\/core';\r\nimport { HttpClient, HttpHeaders } from &quot;@angular\/common\/http&quot;;\r\nimport { inject } from '@angular\/core\/src\/render3';\r\nimport { Personel } from '..\/classes\/personel';\r\n\r\n@Injectable()\r\nexport class PersonelService {\r\n\r\n  constructor(private httpClient: HttpClient, @Inject(&quot;url&quot;) private url: string) { }\r\n\r\n  GetAll(headers: HttpHeaders) {\r\n    return this.httpClient.get(this.url + &quot;api\/personel\/getall&quot;, { headers: headers });\r\n  }\r\n  GetSingle(id: number, headers: HttpHeaders) {\r\n    return this.httpClient.get(this.url + &quot;api\/personel\/getsingle\/&quot; + id, { headers: headers });\r\n  }\r\n  PostAdd(personel: Personel, headers: HttpHeaders) {\r\n    return this.httpClient.post(this.url + &quot;api\/personel\/postadd&quot;, personel, { headers: headers });\r\n  }\r\n  PutUpdate(personel: Personel, headers: HttpHeaders) {\r\n    return this.httpClient.put(this.url + &quot;api\/personel\/putupdate&quot;, personel, { headers: headers });\r\n  }\r\n  Remove(id: number, headers: HttpHeaders) {\r\n    return this.httpClient.delete(this.url + &quot;api\/personel\/remove\/&quot; + id, { headers: headers });\r\n  }\r\n}\r\n<\/pre>\n<p>\u0130\u015fte bitti&#8230;<\/p>\n<p>\u015eimdi projeyi kaydedip, \u00e7al\u0131\u015ft\u0131rma zaman\u0131&#8230;<\/p>\n<p>Hadi bakal\u0131m&#8230;<br \/>\n<a href=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/07\/Angular-\u0130le-Token-Authentication-Uygulanan-Web-API-Tetikleme.gif\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/07\/Angular-\u0130le-Token-Authentication-Uygulanan-Web-API-Tetikleme.gif\" alt=\"Angular \u0130le Token Authentication Uygulanan Web API Tetikleme\" width=\"600\" height=\"315\" class=\"aligncenter size-full wp-image-8422\" \/><\/a><br \/>\n<em>Hooppbala!<br \/>\n&#8220;Ulan tam \u00e7al\u0131\u015facak diye hevesleniyorduk, hevesimiz kursa\u011f\u0131m\u0131zda kald\u0131&#8230;&#8221;<\/em><br \/>\nNe ile kar\u015f\u0131la\u015ft\u0131k?<\/p>\n<blockquote><p>\n<strong>Failed to load http:\/\/localhost:50875\/api\/personel\/getall: Response to preflight request doesn&#8217;t pass access control check: No &#8216;Access-Control-Allow-Origin&#8217; header is present on the requested resource. Origin &#8216;http:\/\/localhost:4200&#8217; is therefore not allowed access. The response had HTTP status code 400.<\/strong>\n<\/p><\/blockquote>\n<blockquote><p>\n<strong>ERROR HttpErrorResponse\u00a0{headers: HttpHeaders, status: 0, statusText: &#8220;Unknown Error&#8221;, url: null, ok: false,\u00a0\u2026}<\/strong>\n<\/p><\/blockquote>\n<blockquote><p>\n<strong>zone.js:2969 Cross-Origin Read Blocking (CORB) blocked cross-origin response http:\/\/localhost:50875\/api\/personel\/getall with MIME type application\/json. See https:\/\/www.chromestatus.com\/feature\/5629709824032768 for more details.<\/strong>\n<\/p><\/blockquote>\n<p>hatalar\u0131yla&#8230;<\/p>\n<p>Sakin olun. Bu hatalar farkl\u0131 domainlerin birbirleriyle etkile\u015fim s\u00fcrecine girdiklerinde s\u00fcreci daha da sa\u011fl\u0131kl\u0131 kontrol edebilmek i\u00e7in g\u00fcvenlik ama\u00e7l\u0131 al\u0131nm\u0131\u015f \u00f6nlemlerden kaynaklanmaktad\u0131r. Bu hatalardan kurtulmak i\u00e7in ilgili Web API s\u0131n\u0131f\u0131n\u0131n ba\u015f\u0131na a\u015fa\u011f\u0131daki attribute&#8217;u oldu\u011fu gibi eklemeniz yeterli olacakt\u0131r.<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n&#x5B;EnableCors(origins: &quot;*&quot;, headers: &quot;*&quot;, methods: &quot;*&quot;)]\r\n<\/pre>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n    &#x5B;Authorize]\r\n    &#x5B;EnableCors(origins: &quot;*&quot;, headers: &quot;*&quot;, methods: &quot;*&quot;)]\r\n    public class PersonelController : ApiController\r\n    {\r\n        .\r\n        .\r\n        .\r\n    }\r\n<\/pre>\n<p>Bu ayarlamadan sonra projemizi kaydedip, yay\u0131nlad\u0131\u011f\u0131m\u0131zda art\u0131k sa\u011fl\u0131kl\u0131 bir \u015fekilde \u00e7al\u0131\u015ft\u0131\u011f\u0131n\u0131 g\u00f6receksiniz.<br \/>\n<a href=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/07\/Angular-\u0130le-Token-Authentication-Uygulanan-Web-API-Tetikleme-1.gif\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.gencayyildiz.com\/blog\/wp-content\/uploads\/2018\/07\/Angular-\u0130le-Token-Authentication-Uygulanan-Web-API-Tetikleme-1.gif\" alt=\"Angular \u0130le Token Authentication Uygulanan Web API Tetikleme\" width=\"600\" height=\"315\" class=\"aligncenter size-full wp-image-8425\" \/><\/a><\/p>\n<p>Bu uzun ve zahmetli makaleden sonra art\u0131k Angular uygulamalar\u0131nda Token Authentication uygulanm\u0131\u015f Web API&#8217;ler \u00fczerinde \u00e7al\u0131\u015fmalar\u0131n\u0131z\u0131 ger\u00e7ekle\u015ftirebileceksiniz.<\/p>\n<p>Faydal\u0131 bir i\u00e7erik olmas\u0131n\u0131 umut ediyorum.<\/p>\n<p>Sonraki 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, Bir \u00f6nceki Angular \u0130le Web API Tetikleme ba\u015fl\u0131kl\u0131 makalemde Angular uygulamalar\u0131nda Web Apilerin nas\u0131l tetiklendi\u011fini incelemi\u015ftik lakin e\u011fer kullan\u0131lacak web apinin token authentication ile g\u00fcvenli\u011fi sa\u011flanm\u0131\u015fsa nas\u0131l bir \u00e7al\u0131\u015fma yap\u0131lmas\u0131 gerekti\u011fini g\u00f6z ard\u0131&#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":8329,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2144,2415,11],"tags":[2418,2419,2416,2413,2414,2417,2399],"class_list":["post-8407","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular-4","category-angular-5","category-asp-net-mvc","tag-angular-token","tag-angular-token-authentication","tag-angular-token-authentication-web-api","tag-angular-web-api","tag-httpheaders","tag-token-authentication-web-api","tag-web-api"],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/8407","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=8407"}],"version-history":[{"count":18,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/8407\/revisions"}],"predecessor-version":[{"id":8428,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/posts\/8407\/revisions\/8428"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media\/8329"}],"wp:attachment":[{"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/media?parent=8407"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/categories?post=8407"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gencayyildiz.com\/blog\/wp-json\/wp\/v2\/tags?post=8407"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}