├── .gitignore
├── Api
├── Datastore
│ └── users.json
├── appsettings.json
├── wwwroot
│ └── web.config
├── Models
│ ├── User.cs
│ └── ApiDbContext.cs
├── Properties
│ └── launchSettings.json
├── project.json
├── Api.xproj
├── Auth
│ └── JWTAuth.cs
├── Startup.cs
└── Controllers
│ └── UsersController.cs
├── WpfClient
├── packages.config
├── App.config
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Globals.cs
├── App.xaml
├── App.xaml.cs
├── Models
│ └── User.cs
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── Pages
│ ├── LoginPage.xaml
│ ├── RegistrationPage.xaml
│ ├── LoginPage.xaml.cs
│ ├── DetailsPage.xaml
│ ├── RegistrationPage.xaml.cs
│ └── DetailsPage.xaml.cs
├── Operations
│ └── ApiOperations.cs
└── WpfClient.csproj
├── LICENSE
├── Csharp-jwt-authentication-sample.sln
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 |
--------------------------------------------------------------------------------
/Api/Datastore/users.json:
--------------------------------------------------------------------------------
1 | [ ]
--------------------------------------------------------------------------------
/WpfClient/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/WpfClient/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Api/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Verbose",
6 | "System": "Information",
7 | "Microsoft": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/WpfClient/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/WpfClient/Globals.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | using WpfClient.Models;
8 |
9 | namespace WpfClient
10 | {
11 | class Globals
12 | {
13 | public static User LoggedInUser { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/WpfClient/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/WpfClient/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Configuration;
4 | using System.Data;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 |
9 | namespace WpfClient
10 | {
11 | ///
12 | /// Interaction logic for App.xaml
13 | ///
14 | public partial class App : Application
15 | {
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Api/wwwroot/web.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/WpfClient/Models/User.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace WpfClient.Models
8 | {
9 | class User
10 | {
11 | public int Id { get; set; }
12 | public string Username { get; set; }
13 | public string Firstname { get; set; }
14 | public string Middlename { get; set; }
15 | public string Lastname { get; set; }
16 | public int Age { get; set; }
17 | public string access_token { get; set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Api/Models/User.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel.DataAnnotations;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 |
7 | namespace Api.Models
8 | {
9 | public class User
10 | {
11 | public int Id { get; set; }
12 | [Required]
13 | public string Username { get; set; }
14 | [Required]
15 | public string Password { get; set; }
16 | public string Firstname { get; set; }
17 | public string Middlename { get; set; }
18 | public string Lastname { get; set; }
19 | public int Age { get; set; }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/WpfClient/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Api/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:50369/",
7 | "sslPort": 0
8 | }
9 | },
10 | "profiles": {
11 | "IIS Express": {
12 | "commandName": "IISExpress",
13 | "launchBrowser": true,
14 | "launchUrl": "api/values",
15 | "environmentVariables": {
16 | "Hosting:Environment": "Development"
17 | }
18 | },
19 | "web": {
20 | "commandName": "web",
21 | "environmentVariables": {
22 | "Hosting:Environment": "Development"
23 | }
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/WpfClient/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Navigation;
14 | using System.Windows.Shapes;
15 |
16 | namespace WpfClient
17 | {
18 | ///
19 | /// Interaction logic for MainWindow.xaml
20 | ///
21 | public partial class MainWindow : Window
22 | {
23 | public MainWindow()
24 | {
25 | InitializeComponent();
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/Api/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "1.0.0-*",
3 | "compilationOptions": {
4 | "emitEntryPoint": true
5 | },
6 |
7 | "dependencies": {
8 | "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
9 | "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
10 | "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
11 | "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
12 | "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
13 | "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
14 | "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
15 | "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
16 | "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
17 | "Newtonsoft.Json": "8.0.3",
18 | "JWT": "1.3.4"
19 | },
20 |
21 | "commands": {
22 | "web": "Microsoft.AspNet.Server.Kestrel"
23 | },
24 |
25 | "frameworks": {
26 | "dnx451": { }
27 | },
28 |
29 | "exclude": [
30 | "wwwroot",
31 | "node_modules"
32 | ],
33 | "publishExclude": [
34 | "**.user",
35 | "**.vspscc"
36 | ]
37 | }
38 |
--------------------------------------------------------------------------------
/Api/Models/ApiDbContext.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 |
7 | using Newtonsoft.Json;
8 |
9 | namespace Api.Models
10 | {
11 | public class ApiDbContext
12 | {
13 | private string datastore;
14 |
15 | public ApiDbContext()
16 | {
17 | this.datastore = "./Datastore";
18 | InitializeFieldValues();
19 | }
20 |
21 | private void InitializeFieldValues()
22 | {
23 | // Get users
24 | string filename = "/users.json";
25 | string json = File.ReadAllText(this.datastore + filename);
26 | this.Users = JsonConvert.DeserializeObject>(json);
27 | }
28 |
29 | public List Users { get; set; }
30 |
31 | public void SaveChanges()
32 | {
33 | // Save users
34 | string json = JsonConvert.SerializeObject(this.Users);
35 | string filename = "/users.json";
36 | File.WriteAllText(this.datastore + filename, json);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Api/Api.xproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 14.0
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 |
7 |
8 |
9 | cb06044e-c84b-4163-8f45-c192ffab4f3f
10 | Api
11 | ..\artifacts\obj\$(MSBuildProjectName)
12 | ..\artifacts\bin\$(MSBuildProjectName)\
13 |
14 |
15 | 2.0
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 Prosper Otemuyiwa
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/WpfClient/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace WpfClient.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/WpfClient/Pages/LoginPage.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Csharp-jwt-authentication-sample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25123.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Api", "Api\Api.xproj", "{CB06044E-C84B-4163-8F45-C192FFAB4F3F}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfClient", "WpfClient\WpfClient.csproj", "{2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {CB06044E-C84B-4163-8F45-C192FFAB4F3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {CB06044E-C84B-4163-8F45-C192FFAB4F3F}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {CB06044E-C84B-4163-8F45-C192FFAB4F3F}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {CB06044E-C84B-4163-8F45-C192FFAB4F3F}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------
/Api/Auth/JWTAuth.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 |
6 | using Api.Models;
7 | using JWT;
8 | using Newtonsoft.Json.Linq;
9 |
10 | namespace Api.Auth
11 | {
12 | public class JWTAuth
13 | {
14 | // I know I know this shouldn't be visible
15 | // it's a sample cut me some slack 😊😊😋😋
16 | private static string secret = "Auth0 rocks!";
17 |
18 | public static string GenerateToken(User user)
19 | {
20 | DateTime expires = DateTime.UtcNow.AddDays(1);
21 | var payload = new Dictionary
22 | {
23 | {"user_id", user.Id},
24 | {"username", user.Username},
25 | {"expires", expires}
26 | };
27 |
28 | return JWT.JsonWebToken.Encode(payload, secret, JWT.JwtHashAlgorithm.HS256);
29 | }
30 |
31 | public static bool ValidateToken(string accessToken, int userId)
32 | {
33 | try
34 | {
35 | var payload = JWT.JsonWebToken.Decode(accessToken, secret);
36 | dynamic obj = JObject.Parse(payload);
37 | TimeSpan ts = DateTime.UtcNow - DateTime.Parse(obj.expires.ToString());
38 |
39 | if (obj.user_id == userId && ts.Days < 1)
40 | {
41 | return true;
42 | }
43 |
44 | return false;
45 | }
46 | catch (Exception)
47 | {
48 | return false;
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Api/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNet.Builder;
6 | using Microsoft.AspNet.Hosting;
7 | using Microsoft.Extensions.Configuration;
8 | using Microsoft.Extensions.DependencyInjection;
9 | using Microsoft.Extensions.Logging;
10 |
11 | namespace Api
12 | {
13 | public class Startup
14 | {
15 | public Startup(IHostingEnvironment env)
16 | {
17 | // Set up configuration sources.
18 | var builder = new ConfigurationBuilder()
19 | .AddJsonFile("appsettings.json")
20 | .AddEnvironmentVariables();
21 | Configuration = builder.Build();
22 | }
23 |
24 | public IConfigurationRoot Configuration { get; set; }
25 |
26 | // This method gets called by the runtime. Use this method to add services to the container.
27 | public void ConfigureServices(IServiceCollection services)
28 | {
29 | // Add framework services.
30 | services.AddMvc();
31 | }
32 |
33 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
34 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
35 | {
36 | loggerFactory.AddConsole(Configuration.GetSection("Logging"));
37 | loggerFactory.AddDebug();
38 |
39 | app.UseIISPlatformHandler();
40 |
41 | app.UseStaticFiles();
42 |
43 | app.UseMvc();
44 | }
45 |
46 | // Entry point for the application.
47 | public static void Main(string[] args) => WebApplication.Run(args);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/WpfClient/Pages/RegistrationPage.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/WpfClient/Pages/LoginPage.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Navigation;
14 | using System.Windows.Shapes;
15 |
16 | using WpfClient.Models;
17 | using WpfClient.Operations;
18 |
19 | namespace WpfClient.Pages
20 | {
21 | ///
22 | /// Interaction logic for LoginPage.xaml
23 | ///
24 | public partial class LoginPage : Page
25 | {
26 | public LoginPage()
27 | {
28 | InitializeComponent();
29 | }
30 |
31 | /**
32 | * Login Method to handle Login Button
33 | * @param object sender
34 | * @param RoutedEventArgs e
35 | */
36 | private void btnLogin_Click(object sender, RoutedEventArgs e)
37 | {
38 | string username = tbxUsername.Text;
39 | string password = pbxPassword.Password;
40 |
41 | ApiOperations ops = new ApiOperations();
42 | User user = ops.AuthenticateUser(username, password);
43 | if (user == null)
44 | {
45 | MessageBox.Show("Invalid username or password");
46 | return;
47 | }
48 |
49 | Globals.LoggedInUser = user;
50 | MessageBox.Show("Login successful");
51 | NavigationService.Navigate(new DetailsPage());
52 | }
53 |
54 | /**
55 | * Method to direct user to Register Page
56 | * @param object sender
57 | * @param RoutedEventArgs e
58 | */
59 | private void btnRegister_Click(object sender, RoutedEventArgs e)
60 | {
61 | NavigationService.Navigate(new RegistrationPage());
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/WpfClient/Pages/DetailsPage.xaml:
--------------------------------------------------------------------------------
1 |
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 |
--------------------------------------------------------------------------------
/WpfClient/Pages/RegistrationPage.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Navigation;
14 | using System.Windows.Shapes;
15 |
16 | using WpfClient.Models;
17 | using WpfClient.Operations;
18 |
19 | namespace WpfClient.Pages
20 | {
21 | ///
22 | /// Interaction logic for RegistrationPage.xaml
23 | ///
24 | public partial class RegistrationPage : Page
25 | {
26 | public RegistrationPage()
27 | {
28 | InitializeComponent();
29 | }
30 |
31 | /**
32 | * Register method to handle the Rgister Button
33 | * @param object sender
34 | * @param RoutedEventArgs e
35 | */
36 | private void btnReg_Click(object sender, RoutedEventArgs e)
37 | {
38 | string username = tbxUsername.Text;
39 | string password = pbxPassword.Password;
40 | string firstname = tbxFirstname.Text;
41 | string lastname = tbxLastname.Text;
42 | string middlename = tbxMiddlename.Text;
43 | int age = int.Parse(tbxAge.Text);
44 |
45 | ApiOperations ops = new ApiOperations();
46 | User user = ops.RegisterUser(username, password, firstname, lastname, middlename, age);
47 | if (user == null)
48 | {
49 | MessageBox.Show("Username already exists");
50 | return;
51 | }
52 |
53 | Globals.LoggedInUser = user;
54 | MessageBox.Show("Registration successful");
55 | NavigationService.Navigate(new DetailsPage());
56 | }
57 |
58 | /**
59 | * Method to handle going back to the previous screen
60 | * @param object sender
61 | * @param RoutedEventArgs e
62 | */
63 | private void btnBack_Click(object sender, RoutedEventArgs e)
64 | {
65 | NavigationService.GoBack();
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/WpfClient/Pages/DetailsPage.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Navigation;
14 | using System.Windows.Shapes;
15 |
16 | using WpfClient.Models;
17 | using WpfClient.Operations;
18 |
19 | namespace WpfClient.Pages
20 | {
21 | ///
22 | /// Interaction logic for DetailsPage.xaml
23 | ///
24 | public partial class DetailsPage : Page
25 | {
26 | public DetailsPage()
27 | {
28 | InitializeComponent();
29 | }
30 |
31 | /**
32 | * Details Page Loaded
33 | * @param object sender
34 | * @param RoutedEventArgs e
35 | */
36 | private void detailsPage_Loaded(object sender, RoutedEventArgs e)
37 | {
38 | FetchUserDetails();
39 | ShowUserInfo();
40 | }
41 |
42 | /**
43 | * Fetch User Details
44 | */
45 | private void FetchUserDetails()
46 | {
47 | ApiOperations ops = new ApiOperations();
48 | User user = ops.GetUserDetails(Globals.LoggedInUser);
49 | if (user == null)
50 | {
51 | MessageBox.Show("Session expired");
52 | // Navigate back to login page
53 | NavigationService.Navigate(new LoginPage());
54 | }
55 |
56 | Globals.LoggedInUser = user;
57 | }
58 |
59 | /**
60 | * Show User Info on the Screen
61 | */
62 | private void ShowUserInfo()
63 | {
64 | tbkWelcome.Text += " " + Globals.LoggedInUser.Username;
65 | tbkFname.Text = Globals.LoggedInUser.Firstname;
66 | tbkMname.Text = Globals.LoggedInUser.Middlename;
67 | tbkLname.Text = Globals.LoggedInUser.Lastname;
68 | tbkAge.Text = Globals.LoggedInUser.Age.ToString();
69 | }
70 |
71 | /**
72 | * Logout Method to be called on the logout Button
73 | * @param object sender
74 | * @param RoutedEventArgs e
75 | */
76 | private void btnLogout_Click(object sender, RoutedEventArgs e)
77 | {
78 | Globals.LoggedInUser = null;
79 | NavigationService.Navigate(new LoginPage());
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/WpfClient/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // General Information about an assembly is controlled through the following
8 | // set of attributes. Change these attribute values to modify the information
9 | // associated with an assembly.
10 | [assembly: AssemblyTitle("WpfClient")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("WpfClient")]
15 | [assembly: AssemblyCopyright("Copyright © 2016")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Setting ComVisible to false makes the types in this assembly not visible
20 | // to COM components. If you need to access a type in this assembly from
21 | // COM, set the ComVisible attribute to true on that type.
22 | [assembly: ComVisible(false)]
23 |
24 | //In order to begin building localizable applications, set
25 | //CultureYouAreCodingWith in your .csproj file
26 | //inside a . For example, if you are using US english
27 | //in your source files, set the to en-US. Then uncomment
28 | //the NeutralResourceLanguage attribute below. Update the "en-US" in
29 | //the line below to match the UICulture setting in the project file.
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
36 | //(used if a resource is not found in the page,
37 | // or application resource dictionaries)
38 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
39 | //(used if a resource is not found in the page,
40 | // app, or any theme specific resource dictionaries)
41 | )]
42 |
43 |
44 | // Version information for an assembly consists of the following four values:
45 | //
46 | // Major Version
47 | // Minor Version
48 | // Build Number
49 | // Revision
50 | //
51 | // You can specify all the values or you can default the Build and Revision Numbers
52 | // by using the '*' as shown below:
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("1.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.0.0")]
56 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Csharp JWT Authentication sample
2 |
3 | This is a Csharp Web API that supports username and password authentication with JWTs and has APIs that return user information to the GUI client and vice-versa.
4 |
5 | Everything about the Csharp WEB API runs from the `Api` Directory.
6 |
7 | The Desktop C# app runs from the `WpfClient` Directory.
8 |
9 | ## Available APIs
10 |
11 | ### User APIs
12 |
13 | #### POST `/users`
14 |
15 | You can do a POST to `/users` to create a new user.
16 |
17 | ```json
18 | {
19 | "username": "",
20 |
21 | "firstname": "",
22 |
23 | "middlename": "",
24 |
25 | "lastname": "",
26 |
27 | "age":
28 | }
29 | ```
30 |
31 | The body must have:
32 |
33 | * `username`: The username
34 | * `password`: The password
35 |
36 | It returns the following:
37 |
38 | ```json
39 | {
40 |
41 | "id": "",
42 |
43 | "username": "",
44 |
45 | "access_token": ""
46 | }
47 | ```
48 |
49 | That JWT will contain the `id`, `username` and an `expires` indicating when the token will expire.
50 |
51 | #### POST `/users/login`
52 |
53 | You can do a POST to `/users/login` to log a user in.
54 |
55 | The body must have:
56 |
57 | * `username`: The username
58 | * `password`: The password
59 |
60 | It returns the following:
61 |
62 | ```json
63 | {
64 |
65 | "id": "",
66 |
67 | "username": "",
68 |
69 | "access_token": ""
70 | }
71 | ```
72 |
73 | That JWT will contain the `id`, `username` and an `expires` indicating when the token will expire.
74 |
75 | ### User API
76 |
77 | #### GET `/api/users/{id}`
78 |
79 | Where `id` is the Id of a user
80 |
81 | It returns the complete user information
82 |
83 | ```json
84 | {
85 | "id": "",
86 | "username": "",
87 |
88 | "firstname": "",
89 |
90 | "middlename": "",
91 |
92 | "lastname": "",
93 |
94 | "age":
95 | }
96 | ```
97 |
98 | The JWT must be sent on the `Authorization` header as follows: `Authorization: `
99 |
100 | ## Running it
101 |
102 | Just clone the repository, and launch the solution in Visual Studio. That's it :).
103 | This project was built using Visual Studio 2015.
104 |
105 | ## Issue Reporting
106 |
107 | If you have found a bug or if you have a feature request, please report them at this repository issues section.
108 |
109 | ## Author
110 |
111 | [Prosper Otemuyiwa](https://twitter.com/unicodeveloper)
112 |
113 | ## License
114 |
115 | This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
116 |
--------------------------------------------------------------------------------
/WpfClient/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace WpfClient.Properties
12 | {
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// Returns the cached ResourceManager instance used by this class.
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WpfClient.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// Overrides the current thread's CurrentUICulture property for all
56 | /// resource lookups using this strongly typed resource class.
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/Api/Controllers/UsersController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNet.Mvc;
6 |
7 | using Api.Models;
8 | using Api.Auth;
9 |
10 | namespace Api.Controllers
11 | {
12 | [Route("api/[controller]")]
13 | public class UsersController : Controller
14 | {
15 | private ApiDbContext _db;
16 | public UsersController()
17 | {
18 | _db = new ApiDbContext();
19 | }
20 |
21 | [HttpGet("{id}")]
22 | public IActionResult Get(int id)
23 | {
24 | string token = this.Request.Headers["Authorization"];
25 | if (token == null)
26 | return HttpBadRequest(new { error = "No authorization header" });
27 |
28 | bool isValid = JWTAuth.ValidateToken(token, id);
29 | if (!isValid)
30 | {
31 | this.Response.StatusCode = 403;
32 | return new ObjectResult(new { error = "Invalid access token" });
33 | }
34 |
35 | User user = _db.Users.FirstOrDefault(u => u.Id == id);
36 | return new ObjectResult(new
37 | {
38 | user.Id,
39 | user.Username,
40 | user.Firstname,
41 | user.Middlename,
42 | user.Lastname,
43 | user.Age
44 | });
45 | }
46 |
47 | [HttpPost("login")]
48 | public IActionResult Login([FromBody]User user)
49 | {
50 | if (!ModelState.IsValid)
51 | {
52 | return HttpBadRequest(ModelState);
53 | }
54 |
55 | User _user = _db.Users.FirstOrDefault(
56 | u => u.Username == user.Username &&
57 | u.Password == user.Password);
58 |
59 | if (_user == null)
60 | return new HttpUnauthorizedResult();
61 |
62 | string accessToken = JWTAuth.GenerateToken(_user);
63 | return new ObjectResult(new
64 | {
65 | _user.Id,
66 | _user.Username,
67 | access_token = accessToken
68 | });
69 | }
70 |
71 | [HttpPost]
72 | public IActionResult Post([FromBody]User user)
73 | {
74 | if (!ModelState.IsValid)
75 | {
76 | return HttpBadRequest(ModelState);
77 | }
78 |
79 | var users = _db.Users;
80 |
81 | // Validate uniqueness of submitted username
82 | if (users.FirstOrDefault(u => u.Username == user.Username) != null)
83 | return HttpBadRequest(new { error = "Username already in use" });
84 |
85 | // Auto increment Id
86 | if (users.Count == 0)
87 | user.Id = 1;
88 | else
89 | user.Id = users.Last().Id + 1;
90 |
91 | _db.Users.Add(user);
92 | _db.SaveChanges();
93 |
94 | string accessToken = JWTAuth.GenerateToken(user);
95 | return new ObjectResult(new
96 | {
97 | user.Id,
98 | user.Username,
99 | access_token = accessToken
100 | });
101 | }
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/WpfClient/Operations/ApiOperations.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | using WpfClient.Models;
9 | using Newtonsoft.Json;
10 |
11 | namespace WpfClient.Operations
12 | {
13 | class ApiOperations
14 | {
15 | /**
16 | * Base Url @string
17 | */
18 | private string baseUrl;
19 |
20 | public ApiOperations()
21 | {
22 | this.baseUrl = "http://localhost:5000/api";
23 | }
24 |
25 | /**
26 | * Authenticate user with Web Api Endpoint
27 | * @param string username
28 | * @param string password
29 | */
30 | public User AuthenticateUser(string username, string password)
31 | {
32 | string endpoint = this.baseUrl + "/users/login";
33 | string method = "POST";
34 | string json = JsonConvert.SerializeObject(new
35 | {
36 | username = username,
37 | password = password
38 | });
39 |
40 | WebClient wc = new WebClient();
41 | wc.Headers["Content-Type"] = "application/json";
42 | try
43 | {
44 | string response = wc.UploadString(endpoint, method, json);
45 | return JsonConvert.DeserializeObject(response);
46 | }
47 | catch (Exception)
48 | {
49 | return null;
50 | }
51 | }
52 |
53 | /**
54 | * Get User Details from Web Api
55 | * @param User Model
56 | */
57 | public User GetUserDetails(User user)
58 | {
59 | string endpoint = this.baseUrl + "/users/" + user.Id;
60 | string access_token = user.access_token;
61 |
62 | WebClient wc = new WebClient();
63 | wc.Headers["Content-Type"] = "application/json";
64 | wc.Headers["Authorization"] = access_token;
65 | try
66 | {
67 | string response = wc.DownloadString(endpoint);
68 | user = JsonConvert.DeserializeObject(response);
69 | user.access_token = access_token;
70 | return user;
71 | }
72 | catch (Exception)
73 | {
74 | return null;
75 | }
76 | }
77 |
78 | /**
79 | * Register User
80 | * @param string username
81 | * @param string password
82 | * @param string firstname
83 | * @param string lastname
84 | * @param string middlename
85 | * @param int age
86 | */
87 | public User RegisterUser(string username, string password, string firstname,
88 | string lastname, string middlename, int age)
89 | {
90 | string endpoint = this.baseUrl + "/users";
91 | string method = "POST";
92 | string json = JsonConvert.SerializeObject(new
93 | {
94 | username = username,
95 | password = password,
96 | firstname = firstname,
97 | lastname = lastname,
98 | middlename = middlename,
99 | age = age
100 | });
101 |
102 | WebClient wc = new WebClient();
103 | wc.Headers["Content-Type"] = "application/json";
104 | try
105 | {
106 | string response = wc.UploadString(endpoint, method, json);
107 | return JsonConvert.DeserializeObject(response);
108 | }
109 | catch (Exception)
110 | {
111 | return null;
112 | }
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/WpfClient/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/WpfClient/WpfClient.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {2286BAA4-E658-4C5E-A085-5BC6C8FA0F78}
8 | WinExe
9 | Properties
10 | WpfClient
11 | WpfClient
12 | v4.6.1
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 | true
17 |
18 |
19 | AnyCPU
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 |
39 | ..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll
40 | True
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 | 4.0
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | MSBuild:Compile
60 | Designer
61 |
62 |
63 | MSBuild:Compile
64 | Designer
65 |
66 |
67 | App.xaml
68 | Code
69 |
70 |
71 |
72 | MainWindow.xaml
73 | Code
74 |
75 |
76 | Designer
77 | MSBuild:Compile
78 |
79 |
80 | Designer
81 | MSBuild:Compile
82 |
83 |
84 | Designer
85 | MSBuild:Compile
86 |
87 |
88 |
89 |
90 |
91 |
92 | DetailsPage.xaml
93 |
94 |
95 | LoginPage.xaml
96 |
97 |
98 | RegistrationPage.xaml
99 |
100 |
101 | Code
102 |
103 |
104 | True
105 | True
106 | Resources.resx
107 |
108 |
109 | True
110 | Settings.settings
111 | True
112 |
113 |
114 | ResXFileCodeGenerator
115 | Resources.Designer.cs
116 |
117 |
118 |
119 | SettingsSingleFileGenerator
120 | Settings.Designer.cs
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
135 |
--------------------------------------------------------------------------------