├── LICENSE ├── README.md ├── ngWithJwt.sln └── ngWithJwt ├── .gitignore ├── ClientApp ├── .browserslistrc ├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── e2e │ ├── protractor.conf.js │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.e2e.json ├── package-lock.json ├── package.json ├── src │ ├── app │ │ ├── admin-home │ │ │ ├── admin-home.component.css │ │ │ ├── admin-home.component.html │ │ │ ├── admin-home.component.spec.ts │ │ │ └── admin-home.component.ts │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── app.server.module.ts │ │ ├── guards │ │ │ ├── admin.guard.spec.ts │ │ │ ├── admin.guard.ts │ │ │ ├── auth.guard.spec.ts │ │ │ └── auth.guard.ts │ │ ├── home │ │ │ ├── home.component.html │ │ │ └── home.component.ts │ │ ├── login │ │ │ ├── login.component.css │ │ │ ├── login.component.html │ │ │ ├── login.component.spec.ts │ │ │ └── login.component.ts │ │ ├── models │ │ │ ├── roles.ts │ │ │ └── user.ts │ │ ├── nav-menu │ │ │ ├── nav-menu.component.css │ │ │ ├── nav-menu.component.html │ │ │ └── nav-menu.component.ts │ │ ├── services │ │ │ ├── auth.service.spec.ts │ │ │ ├── auth.service.ts │ │ │ ├── error-interceptor.service.spec.ts │ │ │ ├── error-interceptor.service.ts │ │ │ ├── http-interceptor.service.spec.ts │ │ │ ├── http-interceptor.service.ts │ │ │ ├── user.service.spec.ts │ │ │ └── user.service.ts │ │ └── user-home │ │ │ ├── user-home.component.css │ │ │ ├── user-home.component.html │ │ │ ├── user-home.component.spec.ts │ │ │ └── user-home.component.ts │ ├── assets │ │ └── .gitkeep │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── index.html │ ├── karma.conf.js │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ ├── test.ts │ ├── tsconfig.app.json │ ├── tsconfig.server.json │ ├── tsconfig.spec.json │ └── tslint.json ├── tsconfig.json └── tslint.json ├── Controllers ├── LoginController.cs └── UserController.cs ├── Models ├── Policies.cs └── User.cs ├── Pages ├── Error.cshtml ├── Error.cshtml.cs └── _ViewImports.cshtml ├── Program.cs ├── Properties └── launchSettings.json ├── Startup.cs ├── appsettings.Development.json ├── appsettings.json ├── ngWithJwt.csproj └── wwwroot └── favicon.ico /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Ankit 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 NONINFRINGEMENT. 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jwt-authentication-authorization-angular-aspnetcore 2 | In this article, we will create a web application using ASP.NET Core and Angular. We will then implement authentication and policy-based authorization in the application with the help of JWT. The web application will have two roles – Admin and User. The application will have role-based access for each role. We will learn how to configure and validate a JWT. 3 | 4 | # Demo 5 | ![Alt Text](https://ankitsharmablogs.com/wp-content/uploads/2019/11/ngjwt.gif) 6 | 7 | # Read the full article at 8 | https://ankitsharmablogs.com/policy-based-authorization-in-angular-using-jwt/ 9 | -------------------------------------------------------------------------------- /ngWithJwt.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29318.209 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ngWithJwt", "ngWithJwt\ngWithJwt.csproj", "{B733F6C9-FBFE-420B-B73B-734CA070C8DF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B733F6C9-FBFE-420B-B73B-734CA070C8DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B733F6C9-FBFE-420B-B73B-734CA070C8DF}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B733F6C9-FBFE-420B-B73B-734CA070C8DF}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B733F6C9-FBFE-420B-B73B-734CA070C8DF}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {E9B175B0-934E-44A9-91AA-38420CD0ABD4} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /ngWithJwt/.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | bin/ 23 | Bin/ 24 | obj/ 25 | Obj/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | *_i.c 44 | *_p.c 45 | *_i.h 46 | *.ilk 47 | *.meta 48 | *.obj 49 | *.pch 50 | *.pdb 51 | *.pgc 52 | *.pgd 53 | *.rsp 54 | *.sbr 55 | *.tlb 56 | *.tli 57 | *.tlh 58 | *.tmp 59 | *.tmp_proj 60 | *.log 61 | *.vspscc 62 | *.vssscc 63 | .builds 64 | *.pidb 65 | *.svclog 66 | *.scc 67 | 68 | # Chutzpah Test files 69 | _Chutzpah* 70 | 71 | # Visual C++ cache files 72 | ipch/ 73 | *.aps 74 | *.ncb 75 | *.opendb 76 | *.opensdf 77 | *.sdf 78 | *.cachefile 79 | 80 | # Visual Studio profiler 81 | *.psess 82 | *.vsp 83 | *.vspx 84 | *.sap 85 | 86 | # TFS 2012 Local Workspace 87 | $tf/ 88 | 89 | # Guidance Automation Toolkit 90 | *.gpState 91 | 92 | # ReSharper is a .NET coding add-in 93 | _ReSharper*/ 94 | *.[Rr]e[Ss]harper 95 | *.DotSettings.user 96 | 97 | # JustCode is a .NET coding add-in 98 | .JustCode 99 | 100 | # TeamCity is a build add-in 101 | _TeamCity* 102 | 103 | # DotCover is a Code Coverage Tool 104 | *.dotCover 105 | 106 | # NCrunch 107 | _NCrunch_* 108 | .*crunch*.local.xml 109 | nCrunchTemp_* 110 | 111 | # MightyMoose 112 | *.mm.* 113 | AutoTest.Net/ 114 | 115 | # Web workbench (sass) 116 | .sass-cache/ 117 | 118 | # Installshield output folder 119 | [Ee]xpress/ 120 | 121 | # DocProject is a documentation generator add-in 122 | DocProject/buildhelp/ 123 | DocProject/Help/*.HxT 124 | DocProject/Help/*.HxC 125 | DocProject/Help/*.hhc 126 | DocProject/Help/*.hhk 127 | DocProject/Help/*.hhp 128 | DocProject/Help/Html2 129 | DocProject/Help/html 130 | 131 | # Click-Once directory 132 | publish/ 133 | 134 | # Publish Web Output 135 | *.[Pp]ublish.xml 136 | *.azurePubxml 137 | # TODO: Comment the next line if you want to checkin your web deploy settings 138 | # but database connection strings (with potential passwords) will be unencrypted 139 | *.pubxml 140 | *.publishproj 141 | 142 | # NuGet Packages 143 | *.nupkg 144 | # The packages folder can be ignored because of Package Restore 145 | **/packages/* 146 | # except build/, which is used as an MSBuild target. 147 | !**/packages/build/ 148 | # Uncomment if necessary however generally it will be regenerated when needed 149 | #!**/packages/repositories.config 150 | 151 | # Microsoft Azure Build Output 152 | csx/ 153 | *.build.csdef 154 | 155 | # Microsoft Azure Emulator 156 | ecf/ 157 | rcf/ 158 | 159 | # Microsoft Azure ApplicationInsights config file 160 | ApplicationInsights.config 161 | 162 | # Windows Store app package directory 163 | AppPackages/ 164 | BundleArtifacts/ 165 | 166 | # Visual Studio cache files 167 | # files ending in .cache can be ignored 168 | *.[Cc]ache 169 | # but keep track of directories ending in .cache 170 | !*.[Cc]ache/ 171 | 172 | # Others 173 | ClientBin/ 174 | ~$* 175 | *~ 176 | *.dbmdl 177 | *.dbproj.schemaview 178 | *.pfx 179 | *.publishsettings 180 | orleans.codegen.cs 181 | 182 | /node_modules 183 | 184 | # RIA/Silverlight projects 185 | Generated_Code/ 186 | 187 | # Backup & report files from converting an old project file 188 | # to a newer Visual Studio version. Backup files are not needed, 189 | # because we have git ;-) 190 | _UpgradeReport_Files/ 191 | Backup*/ 192 | UpgradeLog*.XML 193 | UpgradeLog*.htm 194 | 195 | # SQL Server files 196 | *.mdf 197 | *.ldf 198 | 199 | # Business Intelligence projects 200 | *.rdl.data 201 | *.bim.layout 202 | *.bim_*.settings 203 | 204 | # Microsoft Fakes 205 | FakesAssemblies/ 206 | 207 | # GhostDoc plugin setting file 208 | *.GhostDoc.xml 209 | 210 | # Node.js Tools for Visual Studio 211 | .ntvs_analysis.dat 212 | 213 | # Visual Studio 6 build log 214 | *.plg 215 | 216 | # Visual Studio 6 workspace options file 217 | *.opt 218 | 219 | # Visual Studio LightSwitch build output 220 | **/*.HTMLClient/GeneratedArtifacts 221 | **/*.DesktopClient/GeneratedArtifacts 222 | **/*.DesktopClient/ModelManifest.xml 223 | **/*.Server/GeneratedArtifacts 224 | **/*.Server/ModelManifest.xml 225 | _Pvt_Extensions 226 | 227 | # Paket dependency manager 228 | .paket/paket.exe 229 | 230 | # FAKE - F# Make 231 | .fake/ 232 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed 5 | > 0.5% 6 | last 2 versions 7 | Firefox ESR 8 | not dead 9 | # IE 9-11 -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /dist-server 6 | /tmp 7 | /out-tsc 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | /.angular/cache 30 | /.sass-cache 31 | /connect.lock 32 | /coverage 33 | /libpeerconnection.log 34 | npm-debug.log 35 | yarn-error.log 36 | testem.log 37 | /typings 38 | 39 | # System Files 40 | .DS_Store 41 | Thumbs.db 42 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/README.md: -------------------------------------------------------------------------------- 1 | # ngWithJwt 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.0. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ngWithJwt": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": {}, 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "progress": true, 17 | "outputPath": "dist", 18 | "index": "src/index.html", 19 | "main": "src/main.ts", 20 | "polyfills": "src/polyfills.ts", 21 | "tsConfig": "src/tsconfig.app.json", 22 | "assets": [ 23 | "src/assets" 24 | ], 25 | "styles": [ 26 | "node_modules/bootstrap/dist/css/bootstrap.min.css", 27 | "src/styles.css" 28 | ], 29 | "scripts": [], 30 | "vendorChunk": true, 31 | "extractLicenses": false, 32 | "buildOptimizer": false, 33 | "sourceMap": true, 34 | "optimization": false, 35 | "namedChunks": true 36 | }, 37 | "configurations": { 38 | "production": { 39 | "budgets": [ 40 | { 41 | "type": "anyComponentStyle", 42 | "maximumWarning": "6kb" 43 | } 44 | ], 45 | "fileReplacements": [ 46 | { 47 | "replace": "src/environments/environment.ts", 48 | "with": "src/environments/environment.prod.ts" 49 | } 50 | ], 51 | "optimization": true, 52 | "outputHashing": "all", 53 | "sourceMap": false, 54 | "namedChunks": false, 55 | "extractLicenses": true, 56 | "vendorChunk": false, 57 | "buildOptimizer": true 58 | } 59 | }, 60 | "defaultConfiguration": "" 61 | }, 62 | "serve": { 63 | "builder": "@angular-devkit/build-angular:dev-server", 64 | "options": { 65 | "browserTarget": "ngWithJwt:build" 66 | }, 67 | "configurations": { 68 | "production": { 69 | "browserTarget": "ngWithJwt:build:production" 70 | } 71 | } 72 | }, 73 | "extract-i18n": { 74 | "builder": "@angular-devkit/build-angular:extract-i18n", 75 | "options": { 76 | "browserTarget": "ngWithJwt:build" 77 | } 78 | }, 79 | "test": { 80 | "builder": "@angular-devkit/build-angular:karma", 81 | "options": { 82 | "main": "src/test.ts", 83 | "polyfills": "src/polyfills.ts", 84 | "tsConfig": "src/tsconfig.spec.json", 85 | "karmaConfig": "src/karma.conf.js", 86 | "styles": ["styles.css"], 87 | "scripts": [], 88 | "assets": ["src/assets"] 89 | } 90 | }, 91 | "server": { 92 | "builder": "@angular-devkit/build-angular:server", 93 | "options": { 94 | "outputPath": "dist-server", 95 | "main": "src/main.ts", 96 | "tsConfig": "src/tsconfig.server.json", 97 | "sourceMap": true, 98 | "optimization": false 99 | }, 100 | "configurations": { 101 | "dev": { 102 | "optimization": true, 103 | "outputHashing": "all", 104 | "sourceMap": false, 105 | "namedChunks": false, 106 | "extractLicenses": true 107 | }, 108 | "production": { 109 | "optimization": true, 110 | "outputHashing": "all", 111 | "sourceMap": false, 112 | "namedChunks": false, 113 | "extractLicenses": true 114 | } 115 | }, 116 | "defaultConfiguration": "" 117 | } 118 | } 119 | }, 120 | "ngWithJwt-e2e": { 121 | "root": "e2e/", 122 | "projectType": "application", 123 | "architect": { 124 | "e2e": { 125 | "builder": "@angular-devkit/build-angular:protractor", 126 | "options": { 127 | "protractorConfig": "e2e/protractor.conf.js", 128 | "devServerTarget": "ngWithJwt:serve" 129 | } 130 | } 131 | } 132 | } 133 | }, 134 | "defaultProject": "ngWithJwt" 135 | } 136 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require("jasmine-spec-reporter"); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: ["./src/**/*.e2e-spec.ts"], 9 | capabilities: { 10 | browserName: "chrome" 11 | }, 12 | directConnect: true, 13 | baseUrl: "http://localhost:4200/", 14 | framework: "jasmine", 15 | jasmineNodeOpts: { 16 | showColors: true, 17 | defaultTimeoutInterval: 30000, 18 | print: function() {} 19 | }, 20 | onPrepare() { 21 | require("ts-node").register({ 22 | project: require("path").join(__dirname, "./tsconfig.e2e.json") 23 | }); 24 | jasmine 25 | .getEnv() 26 | .addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getMainHeading()).toEqual('Hello, world!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getMainHeading() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ngwithjwt", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "build:ssr": "ng run ngWithJwt:server:dev", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "13.0.2", 16 | "@angular/common": "13.0.2", 17 | "@angular/compiler": "13.0.2", 18 | "@angular/core": "13.0.2", 19 | "@angular/forms": "13.0.2", 20 | "@angular/platform-browser": "13.0.2", 21 | "@angular/platform-browser-dynamic": "13.0.2", 22 | "@angular/platform-server": "13.0.2", 23 | "@angular/router": "13.0.2", 24 | "@nguniversal/module-map-ngfactory-loader": "8.0.0-rc.1", 25 | "aspnet-prerendering": "^3.0.1", 26 | "bootstrap": "^4.3.1", 27 | "core-js": "^2.6.5", 28 | "jquery": "3.4.1", 29 | "oidc-client": "^1.9.0", 30 | "popper.js": "^1.14.3", 31 | "rxjs": "^6.6.3", 32 | "tslib": "^2.0.0", 33 | "zone.js": "~0.11.4" 34 | }, 35 | "devDependencies": { 36 | "@angular-devkit/build-angular": "~13.0.3", 37 | "@angular/cli": "13.0.3", 38 | "@angular/compiler-cli": "13.0.2", 39 | "@angular/language-service": "13.0.2", 40 | "@types/jasmine": "~3.3.9", 41 | "@types/jasminewd2": "~2.0.6", 42 | "@types/node": "^12.11.1", 43 | "codelyzer": "^5.1.2", 44 | "jasmine-core": "~3.5.0", 45 | "jasmine-spec-reporter": "~5.0.0", 46 | "karma": "~6.3.9", 47 | "karma-chrome-launcher": "~3.1.0", 48 | "karma-coverage-istanbul-reporter": "~3.0.2", 49 | "karma-jasmine": "~4.0.0", 50 | "karma-jasmine-html-reporter": "^1.5.0", 51 | "typescript": "4.4.4" 52 | }, 53 | "optionalDependencies": { 54 | "node-sass": "^4.9.3", 55 | "protractor": "~7.0.0", 56 | "ts-node": "~5.0.1", 57 | "tslint": "~6.1.0" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/admin-home/admin-home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitSharma-007/jwt-authentication-authorization-angular-aspnetcore/9ac1a641225b86f27fa80956ec94aa23fc3ca761/ngWithJwt/ClientApp/src/app/admin-home/admin-home.component.css -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/admin-home/admin-home.component.html: -------------------------------------------------------------------------------- 1 |

