{"id":539,"date":"2016-09-22T16:31:33","date_gmt":"2016-09-22T14:31:33","guid":{"rendered":"https:\/\/zaven.co\/blog\/?p=539"},"modified":"2025-04-08T19:55:19","modified_gmt":"2025-04-08T17:55:19","slug":"user-authentication-web-api-2-jwt-token","status":"publish","type":"post","link":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/","title":{"rendered":"User Authentication in ASP.NET WEB API 2 with RSA-signed JWT Tokens (part 2)"},"content":{"rendered":"<p>In the second part on JWT Tokens we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2.<!--more--><\/p>\n<p>In <a href=\"https:\/\/zaven.co\/blog\/user-authentication-asp-net-web-api-2-rsa-encrypted-jwt-tokens-part-1\/\" target=\"_blank\" rel=\"noopener noreferrer\">the first part<\/a> we\u2019ve learnt about JWT structure and found out how Tokens are working. In the following examples we will use RSA for signing (an asymmetric coding algorithm) and Unity as a dependency injection container.<\/p>\n<h2><strong>JWT Token example<\/strong><\/h2>\n<p>To create, sign and validate tokens you can use an existing library provided by Microsoft: <code>System.IdentityModel.Tokens.Jwt<\/code>. You can download it right through NuGet.<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-medium wp-image-544\" src=\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/3-730x57.png\" alt=\" JWT Token example\"   srcset=\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/3-730x57.png 730w, https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/3.png 929w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<div id=\"attachment_545\" style=\"width: 594px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-545\" class=\"size-full wp-image-545\" src=\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/4..png\" alt=\"User Authentication\"  ><p id=\"caption-attachment-545\" class=\"wp-caption-text\">The architecture of our app<\/p><\/div>\n<h2>MembershipProvider<\/h2>\n<p>In the beginning we create a new class (<code>MembershipProvider<\/code>), which is responsible for downloading claims and validating the user.<\/p>\n<pre><code class=\"language-csharp\">\nusing System.Collections.Generic;\nusing System.Security.Claims;\nusing Zaven.Practices.Auth.JWT.Providers.Interfaces;\n...\npublic class MembershipProvider : IMembershipProvider\n    {\n        public List GetUserClaims(string username)\n        {\n            List claims = new List();\n            claims.Add(new Claim(ClaimTypes.Role, \"Admin\"));\n            claims.Add(new Claim(ClaimTypes.Email, \"admin93@gmail.com\"));\n            return claims; \n        }\n\n        public bool VerifyUserPassword(string username, string password)\n        {\n            if (username == \"admin93\" &amp;&amp; password == \"password\")\n                return true;\n            return false;\n        }\n    }\n<\/code><\/pre>\n<h2>RSAKeyProvider<\/h2>\n<p><code>RSAKeyProvider<\/code> <b>is responsible for providing the RSA key to encrypt\/decrypt the<\/b> <strong>JWT Token<\/strong>. In our example the RSA key is downloaded from a file in our repository, but in a real case scenario it should be kept in a safe place somewhere else.<\/p>\n<pre><code class=\"language-csharp\">using System;\nusing System.IO;\nusing System.Threading.Tasks;\nusing System.Security.Cryptography;\nusing Zaven.Practices.Auth.JWT.Providers.Interfaces;\n...\npublic class RSAKeyProvider : IRSAKeyProvider\n    {\n\n        private string rsaKeyPath;\n\n        public RSAKeyProvider()\n        {\n            rsaKeyPath = AppDomain.CurrentDomain.BaseDirectory + @\"RsaKeys\\RsaUserKey.txt\";\n        }\n\n        public async Task GetPrivateAndPublicKeyAsync()\n        {\n            string result = await ReadPrivateAndPublicKeyAsync();\n            if (string.IsNullOrEmpty(result))\n            {\n                string key = CreatePrivateAndPublicKey();\n                Boolean isInserted = await InsertPrivateAndPublicKeyAsync(key);\n                if (isInserted)\n                    result = key;\n            }\n            return result;\n        }\n\n        private string CreatePrivateAndPublicKey()\n        {\n            RSACryptoServiceProvider myRSA = new RSACryptoServiceProvider(2048);\n            RSAParameters publicKey = myRSA.ExportParameters(true);\n            string publicAndPrivateKey = myRSA.ToXmlString(true);\n            return publicAndPrivateKey;\n        }       \n\n        private async Task InsertPrivateAndPublicKeyAsync(string key)\n        {\n            Boolean result = false;\n            try\n            {\n                using (StreamWriter fileStream = new StreamWriter(rsaKeyPath))\n                {\n                    await fileStream.WriteLineAsync(key);\n                    result = true;\n                }\n            }\n            catch(Exception ex)\n            {\n                Debug.WriteLine(ex.Message);\n                result = false;\n            }\n            return result;            \n        }\n\n        private async Task ReadPrivateAndPublicKeyAsync()\n        {\n            String result = null;\n            try\n            {\n                using (StreamReader fileStream = new StreamReader(rsaKeyPath))\n                {\n                    result = await fileStream.ReadToEndAsync();\n                }\n            }\n            catch(Exception ex)\n            {\n                Debug.WriteLine(ex.Message);\n            }          \n            return result;\n        }\n}\n\n\n<\/code><\/pre>\n<p>The RSA key is generated in the <code>CreatePrivateAndPublicKey()<\/code> method using the existing RSACryptoServiceProvider class. The <code>ToXmlString(true)<\/code> method generates both public and private, while <code>ToXmlString(false)<\/code> only the public one.<\/p>\n<p>In <a href=\"https:\/\/zaven.co\/blog\/user-authentication-asp-net-web-api-2-rsa-encrypted-jwt-tokens-part-3\/\" target=\"_blank\" rel=\"noopener noreferrer\">the next part<\/a> we\u2019ll move on to <code>AuthService<\/code>. This is the most important element of the application because it\u2019s responsible for creating, signing and verifying the incoming <em>JWT token<\/em>.<\/p>\n<p><span style=\"color: #808080;\">Sources: <\/span><\/p>\n<ul>\n<li><a href=\"https:\/\/jwt.io\/\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">Official JWT website<\/a><\/li>\n<li><a href=\"http:\/\/dotnetcodes.com\/\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">.NET Codes website<\/a><\/li>\n<li><a href=\"https:\/\/msdn.microsoft.com\/pl-pl\/default.aspx\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">Microsoft Developer Network<\/a><\/li>\n<li><a href=\"http:\/\/www.asp.net\/\" target=\"_blank\" rel=\"noopener noreferrer nofollow\">The ASP.NET Site<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In the second part on JWT Tokens we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2.<\/p>\n","protected":false},"author":12,"featured_media":581,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[56,57,5],"tags":[48,47,40,8,49,41],"class_list":["post-539","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-ios-development","category-tutorials","tag-json-tokens","tag-jwt","tag-mobile-app","tag-tutorial","tag-user-authentication","tag-web-app"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.8.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog<\/title>\n<meta name=\"description\" content=\"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog\" \/>\n<meta property=\"og:description\" content=\"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/\" \/>\n<meta property=\"og:site_name\" content=\"Zaven Blog\" \/>\n<meta property=\"article:published_time\" content=\"2016-09-22T14:31:33+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-04-08T17:55:19+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1252\" \/>\n\t<meta property=\"og:image:height\" content=\"835\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Micha\u0142 Zawadzki\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Micha\u0142 Zawadzki\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/\",\"url\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/\",\"name\":\"User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog\",\"isPartOf\":{\"@id\":\"https:\/\/zaven.co\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg\",\"datePublished\":\"2016-09-22T14:31:33+00:00\",\"dateModified\":\"2025-04-08T17:55:19+00:00\",\"author\":{\"@id\":\"https:\/\/zaven.co\/blog\/#\/schema\/person\/7398fa7d171618b07d568aea38f1d17f\"},\"description\":\"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.\",\"breadcrumb\":{\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage\",\"url\":\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg\",\"contentUrl\":\"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg\",\"width\":1252,\"height\":835,\"caption\":\"User Authentication in ASP.NET WEB API 2 with RSA-encrypted JWT Tokens\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/zaven.co\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"User Authentication in ASP.NET WEB API 2 with RSA-signed JWT Tokens (part 2)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/zaven.co\/blog\/#website\",\"url\":\"https:\/\/zaven.co\/blog\/\",\"name\":\"Zaven Blog\",\"description\":\"Software development blog. Generative AI, web &amp; mobile applications.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/zaven.co\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/zaven.co\/blog\/#\/schema\/person\/7398fa7d171618b07d568aea38f1d17f\",\"name\":\"Micha\u0142 Zawadzki\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/zaven.co\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/ca67b3acf11d373f6677081d08548407?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/ca67b3acf11d373f6677081d08548407?s=96&d=mm&r=g\",\"caption\":\"Micha\u0142 Zawadzki\"},\"description\":\"Micha\u0142 is at the Back-end site of our software team, specializing in .NET web apps. Apart from being an excellent table tennis player, he\u2019s very much into sci-fi literature and computer games.\",\"sameAs\":[\"https:\/\/pl.linkedin.com\/in\/micha\u0142-zawadzki-003428126\"],\"url\":\"https:\/\/zaven.co\/blog\/author\/michal\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog","description":"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/","og_locale":"en_US","og_type":"article","og_title":"User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog","og_description":"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.","og_url":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/","og_site_name":"Zaven Blog","article_published_time":"2016-09-22T14:31:33+00:00","article_modified_time":"2025-04-08T17:55:19+00:00","og_image":[{"width":1252,"height":835,"url":"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg","type":"image\/jpeg"}],"author":"Micha\u0142 Zawadzki","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Micha\u0142 Zawadzki","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/","url":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/","name":"User Authentication in ASP.NET WEB API 2 with JWT Token | Zaven Blog","isPartOf":{"@id":"https:\/\/zaven.co\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage"},"image":{"@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage"},"thumbnailUrl":"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg","datePublished":"2016-09-22T14:31:33+00:00","dateModified":"2025-04-08T17:55:19+00:00","author":{"@id":"https:\/\/zaven.co\/blog\/#\/schema\/person\/7398fa7d171618b07d568aea38f1d17f"},"description":"In the second part on JWT Token we will implement a basic user authentication in a REST app based on ASP.NET WEB API 2. Read it and find out more about it.","breadcrumb":{"@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#primaryimage","url":"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg","contentUrl":"https:\/\/zaven.co\/blog\/wp-content\/uploads\/2016\/09\/klucze.jpg","width":1252,"height":835,"caption":"User Authentication in ASP.NET WEB API 2 with RSA-encrypted JWT Tokens"},{"@type":"BreadcrumbList","@id":"https:\/\/zaven.co\/blog\/user-authentication-web-api-2-jwt-token\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/zaven.co\/blog\/"},{"@type":"ListItem","position":2,"name":"User Authentication in ASP.NET WEB API 2 with RSA-signed JWT Tokens (part 2)"}]},{"@type":"WebSite","@id":"https:\/\/zaven.co\/blog\/#website","url":"https:\/\/zaven.co\/blog\/","name":"Zaven Blog","description":"Software development blog. Generative AI, web &amp; mobile applications.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/zaven.co\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/zaven.co\/blog\/#\/schema\/person\/7398fa7d171618b07d568aea38f1d17f","name":"Micha\u0142 Zawadzki","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/zaven.co\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/ca67b3acf11d373f6677081d08548407?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/ca67b3acf11d373f6677081d08548407?s=96&d=mm&r=g","caption":"Micha\u0142 Zawadzki"},"description":"Micha\u0142 is at the Back-end site of our software team, specializing in .NET web apps. Apart from being an excellent table tennis player, he\u2019s very much into sci-fi literature and computer games.","sameAs":["https:\/\/pl.linkedin.com\/in\/micha\u0142-zawadzki-003428126"],"url":"https:\/\/zaven.co\/blog\/author\/michal\/"}]}},"_links":{"self":[{"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/posts\/539","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/comments?post=539"}],"version-history":[{"count":16,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/posts\/539\/revisions"}],"predecessor-version":[{"id":69746,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/posts\/539\/revisions\/69746"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/media\/581"}],"wp:attachment":[{"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/media?parent=539"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/categories?post=539"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zaven.co\/blog\/wp-json\/wp\/v2\/tags?post=539"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}