This is Admin home page

2 |
3 | 4 |
5 |
6 |
7 |

8 | {{adminData}} 9 |

10 |
-------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/admin-home/admin-home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { AdminHomeComponent } from './admin-home.component'; 4 | 5 | describe('AdminHomeComponent', () => { 6 | let component: AdminHomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ AdminHomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(AdminHomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/admin-home/admin-home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { UserService } from '../services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-admin-home', 6 | templateUrl: './admin-home.component.html', 7 | styleUrls: ['./admin-home.component.css'] 8 | }) 9 | export class AdminHomeComponent { 10 | 11 | adminData: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | fetchAdminData() { 16 | this.userService.getAdminData().subscribe( 17 | (result: string) => { 18 | this.adminData = result; 19 | } 20 | ); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 |
6 | 7 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { AuthService } from './services/auth.service'; 3 | 4 | @Component({ 5 | selector: 'app-root', 6 | templateUrl: './app.component.html' 7 | }) 8 | export class AppComponent { 9 | title = 'app'; 10 | 11 | constructor(private authService: AuthService) { 12 | if (localStorage.getItem('authToken')) { 13 | this.authService.setUserDetails(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 4 | import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; 5 | import { RouterModule } from '@angular/router'; 6 | 7 | import { AppComponent } from './app.component'; 8 | import { NavMenuComponent } from './nav-menu/nav-menu.component'; 9 | import { HomeComponent } from './home/home.component'; 10 | 11 | import { LoginComponent } from './login/login.component'; 12 | import { UserHomeComponent } from './user-home/user-home.component'; 13 | import { AuthGuard } from './guards/auth.guard'; 14 | import { HttpInterceptorService } from './services/http-interceptor.service'; 15 | import { ErrorInterceptorService } from './services/error-interceptor.service'; 16 | import { AdminHomeComponent } from './admin-home/admin-home.component'; 17 | import { AdminGuard } from './guards/admin.guard'; 18 | 19 | @NgModule({ 20 | declarations: [ 21 | AppComponent, 22 | NavMenuComponent, 23 | HomeComponent, 24 | LoginComponent, 25 | UserHomeComponent, 26 | AdminHomeComponent 27 | ], 28 | imports: [ 29 | BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }), 30 | HttpClientModule, 31 | FormsModule, 32 | ReactiveFormsModule, 33 | RouterModule.forRoot([ 34 | { path: '', component: HomeComponent, pathMatch: 'full' }, 35 | { path: 'login', component: LoginComponent }, 36 | { path: 'user-home', component: UserHomeComponent, canActivate: [AuthGuard] }, 37 | { path: 'admin-home', component: AdminHomeComponent, canActivate: [AdminGuard] } 38 | ], { relativeLinkResolution: 'legacy' }) 39 | ], 40 | providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }, 41 | { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }, 42 | ], 43 | bootstrap: [AppComponent] 44 | }) 45 | export class AppModule { } 46 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/app.server.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { ServerModule } from '@angular/platform-server'; 3 | import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader'; 4 | import { AppComponent } from './app.component'; 5 | import { AppModule } from './app.module'; 6 | 7 | @NgModule({ 8 | imports: [AppModule, ServerModule, ModuleMapLoaderModule], 9 | bootstrap: [AppComponent] 10 | }) 11 | export class AppServerModule { } 12 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/guards/admin.guard.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { AdminGuard } from './admin.guard'; 4 | 5 | describe('AdminGuard', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [AdminGuard] 9 | }); 10 | }); 11 | 12 | it('should ...', inject([AdminGuard], (guard: AdminGuard) => { 13 | expect(guard).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/guards/admin.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthService } from '../services/auth.service'; 5 | import { User } from '../models/user'; 6 | import { UserRole } from '../models/roles'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AdminGuard implements CanActivate { 12 | 13 | userDataSubscription: any; 14 | userData = new User(); 15 | 16 | constructor(private router: Router, private authService: AuthService) { 17 | this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => { 18 | this.userData = data; 19 | }); 20 | } 21 | 22 | canActivate( 23 | next: ActivatedRouteSnapshot, 24 | state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { 25 | 26 | if (this.userData.role === UserRole.Admin) { 27 | return true; 28 | } 29 | 30 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 31 | return false; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/guards/auth.guard.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { AuthGuard } from './auth.guard'; 4 | 5 | describe('AuthGuard', () => { 6 | beforeEach(() => { 7 | TestBed.configureTestingModule({ 8 | providers: [AuthGuard] 9 | }); 10 | }); 11 | 12 | it('should ...', inject([AuthGuard], (guard: AuthGuard) => { 13 | expect(guard).toBeTruthy(); 14 | })); 15 | }); 16 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/guards/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { AuthService } from '../services/auth.service'; 5 | import { User } from '../models/user'; 6 | import { UserRole } from '../models/roles'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthGuard implements CanActivate { 12 | 13 | userDataSubscription: any; 14 | userData = new User(); 15 | 16 | constructor(private router: Router, private authService: AuthService) { 17 | this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => { 18 | this.userData = data; 19 | }); 20 | } 21 | 22 | canActivate( 23 | next: ActivatedRouteSnapshot, 24 | state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { 25 | 26 | if (this.userData.role == UserRole.User) { 27 | return true; 28 | } 29 | 30 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 31 | return false; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |

Hello, world!

2 |

Welcome to your new single-page application, built with:

3 | 8 |

To help you get started, we've also set up:

9 |
    10 |
  • Client-side navigation. For example, click Counter then Back to return here.
  • 11 |
  • Angular CLI integration. In development mode, there's no need to run ng serve. It runs in the background automatically, so your client-side resources are dynamically built on demand and the page refreshes when you modify any file.
  • 12 |
  • Efficient production builds. In production mode, development-time features are disabled, and your dotnet publish configuration automatically invokes ng build to produce minified, ahead-of-time compiled JavaScript files.
  • 13 |
14 |

The ClientApp subdirectory is a standard Angular CLI application. If you open a command prompt in that directory, you can run any ng command (e.g., ng test), or use npm to install extra packages into it.

15 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | }) 7 | export class HomeComponent { 8 | } 9 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/login/login.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitSharma-007/jwt-authentication-authorization-angular-aspnetcore/9ac1a641225b86f27fa80956ec94aa23fc3ca761/ngWithJwt/ClientApp/src/app/login/login.component.css -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | Username or Password is incorrect. 4 |
5 |
6 |
JWT authentication with Angular and .NET
7 |
8 |
9 |
10 | 11 | 13 |
14 |
Username is required
15 |
16 |
17 |
18 | 19 | 21 |
22 |
Password is required
23 |
24 |
25 | 29 |
30 |
31 |
32 |
33 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(LoginComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { FormGroup, FormBuilder, Validators } from '@angular/forms'; 3 | import { ActivatedRoute, Router } from '@angular/router'; 4 | import { AuthService } from '../services/auth.service'; 5 | 6 | @Component({ 7 | selector: 'app-login', 8 | templateUrl: './login.component.html', 9 | styleUrls: ['./login.component.css'] 10 | }) 11 | export class LoginComponent implements OnInit { 12 | 13 | loading = false; 14 | loginForm: FormGroup; 15 | submitted = false; 16 | returnUrl: string; 17 | 18 | constructor(private formBuilder: FormBuilder, 19 | private route: ActivatedRoute, 20 | private router: Router, 21 | private authService: AuthService) { } 22 | 23 | ngOnInit() { 24 | this.loginForm = this.formBuilder.group({ 25 | username: ['', Validators.required], 26 | password: ['', Validators.required] 27 | }); 28 | } 29 | 30 | get loginFormControl() { return this.loginForm.controls; } 31 | 32 | onSubmit() { 33 | this.submitted = true; 34 | 35 | if (this.loginForm.invalid) { 36 | return; 37 | } 38 | 39 | this.loading = true; 40 | const returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') || '/'; 41 | this.authService.login(this.loginForm.value) 42 | .subscribe( 43 | () => { 44 | this.router.navigate([returnUrl]); 45 | }, 46 | () => { 47 | this.loading = false; 48 | this.loginForm.reset(); 49 | this.loginForm.setErrors({ 50 | invalidLogin: true 51 | }); 52 | }); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/models/roles.ts: -------------------------------------------------------------------------------- 1 | export enum UserRole { 2 | Admin = 'Admin', 3 | User = 'User' 4 | } 5 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/models/user.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | userName: string; 3 | firstName: string; 4 | isLoggedIn: boolean; 5 | role: string; 6 | } 7 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/nav-menu/nav-menu.component.css: -------------------------------------------------------------------------------- 1 | a.navbar-brand { 2 | white-space: normal; 3 | text-align: center; 4 | word-break: break-all; 5 | } 6 | 7 | html { 8 | font-size: 14px; 9 | } 10 | @media (min-width: 768px) { 11 | html { 12 | font-size: 16px; 13 | } 14 | } 15 | 16 | .box-shadow { 17 | box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); 18 | } 19 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/nav-menu/nav-menu.component.html: -------------------------------------------------------------------------------- 1 |
2 | 81 |
82 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/nav-menu/nav-menu.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { AuthService } from '../services/auth.service'; 3 | import { User } from '../models/user'; 4 | import { UserRole } from '../models/roles'; 5 | 6 | @Component({ 7 | selector: 'app-nav-menu', 8 | templateUrl: './nav-menu.component.html', 9 | styleUrls: ['./nav-menu.component.css'] 10 | }) 11 | export class NavMenuComponent { 12 | isExpanded = false; 13 | userDataSubscription: any; 14 | userData = new User(); 15 | userRole = UserRole; 16 | 17 | constructor(private authService: AuthService) { 18 | this.userDataSubscription = this.authService.userData.asObservable().subscribe(data => { 19 | this.userData = data; 20 | }); 21 | } 22 | 23 | collapse() { 24 | this.isExpanded = false; 25 | } 26 | 27 | toggle() { 28 | this.isExpanded = !this.isExpanded; 29 | } 30 | 31 | logout() { 32 | this.authService.logout(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthService } from './auth.service'; 4 | 5 | describe('AuthService', () => { 6 | beforeEach(() => TestBed.configureTestingModule({})); 7 | 8 | it('should be created', () => { 9 | const service: AuthService = TestBed.get(AuthService); 10 | expect(service).toBeTruthy(); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { BehaviorSubject } from 'rxjs'; 4 | import { map } from 'rxjs/operators'; 5 | import { Router } from '@angular/router'; 6 | import { User } from '../models/user'; 7 | 8 | @Injectable({ 9 | providedIn: 'root' 10 | }) 11 | export class AuthService { 12 | 13 | userData = new BehaviorSubject(new User()); 14 | 15 | constructor(private http: HttpClient, private router: Router) { } 16 | 17 | login(userDetails) { 18 | return this.http.post('/api/login', userDetails) 19 | .pipe(map(response => { 20 | localStorage.setItem('authToken', response.token); 21 | this.setUserDetails(); 22 | return response; 23 | })); 24 | } 25 | 26 | setUserDetails() { 27 | if (localStorage.getItem('authToken')) { 28 | const userDetails = new User(); 29 | const decodeUserDetails = JSON.parse(window.atob(localStorage.getItem('authToken').split('.')[1])); 30 | 31 | userDetails.userName = decodeUserDetails.sub; 32 | userDetails.firstName = decodeUserDetails.firstName; 33 | userDetails.isLoggedIn = true; 34 | userDetails.role = decodeUserDetails.role; 35 | 36 | this.userData.next(userDetails); 37 | } 38 | } 39 | 40 | logout() { 41 | localStorage.removeItem('authToken'); 42 | this.router.navigate(['/login']); 43 | this.userData.next(new User()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/error-interceptor.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { ErrorInterceptorService } from './error-interceptor.service'; 4 | 5 | describe('ErrorInterceptorService', () => { 6 | beforeEach(() => TestBed.configureTestingModule({})); 7 | 8 | it('should be created', () => { 9 | const service: ErrorInterceptorService = TestBed.get(ErrorInterceptorService); 10 | expect(service).toBeTruthy(); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/error-interceptor.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { AuthService } from './auth.service'; 3 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 4 | import { Observable, throwError } from 'rxjs'; 5 | import { catchError } from 'rxjs/operators'; 6 | 7 | @Injectable({ 8 | providedIn: 'root' 9 | }) 10 | export class ErrorInterceptorService implements HttpInterceptor { 11 | 12 | constructor(private authService: AuthService) { } 13 | 14 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 15 | return next.handle(request).pipe(catchError(err => { 16 | if (err.status === 401) { 17 | this.authService.logout(); 18 | } 19 | return throwError(err.status); 20 | })); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/http-interceptor.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { HttpInterceptorService } from './http-interceptor.service'; 4 | 5 | describe('HttpInterceptorService', () => { 6 | beforeEach(() => TestBed.configureTestingModule({})); 7 | 8 | it('should be created', () => { 9 | const service: HttpInterceptorService = TestBed.get(HttpInterceptorService); 10 | expect(service).toBeTruthy(); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/http-interceptor.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class HttpInterceptorService implements HttpInterceptor { 9 | 10 | constructor() { } 11 | 12 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 13 | 14 | const token = localStorage.getItem('authToken'); 15 | 16 | if (token) { 17 | request = request.clone({ 18 | setHeaders: { 19 | Authorization: `Bearer ${token}`, 20 | } 21 | }); 22 | } 23 | return next.handle(request); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserService', () => { 6 | beforeEach(() => TestBed.configureTestingModule({})); 7 | 8 | it('should be created', () => { 9 | const service: UserService = TestBed.get(UserService); 10 | expect(service).toBeTruthy(); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | 4 | @Injectable({ 5 | providedIn: 'root' 6 | }) 7 | export class UserService { 8 | 9 | constructor(private http: HttpClient) { } 10 | 11 | getUserData() { 12 | return this.http.get('/api/user/GetUserData'); 13 | } 14 | 15 | getAdminData() { 16 | return this.http.get('/api/user/GetAdminData'); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/user-home/user-home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitSharma-007/jwt-authentication-authorization-angular-aspnetcore/9ac1a641225b86f27fa80956ec94aa23fc3ca761/ngWithJwt/ClientApp/src/app/user-home/user-home.component.css -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/user-home/user-home.component.html: -------------------------------------------------------------------------------- 1 |

This is User home page

2 |
3 | 4 |
5 |
6 |
7 |

8 | {{userData}} 9 |

10 |
-------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/user-home/user-home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; 2 | 3 | import { UserHomeComponent } from './user-home.component'; 4 | 5 | describe('UserHomeComponent', () => { 6 | let component: UserHomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(waitForAsync(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ UserHomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(UserHomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/app/user-home/user-home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { UserService } from '../services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-user-home', 6 | templateUrl: './user-home.component.html', 7 | styleUrls: ['./user-home.component.css'] 8 | }) 9 | export class UserHomeComponent { 10 | 11 | userData: string; 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | fetchUserData() { 16 | this.userService.getUserData().subscribe( 17 | (result: string) => { 18 | this.userData = result; 19 | } 20 | ); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitSharma-007/jwt-authentication-authorization-angular-aspnetcore/9ac1a641225b86f27fa80956ec94aa23fc3ca761/ngWithJwt/ClientApp/src/assets/.gitkeep -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * In development mode, to ignore zone related error stack frames such as 11 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can 12 | * import the following file, but please comment it out in production mode 13 | * because it will have performance impact when throw error 14 | */ 15 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 16 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ngWithJwt 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | export function getBaseUrl() { 8 | return document.getElementsByTagName('base')[0].href; 9 | } 10 | 11 | const providers = [ 12 | { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] } 13 | ]; 14 | 15 | if (environment.production) { 16 | enableProdMode(); 17 | } 18 | 19 | platformBrowserDynamic(providers).bootstrapModule(AppModule) 20 | .catch(err => console.log(err)); 21 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** 22 | * By default, zone.js will patch all possible macroTask and DomEvents 23 | * user can disable parts of macroTask/DomEvents patch by setting following flags 24 | * because those flags need to be set before `zone.js` being loaded, and webpack 25 | * will put import in the top of bundle, so user need to create a separate file 26 | * in this directory (for example: zone-flags.ts), and put the following flags 27 | * into that file, and then add the following code before importing zone.js. 28 | * import './zone-flags.ts'; 29 | * 30 | * The flags allowed in zone-flags.ts are listed here. 31 | * 32 | * The following flags will work for all browsers. 33 | * 34 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 35 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 36 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 37 | * 38 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 39 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 40 | * 41 | * (window as any).__Zone_enable_cross_context_check = true; 42 | * 43 | */ 44 | 45 | /*************************************************************************************************** 46 | * Zone JS is required by default for Angular itself. 47 | */ 48 | import 'zone.js'; // Included with Angular CLI. 49 | 50 | 51 | /*************************************************************************************************** 52 | * APPLICATION IMPORTS 53 | */ 54 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | 3 | /* Provide sufficient contrast against white background */ 4 | a { 5 | color: #0366d6; 6 | } 7 | 8 | code { 9 | color: #e01a76; 10 | } 11 | 12 | .btn-primary { 13 | color: #fff; 14 | background-color: #1b6ec2; 15 | border-color: #1861ac; 16 | } 17 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting(), { 16 | teardown: { destroyAfterEach: false } 17 | } 18 | ); 19 | // Then we find all the tests. 20 | const context = require.context('./', true, /\.spec\.ts$/); 21 | // And load the modules. 22 | context.keys().map(context); 23 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "main.ts", 9 | "polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/tsconfig.server.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "target": "es2016" 5 | }, 6 | "angularCompilerOptions": { 7 | "entryModule": "app/app.server.module#AppServerModule" 8 | } , 9 | "files": [ 10 | "main.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "module": "es2020", 6 | "outDir": "./dist/out-tsc", 7 | "sourceMap": true, 8 | "declaration": false, 9 | "moduleResolution": "node", 10 | "experimentalDecorators": true, 11 | "target": "es2015", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ngWithJwt/ClientApp/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs/Rx" 22 | ], 23 | "import-spacing": true, 24 | "indent": [ 25 | true, 26 | "spaces" 27 | ], 28 | "interface-over-type-literal": true, 29 | "label-position": true, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-arg": true, 47 | "no-bitwise": true, 48 | "no-console": [ 49 | true, 50 | "debug", 51 | "info", 52 | "time", 53 | "timeEnd", 54 | "trace" 55 | ], 56 | "no-construct": true, 57 | "no-debugger": true, 58 | "no-duplicate-super": true, 59 | "no-empty": false, 60 | "no-empty-interface": true, 61 | "no-eval": true, 62 | "no-inferrable-types": [ 63 | true, 64 | "ignore-params" 65 | ], 66 | "no-misused-new": true, 67 | "no-non-null-assertion": true, 68 | "no-shadowed-variable": true, 69 | "no-string-literal": false, 70 | "no-string-throw": true, 71 | "no-switch-case-fall-through": true, 72 | "no-trailing-whitespace": true, 73 | "no-unnecessary-initializer": true, 74 | "no-unused-expression": true, 75 | "no-var-keyword": true, 76 | "object-literal-sort-keys": false, 77 | "one-line": [ 78 | true, 79 | "check-open-brace", 80 | "check-catch", 81 | "check-else", 82 | "check-whitespace" 83 | ], 84 | "prefer-const": true, 85 | "quotemark": [ 86 | true, 87 | "single" 88 | ], 89 | "radix": true, 90 | "semicolon": [ 91 | true, 92 | "always" 93 | ], 94 | "triple-equals": [ 95 | true, 96 | "allow-null-check" 97 | ], 98 | "typedef-whitespace": [ 99 | true, 100 | { 101 | "call-signature": "nospace", 102 | "index-signature": "nospace", 103 | "parameter": "nospace", 104 | "property-declaration": "nospace", 105 | "variable-declaration": "nospace" 106 | } 107 | ], 108 | "unified-signatures": true, 109 | "variable-name": false, 110 | "whitespace": [ 111 | true, 112 | "check-branch", 113 | "check-decl", 114 | "check-operator", 115 | "check-separator", 116 | "check-type" 117 | ], 118 | "no-output-on-prefix": true, 119 | "no-inputs-metadata-property": true, 120 | "no-outputs-metadata-property": true, 121 | "no-host-metadata-property": true, 122 | "no-input-rename": true, 123 | "no-output-rename": true, 124 | "use-lifecycle-interface": true, 125 | "use-pipe-transform-interface": true, 126 | "component-class-suffix": true, 127 | "directive-class-suffix": true 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /ngWithJwt/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.IdentityModel.Tokens; 5 | using ngWithJwt.Models; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IdentityModel.Tokens.Jwt; 9 | using System.Linq; 10 | using System.Security.Claims; 11 | using System.Text; 12 | 13 | namespace ngWithJwt.Controllers 14 | { 15 | [Produces("application/json")] 16 | [Route("api/[controller]")] 17 | public class LoginController : Controller 18 | { 19 | private readonly IConfiguration _config; 20 | 21 | // user details are hardcoded for simplicity. Ideally it should be stored in a database. 22 | private List appUsers = new List 23 | { 24 | new User { FirstName = "Admin", UserName = "admin", Password = "1234", UserType = "Admin" }, 25 | new User { FirstName = "Ankit", UserName = "ankit", Password = "1234", UserType = "User" } 26 | }; 27 | 28 | public LoginController(IConfiguration config) 29 | { 30 | _config = config; 31 | } 32 | 33 | [HttpPost] 34 | [AllowAnonymous] 35 | public IActionResult Login([FromBody] User login) 36 | { 37 | IActionResult response = Unauthorized(); 38 | 39 | User user = AuthenticateUser(login); 40 | if (user != null) 41 | { 42 | var tokenString = GenerateJWT(user); 43 | response = Ok(new 44 | { 45 | token = tokenString, 46 | userDetails = user, 47 | }); 48 | } 49 | 50 | return response; 51 | } 52 | 53 | User AuthenticateUser(User loginCredentials) 54 | { 55 | User user = appUsers.SingleOrDefault(x => x.UserName == loginCredentials.UserName && x.Password == loginCredentials.Password); 56 | 57 | return user; 58 | } 59 | 60 | string GenerateJWT(User userInfo) 61 | { 62 | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])); 63 | var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); 64 | 65 | var claims = new[] 66 | { 67 | new Claim(JwtRegisteredClaimNames.Sub, userInfo.UserName), 68 | new Claim("firstName", userInfo.FirstName.ToString()), 69 | new Claim("role",userInfo.UserType), 70 | new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), 71 | }; 72 | 73 | var token = new JwtSecurityToken( 74 | issuer: _config["Jwt:Issuer"], 75 | audience: _config["Jwt:Audience"], 76 | claims: claims, 77 | expires: DateTime.Now.AddMinutes(30), 78 | signingCredentials: credentials 79 | ); 80 | 81 | return new JwtSecurityTokenHandler().WriteToken(token); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /ngWithJwt/Controllers/UserController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using ngWithJwt.Models; 4 | 5 | namespace ngWithJwt.Controllers 6 | { 7 | [Produces("application/json")] 8 | [Route("api/[controller]")] 9 | public class UserController : Controller 10 | { 11 | [HttpGet] 12 | [Route("GetUserData")] 13 | [Authorize(Policy = Policies.User)] 14 | public IActionResult GetUserData() 15 | { 16 | return Ok("This is an normal user"); 17 | } 18 | 19 | [HttpGet] 20 | [Route("GetAdminData")] 21 | [Authorize(Policy = Policies.Admin)] 22 | public IActionResult GetAdminData() 23 | { 24 | return Ok("This is an Admin user"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ngWithJwt/Models/Policies.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using System; 3 | 4 | namespace ngWithJwt.Models 5 | { 6 | public static class Policies 7 | { 8 | public const string Admin = "Admin"; 9 | public const string User = "User"; 10 | 11 | public static AuthorizationPolicy AdminPolicy() 12 | { 13 | return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(Admin).Build(); 14 | } 15 | 16 | public static AuthorizationPolicy UserPolicy() 17 | { 18 | return new AuthorizationPolicyBuilder().RequireAuthenticatedUser().RequireRole(User).Build(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ngWithJwt/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ngWithJwt.Models 4 | { 5 | public class User 6 | { 7 | public string UserName { get; set; } 8 | public string FirstName { get; set; } 9 | public string Password { get; set; } 10 | public string UserType { get; set; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ngWithJwt/Pages/Error.cshtml: -------------------------------------------------------------------------------- 1 | @page 2 | @model ErrorModel 3 | @{ 4 | ViewData["Title"] = "Error"; 5 | } 6 | 7 |

Error.

8 |

An error occurred while processing your request.

9 | 10 | @if (Model.ShowRequestId) 11 | { 12 |

13 | Request ID: @Model.RequestId 14 |

15 | } 16 | 17 |

Development Mode

18 |

19 | Swapping to the Development environment displays detailed information about the error that occurred. 20 |

21 |

22 | The Development environment shouldn't be enabled for deployed applications. 23 | It can result in displaying sensitive information from exceptions to end users. 24 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development 25 | and restarting the app. 26 |

27 | -------------------------------------------------------------------------------- /ngWithJwt/Pages/Error.cshtml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.AspNetCore.Mvc.RazorPages; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace ngWithJwt.Pages 11 | { 12 | [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 13 | public class ErrorModel : PageModel 14 | { 15 | private readonly ILogger _logger; 16 | 17 | public ErrorModel(ILogger logger) 18 | { 19 | _logger = logger; 20 | } 21 | 22 | public string RequestId { get; set; } 23 | 24 | public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); 25 | 26 | public void OnGet() 27 | { 28 | RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ngWithJwt/Pages/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using ngWithJwt 2 | @namespace ngWithJwt.Pages 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | -------------------------------------------------------------------------------- /ngWithJwt/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace ngWithJwt 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateWebHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 20 | WebHost.CreateDefaultBuilder(args) 21 | .UseStartup(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ngWithJwt/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:63834", 7 | "sslPort": 44373 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "ngWithJwt": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ngWithJwt/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.SpaServices.AngularCli; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.IdentityModel.Tokens; 9 | using ngWithJwt.Models; 10 | using System; 11 | using System.Text; 12 | 13 | namespace ngWithJwt 14 | { 15 | public class Startup 16 | { 17 | public Startup(IConfiguration configuration) 18 | { 19 | Configuration = configuration; 20 | } 21 | 22 | public IConfiguration Configuration { get; } 23 | 24 | // This method gets called by the runtime. Use this method to add services to the container. 25 | public void ConfigureServices(IServiceCollection services) 26 | { 27 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 28 | .AddJwtBearer(options => 29 | { 30 | options.RequireHttpsMetadata = false; 31 | options.SaveToken = true; 32 | options.TokenValidationParameters = new TokenValidationParameters 33 | { 34 | ValidateIssuer = true, 35 | ValidateAudience = true, 36 | ValidateLifetime = true, 37 | ValidateIssuerSigningKey = true, 38 | ValidIssuer = Configuration["Jwt:Issuer"], 39 | ValidAudience = Configuration["Jwt:Audience"], 40 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), 41 | ClockSkew = TimeSpan.Zero // Override the default clock skew of 5 mins 42 | }; 43 | services.AddCors(); 44 | }); 45 | 46 | services.AddAuthorization(config => 47 | { 48 | config.AddPolicy(Policies.Admin, Policies.AdminPolicy()); 49 | config.AddPolicy(Policies.User, Policies.UserPolicy()); 50 | }); 51 | 52 | services.AddControllersWithViews(); 53 | 54 | // In production, the Angular files will be served from this directory 55 | services.AddSpaStaticFiles(configuration => 56 | { 57 | configuration.RootPath = "ClientApp/dist"; 58 | }); 59 | } 60 | 61 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 62 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 63 | { 64 | if (env.IsDevelopment()) 65 | { 66 | app.UseDeveloperExceptionPage(); 67 | } 68 | else 69 | { 70 | app.UseExceptionHandler("/Error"); 71 | // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 72 | app.UseHsts(); 73 | } 74 | 75 | app.UseHttpsRedirection(); 76 | app.UseStaticFiles(); 77 | 78 | if (!env.IsDevelopment()) 79 | { 80 | app.UseSpaStaticFiles(); 81 | } 82 | app.UseRouting(); 83 | 84 | app.UseAuthentication(); 85 | app.UseAuthorization(); 86 | 87 | app.UseEndpoints(endpoints => 88 | { 89 | endpoints.MapControllerRoute( 90 | name: "default", 91 | pattern: "{controller}/{action=Index}/{id?}"); 92 | }); 93 | 94 | app.UseSpa(spa => 95 | { 96 | // To learn more about options for serving an Angular SPA from ASP.NET Core, 97 | // see https://go.microsoft.com/fwlink/?linkid=864501 98 | 99 | spa.Options.SourcePath = "ClientApp"; 100 | 101 | if (env.IsDevelopment()) 102 | { 103 | spa.UseAngularCliServer(npmScript: "start"); 104 | } 105 | }); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /ngWithJwt/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ngWithJwt/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "Jwt": { 8 | // The HmacSha256 encryption algorithm requires a key size minimum 32 bits. 9 | "SecretKey": "KqcL7s998JrfFHRA", 10 | "Issuer": "https://localhost:5001/", 11 | "Audience": "https://localhost:5001/" 12 | }, 13 | "AllowedHosts": "*" 14 | } 15 | -------------------------------------------------------------------------------- /ngWithJwt/ngWithJwt.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | true 6 | Latest 7 | false 8 | ClientApp\ 9 | $(DefaultItemExcludes);$(SpaRoot)node_modules\** 10 | 11 | 12 | false 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 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | %(DistFiles.Identity) 49 | PreserveNewest 50 | true 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /ngWithJwt/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitSharma-007/jwt-authentication-authorization-angular-aspnetcore/9ac1a641225b86f27fa80956ec94aa23fc3ca761/ngWithJwt/wwwroot/favicon.ico --------------------------------------------------------------------------------