├── README.md └── src ├── azure-ad-setup ├── add-client-pw.cmd ├── client.cmd ├── manifest.json ├── manifest2.json ├── notes.txt ├── server.cmd └── update-client.cmd ├── client └── spa-app │ ├── .bowerrc │ ├── .editorconfig │ ├── .gitignore │ ├── README.md │ ├── angular.json │ ├── bower.json │ ├── e2e │ ├── src │ │ ├── app.e2e-spec.ts │ │ └── app.po.ts │ └── tsconfig.e2e.json │ ├── package-lock.json │ ├── package.json │ ├── src │ ├── app │ │ ├── about │ │ │ ├── about.module.ts │ │ │ ├── about.routing.ts │ │ │ └── components │ │ │ │ └── home │ │ │ │ ├── home.component.css │ │ │ │ ├── home.component.html │ │ │ │ ├── home.component.spec.ts │ │ │ │ └── home.component.ts │ │ ├── accessdenied │ │ │ ├── accessdenied.module.ts │ │ │ ├── accessdenied.routing.ts │ │ │ └── components │ │ │ │ └── home │ │ │ │ ├── home.component.css │ │ │ │ ├── home.component.html │ │ │ │ ├── home.component.spec.ts │ │ │ │ └── home.component.ts │ │ ├── app-routing.module.ts │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.config.ts │ │ ├── app.module.ts │ │ ├── common │ │ │ └── basehttp.service.ts │ │ ├── core │ │ │ ├── components │ │ │ │ └── nav │ │ │ │ │ ├── nav.component.css │ │ │ │ │ ├── nav.component.html │ │ │ │ │ ├── nav.component.spec.ts │ │ │ │ │ └── nav.component.ts │ │ │ └── core.module.ts │ │ ├── frameredirect │ │ │ ├── components │ │ │ │ └── home │ │ │ │ │ ├── home.component.css │ │ │ │ │ ├── home.component.html │ │ │ │ │ ├── home.component.spec.ts │ │ │ │ │ └── home.component.ts │ │ │ ├── frameredirect.module.ts │ │ │ └── frameredirect.routing.ts │ │ ├── home │ │ │ ├── components │ │ │ │ └── home │ │ │ │ │ ├── home.component.css │ │ │ │ │ ├── home.component.html │ │ │ │ │ ├── home.component.spec.ts │ │ │ │ │ └── home.component.ts │ │ │ ├── home.module.ts │ │ │ └── home.routing.ts │ │ ├── shared │ │ │ ├── guards │ │ │ │ └── adal-access.guard.ts │ │ │ ├── services │ │ │ │ ├── adal-config.service.ts │ │ │ │ ├── adal.service.ts │ │ │ │ └── auth-interceptor.ts │ │ │ └── shared.module.ts │ │ └── values │ │ │ ├── components │ │ │ └── home │ │ │ │ ├── home.component.css │ │ │ │ ├── home.component.html │ │ │ │ ├── home.component.spec.ts │ │ │ │ └── home.component.ts │ │ │ ├── services │ │ │ └── value.service.ts │ │ │ ├── values.module.ts │ │ │ └── values.routing.ts │ ├── assets │ │ └── .gitkeep │ ├── browserslist │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── karma.conf.js │ ├── main.ts │ ├── polyfills.ts │ ├── styles.css │ ├── test.ts │ ├── tsconfig.app.json │ ├── tsconfig.spec.json │ └── tslint.json │ ├── test.json │ ├── tsconfig.json │ └── tslint.json └── server ├── .gitignore ├── Controllers └── ValuesController.cs ├── Extensions ├── AuthenticationBuilderExtensions.cs └── AuthenticationBuilderExtensionsV2.cs ├── Logging └── MyJwtBearerEvents.cs ├── Models └── AzureAdOptions.cs ├── Program.cs ├── Properties └── launchSettings.json ├── ServiceApp.csproj ├── ServiceApp.sln ├── Startup.cs ├── appsettings.Development.json └── appsettings.json /README.md: -------------------------------------------------------------------------------- 1 | ## Angular4+ with ADAL.js 2 | 3 | A simple starter project showing how to use [ADAL](https://github.com/AzureAD/azure-activedirectory-library-for-js/) with Angular4+ 4 | 5 | 6 | ### Client-App 7 | - Clone [this](https://github.com/vsaroopchand/angular-adal-sample) repository 8 | - Run `npm install` to install dependencies 9 | - Run `bower install` to install Bootstrap 3.3.7 and JQuery 10 | - Register your applications (https://docs.microsoft.com/en-us/azure/active-directory/active-directory-app-registration) 11 | - Update app.module.ts with your Tenant and ClientIDs 12 | - Run `npm start` to run the application 13 | - Open browser to [`http://localhost:4200`](http://localhost:4200) 14 | 15 | ### Server-App 16 | - Update appsettings.json with your Tenant and ClientID for Server-App 17 | - Run dotnet build && dotnet run 18 | - Update Client-App's app.module.ts, change apiEndpoint to reflect Server-App URI 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/azure-ad-setup/add-client-pw.cmd: -------------------------------------------------------------------------------- 1 | az ad app credential reset --id 6737e1a8-990b-4816-a2a6-95eca7fa9d79 --append --credential-description secretkey --password LetMeIn101 --years 2 -------------------------------------------------------------------------------- /src/azure-ad-setup/client.cmd: -------------------------------------------------------------------------------- 1 | az ad app create --display-name WebApp-OpenIDConnect-DotNet2 2 | --key-type Password 3 | --native-app false 4 | --password LetMeIn101 5 | --oauth2-allow-implicit-flow true 6 | --identifier-uris https://localhost:5000 7 | --homepage https://localhost:5000/signin-oidc 8 | --reply-urls https://localhost:4200/frameredirect http://localhost:4200/frameredirect 9 | --required-resource-accesses @manifest2.json -------------------------------------------------------------------------------- /src/azure-ad-setup/manifest.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "allowedMemberTypes": [ 3 | "User" 4 | ], 5 | "displayName": "Admin", 6 | "id": "c20e145e-5459-4a6c-a074-b942bbd4cfe1", 7 | "isEnabled": true, 8 | "description": "Administrators can manage ... ", 9 | "value": "Admin" 10 | }, 11 | { 12 | "allowedMemberTypes": [ 13 | "User" 14 | ], 15 | "displayName": "Creator", 16 | "id": "1b4f816e-5eaf-48b9-8613-7923830595ad", 17 | "isEnabled": true, 18 | "description": "Creators can create ... ", 19 | "value": "Creator" 20 | }] -------------------------------------------------------------------------------- /src/azure-ad-setup/manifest2.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "resourceAppId": "f8f1e8d3-dfd1-400f-93b6-30b7404d2c9a", 4 | "resourceAccess": [ 5 | { 6 | "id": "4da72b0f-1f95-4d53-8b8d-ed070fd881cf", 7 | "type": "Scope" 8 | } 9 | ] 10 | }, 11 | { 12 | "resourceAppId": "00000003-0000-0000-c000-000000000000", 13 | "resourceAccess": [ 14 | { 15 | "id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d", 16 | "type": "Scope" 17 | } 18 | ] 19 | } 20 | ] -------------------------------------------------------------------------------- /src/azure-ad-setup/notes.txt: -------------------------------------------------------------------------------- 1 | Step1: Create the server application 2 | az ad app create --display-name WebServer-OpenIDConnect-DotNet 3 | --key-type Password 4 | --native-app false 5 | --password LetMeIn101 6 | --oauth2-allow-implicit-flow true 7 | --identifier-uris https://localhost:5001 8 | --app-roles @manifest.json 9 | 10 | Step2: Create Service Principal for Application (Optional) 11 | az ad sp create --id [REPLACE WITH CLIENTID FROM STEP 1] 12 | [--subscription] 13 | 14 | Step3: Create Client application 15 | az ad app create --display-name WebApp-OpenIDConnect-DotNet 16 | --key-type Password 17 | --native-app false 18 | --password LetMeIn101 19 | --oauth2-allow-implicit-flow true 20 | --identifier-uris https://localhost:4200 21 | --homepage https://localhost:4200/home 22 | --reply-urls https://localhost:4200/frameredirect http://localhost:4200/frameredirect 23 | --required-resource-accesses @manifest2.json 24 | 25 | Step4: Convert Client App to SP (Optional) 26 | az ad sp create --id [REPLACE WITH CLIENTID FROM STEP 3] 27 | 28 | Step5: Update the Client Apps --required-resource-accesses 29 | az ad app update --id [REPLACE WITH CLIENTID FROM STEP 3] --required-resource-accesses @manifest2.json 30 | 31 | Step6: Create a Client Secret for Client App (Optional, needed for Client Credentials Flow) 32 | az ad app credential reset --id [REPLACE WITH CLIENTID FROM STEP 3] --append --credential-description secretkey --password LetMeIn101 --years 2 33 | 34 | Step7: Add Secret 35 | az ad app credential reset 36 | --id [REPLACE WITH CLIENTID FROM STEP 3] 37 | --append 38 | --credential-description secretkey 39 | --password LetMeIn101 40 | --years 2 41 | 42 | Step 8: Grant accesses 43 | az ad app permission grant --id [REPLACE WITH CLIENTID FROM STEP 3] --api [REPLACE WITH CLIENTID FROM STEP 1] 44 | 45 | Manual Edits: 46 | For some reason, the client app settings didn't stick. I had to manually add the redirect url and oauth2AllowImplicitFlow to manifest 47 | "replyUrls": [ 48 | "http://localhost:4200/frameredirect", 49 | "https://localhost:4200/frameredirect" 50 | ], 51 | 52 | and 53 | 54 | "oauth2AllowImplicitFlow": true, 55 | 56 | 57 | Additional Info: 58 | // See list of permissions on a client app 59 | az ad app permission list --id [REPLACE WITH CLIENTID] 60 | 61 | // Adding Delegated permissions creates the following in manifest 62 | "requiredResourceAccess": [ 63 | { 64 | "resourceAppId": "f8f1e8d3-dfd1-400f-93b6-30b7404d2c9a", <- This is the AppID 65 | "resourceAccess": [ 66 | { 67 | "id": "4da72b0f-1f95-4d53-8b8d-ed070fd881cf", <- This is the OAuth2 Permissions 68 | "type": "Scope" 69 | } 70 | ] 71 | } 72 | ], -------------------------------------------------------------------------------- /src/azure-ad-setup/server.cmd: -------------------------------------------------------------------------------- 1 | az ad app create --display-name WebServer-OpenIDConnect-DotNet2 2 | --key-type Password 3 | --native-app false 4 | --password LetMeIn101 5 | --oauth2-allow-implicit-flow true 6 | --identifier-uris https://localhost:44351 7 | --app-roles @manifest.json -------------------------------------------------------------------------------- /src/azure-ad-setup/update-client.cmd: -------------------------------------------------------------------------------- 1 | az ad app update --id 6737e1a8-990b-4816-a2a6-95eca7fa9d79 --required-resource-accesses @manifest2.json -------------------------------------------------------------------------------- /src/client/spa-app/.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "src/public" 3 | } 4 | -------------------------------------------------------------------------------- /src/client/spa-app/.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 | -------------------------------------------------------------------------------- /src/client/spa-app/.gitignore: -------------------------------------------------------------------------------- 1 | obj 2 | bin 3 | _ReSharper* 4 | *.csproj.user 5 | *.ReSharper.user 6 | *.ReSharper 7 | *.user 8 | *.suo 9 | *.cache 10 | ~$* 11 | *~ 12 | *.log 13 | packages 14 | *.ncrunch* 15 | /pkg 16 | /dist 17 | 18 | 19 | # dependencies 20 | /node_modules 21 | 22 | 23 | # IDEs and editors 24 | /.idea 25 | .project 26 | .classpath 27 | .c9/ 28 | *.launch 29 | .settings/ 30 | *.sublime-workspace 31 | 32 | # IDE - VSCode 33 | .vscode/* 34 | !.vscode/settings.json 35 | !.vscode/tasks.json 36 | !.vscode/launch.json 37 | !.vscode/extensions.json 38 | 39 | # compiled output 40 | /tmp 41 | /out-tsc 42 | /resources 43 | /aot 44 | /src/public 45 | 46 | # e2e 47 | /e2e/*.js 48 | /e2e/*.map 49 | 50 | # System Files 51 | .DS_Store 52 | Thumbs.db 53 | /.vs/config 54 | /Dashboard/node_modules 55 | /Dashboard/src/public 56 | /SfPerfTest/pkg/Debug 57 | /Greeter 58 | /protos 59 | /generate_protos.bat 60 | /csharp 61 | /Service2/PackagRoot/Config/Settings.xml 62 | -------------------------------------------------------------------------------- /src/client/spa-app/README.md: -------------------------------------------------------------------------------- 1 | # Help 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.0.0-rc.1. 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 | -------------------------------------------------------------------------------- /src/client/spa-app/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "help": { 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 | "outputPath": "dist/help", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "src/tsconfig.app.json", 21 | "assets": [ 22 | "src/favicon.ico", 23 | "src/assets" 24 | ], 25 | "styles": [ 26 | "src/public/bootstrap/dist/css/bootstrap.min.css", 27 | "src/styles.css" 28 | ], 29 | "scripts": [ 30 | "src/public/jquery/dist/jquery.min.js", 31 | "src/public/bootstrap/dist/js/bootstrap.min.js", 32 | "./node_modules/adal-angular/dist/adal.min.js" 33 | ] 34 | }, 35 | "configurations": { 36 | "production": { 37 | "fileReplacements": [ 38 | { 39 | "replace": "src/environments/environment.ts", 40 | "with": "src/environments/environment.prod.ts" 41 | } 42 | ], 43 | "optimization": true, 44 | "outputHashing": "all", 45 | "sourceMap": false, 46 | "extractCss": true, 47 | "namedChunks": false, 48 | "aot": true, 49 | "extractLicenses": true, 50 | "vendorChunk": false, 51 | "buildOptimizer": true, 52 | "budgets": [ 53 | { 54 | "type": "initial", 55 | "maximumWarning": "2mb", 56 | "maximumError": "5mb" 57 | } 58 | ] 59 | } 60 | } 61 | }, 62 | "serve": { 63 | "builder": "@angular-devkit/build-angular:dev-server", 64 | "options": { 65 | "browserTarget": "help:build" 66 | }, 67 | "configurations": { 68 | "production": { 69 | "browserTarget": "help:build:production" 70 | } 71 | } 72 | }, 73 | "extract-i18n": { 74 | "builder": "@angular-devkit/build-angular:extract-i18n", 75 | "options": { 76 | "browserTarget": "help: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": [ 87 | "src/styles.css" 88 | ], 89 | "scripts": [], 90 | "assets": [ 91 | "src/favicon.ico", 92 | "src/assets" 93 | ] 94 | } 95 | }, 96 | "lint": { 97 | "builder": "@angular-devkit/build-angular:tslint", 98 | "options": { 99 | "tsConfig": [ 100 | "src/tsconfig.app.json", 101 | "src/tsconfig.spec.json" 102 | ], 103 | "exclude": [ 104 | "**/node_modules/**" 105 | ] 106 | } 107 | } 108 | } 109 | }, 110 | "help-e2e": { 111 | "root": "e2e/", 112 | "projectType": "application", 113 | "prefix": "", 114 | "architect": { 115 | "e2e": { 116 | "builder": "@angular-devkit/build-angular:protractor", 117 | "options": { 118 | "protractorConfig": "e2e/protractor.conf.js", 119 | "devServerTarget": "help:serve" 120 | }, 121 | "configurations": { 122 | "production": { 123 | "devServerTarget": "help:serve:production" 124 | } 125 | } 126 | }, 127 | "lint": { 128 | "builder": "@angular-devkit/build-angular:tslint", 129 | "options": { 130 | "tsConfig": "e2e/tsconfig.e2e.json", 131 | "exclude": [ 132 | "**/node_modules/**" 133 | ] 134 | } 135 | } 136 | } 137 | } 138 | }, 139 | "defaultProject": "help" 140 | } -------------------------------------------------------------------------------- /src/client/spa-app/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client-app", 3 | "description": "angular/adal sample", 4 | "main": "", 5 | "authors": [ 6 | "Vishal Saroopchand " 7 | ], 8 | "license": "MIT", 9 | "keywords": [ 10 | "adal", 11 | "angular" 12 | ], 13 | "homepage": "https://github.com/vsaroopchand/adal-samples", 14 | "ignore": [ 15 | "**/.*", 16 | "node_modules", 17 | "bower_components", 18 | "src/public", 19 | "test", 20 | "tests" 21 | ], 22 | "dependencies": { 23 | "bootstrap": "~3.3.7" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/client/spa-app/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('workspace-project 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.getParagraphText()).toEqual('Welcome to help!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | } -------------------------------------------------------------------------------- /src/client/spa-app/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adal-app", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~7.0.0-rc.0", 15 | "@angular/common": "~7.0.0-rc.0", 16 | "@angular/compiler": "~7.0.0-rc.0", 17 | "@angular/core": "~7.0.0-rc.0", 18 | "@angular/forms": "~7.0.0-rc.0", 19 | "@angular/http": "~7.0.0-rc.0", 20 | "@angular/platform-browser": "~7.0.0-rc.0", 21 | "@angular/platform-browser-dynamic": "~7.0.0-rc.0", 22 | "@angular/router": "~7.0.0-rc.0", 23 | "adal-angular": "^1.0.17", 24 | "core-js": "^2.5.4", 25 | "rxjs": "~6.3.3", 26 | "zone.js": "~0.8.26" 27 | }, 28 | "devDependencies": { 29 | "@angular-devkit/build-angular": "~0.9.0-rc.1", 30 | "@angular/cli": "~7.0.0-rc.1", 31 | "@angular/compiler-cli": "~7.0.0-rc.0", 32 | "@angular/language-service": "~7.0.0-rc.0", 33 | "@types/adal": "^1.0.29", 34 | "@types/jasmine": "~2.8.8", 35 | "@types/jasminewd2": "~2.0.3", 36 | "@types/node": "~8.9.4", 37 | "codelyzer": "~4.3.0", 38 | "jasmine-core": "~2.99.1", 39 | "jasmine-spec-reporter": "~4.2.1", 40 | "karma": "~3.0.0", 41 | "karma-chrome-launcher": "~2.2.0", 42 | "karma-coverage-istanbul-reporter": "~2.0.1", 43 | "karma-jasmine": "~1.1.2", 44 | "karma-jasmine-html-reporter": "^0.2.2", 45 | "protractor": "~5.4.0", 46 | "ts-node": "~7.0.0", 47 | "tslint": "~5.11.0", 48 | "typescript": "~3.1.1" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/about.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HomeComponent } from './components/home/home.component'; 4 | import { routes } from './about.routing'; 5 | 6 | @NgModule({ 7 | imports: [ 8 | CommonModule, 9 | routes 10 | ], 11 | declarations: [HomeComponent] 12 | }) 13 | export class AboutModule { } 14 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/about.routing.ts: -------------------------------------------------------------------------------- 1 | import { RouterModule } from "@angular/router"; 2 | import { HomeComponent } from "./components/home/home.component"; 3 | 4 | export const routes = RouterModule.forChild([{ 5 | path: 'about', 6 | component: HomeComponent 7 | }]) -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/components/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/about/components/home/home.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/components/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | About 3 |
4 | About us 5 |

6 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/components/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/about/components/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.css'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/accessdenied.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HomeComponent } from './components/home/home.component'; 4 | import { routes } from './accessdenied.routing'; 5 | 6 | @NgModule({ 7 | imports: [ 8 | CommonModule, 9 | routes 10 | ], 11 | declarations: [HomeComponent] 12 | }) 13 | export class AccessdeniedModule { } 14 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/accessdenied.routing.ts: -------------------------------------------------------------------------------- 1 | import { RouterModule } from "@angular/router"; 2 | import { HomeComponent } from "./components/home/home.component"; 3 | 4 | export const routes = RouterModule.forChild([ 5 | { 6 | path: 'accessdenied', 7 | component: HomeComponent 8 | } 9 | ]) -------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/components/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/accessdenied/components/home/home.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/components/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | Access Denied 3 |
4 | You must be signed-in to access this resource. 5 |

-------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/components/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/accessdenied/components/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.css'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | const routes: Routes = [ 5 | { path: '', redirectTo: 'home', pathMatch: 'full' } 6 | ]; 7 | 8 | @NgModule({ 9 | imports: [RouterModule.forRoot(routes)], 10 | exports: [RouterModule] 11 | }) 12 | export class AppRoutingModule { } 13 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/app.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
4 |
5 | 6 |
7 |
-------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | })); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.debugElement.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'help'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.debugElement.componentInstance; 26 | expect(app.title).toEqual('help'); 27 | }); 28 | 29 | it('should render title in a h1 tag', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.debugElement.nativeElement; 33 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to help!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, ViewEncapsulation, OnInit } from '@angular/core'; 2 | import { AdalService } from './shared/services/adal.service'; 3 | 4 | @Component({ 5 | selector: 'app-root', 6 | templateUrl: './app.component.html', 7 | styleUrls: ['./app.component.css'], 8 | encapsulation: ViewEncapsulation.None 9 | }) 10 | export class AppComponent implements OnInit { 11 | title = 'Azure AD Client'; 12 | 13 | constructor(private adalService: AdalService) { 14 | } 15 | 16 | ngOnInit(){ 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.config.ts: -------------------------------------------------------------------------------- 1 | import { InjectionToken } from '@angular/core'; 2 | 3 | export class AppConfig { 4 | apiEndpoint: string; 5 | clientId: string; 6 | resource: string; 7 | tenantId: string; 8 | redirectUri: string; 9 | } 10 | 11 | export let APP_CONFIG = new InjectionToken('app.config') -------------------------------------------------------------------------------- /src/client/spa-app/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { AppComponent } from './app.component'; 6 | import { APP_CONFIG } from './app.config'; 7 | 8 | import { CoreModule } from './core/core.module'; 9 | import { HomeModule } from './home/home.module'; 10 | import { AboutModule } from './about/about.module'; 11 | 12 | import { AccessdeniedModule } from './accessdenied/accessdenied.module'; 13 | import { FrameRedirectModule } from './frameredirect/frameredirect.module'; 14 | 15 | import { ValuesModule } from './values/values.module'; 16 | import { SharedModule } from './shared/shared.module'; 17 | 18 | 19 | @NgModule({ 20 | declarations: [ 21 | AppComponent 22 | ], 23 | imports: [ 24 | BrowserModule, 25 | AppRoutingModule, 26 | CoreModule, 27 | SharedModule, 28 | HomeModule, 29 | ValuesModule, 30 | AboutModule, 31 | AccessdeniedModule, 32 | FrameRedirectModule 33 | ], 34 | providers: [ 35 | { 36 | provide: APP_CONFIG, useValue: { 37 | apiEndpoint: 'https://localhost:44340', // WebAPI endpoint for Values 38 | clientId: '00000000-0000-0000-0000-000000000000', // ClientID from AAD Client-App 39 | tenantId: '00000000-0000-0000-0000-000000000000', // AAD TenantID 40 | resource: '00000000-0000-0000-0000-000000000000', // ClientID from AAD Server-App 41 | redirectUri: 'http://localhost:4200/frameredirect', // AAD Client-App's RedirectUri 42 | } 43 | } 44 | ], 45 | bootstrap: [AppComponent] 46 | }) 47 | export class AppModule {} 48 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/common/basehttp.service.ts: -------------------------------------------------------------------------------- 1 | import { Observable, throwError } from "rxjs"; 2 | import { tap } from 'rxjs/operators'; 3 | import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; 4 | 5 | export class BaseHttpService{ 6 | 7 | endpoint = ''; 8 | headers = new HttpHeaders({ 'Content-Type': 'application/json' }); 9 | 10 | constructor(private httpClient: HttpClient, private baseUrl: string, private controller: string) { 11 | this.endpoint = baseUrl + '/api/' + controller + '/'; 12 | } 13 | get(id: number): Observable | T { 14 | return this.httpClient.get(this.endpoint + '/' + id, { headers: this.headers }) 15 | .pipe( 16 | tap( // Log the result or error 17 | data => { 18 | // choose to log 19 | }, 20 | error => this.handleError(error) 21 | ) 22 | ); 23 | } 24 | 25 | getAll(): Observable | T[] { 26 | 27 | return this.httpClient.get(this.endpoint, { headers: this.headers }) 28 | .pipe( 29 | tap( // Log the result or error 30 | data => { 31 | // choose to log 32 | }, 33 | error => this.handleError(error) 34 | ) 35 | ); 36 | } 37 | 38 | put(item: T): Observable | T { 39 | return this.httpClient.put(this.endpoint + 'all', JSON.stringify(item), { headers: this.headers }) 40 | .pipe( 41 | tap( // Log the result or error 42 | data => { 43 | // choose to log 44 | }, 45 | error => this.handleError(error) 46 | ) 47 | ); 48 | } 49 | 50 | post(item: T): Observable | any { 51 | return this.httpClient.post(this.endpoint, JSON.stringify(item), { headers: this.headers }) 52 | .pipe( 53 | tap( // Log the result or error 54 | data => { 55 | // choose to log 56 | }, 57 | error => this.handleError(error) 58 | ) 59 | ); 60 | } 61 | 62 | delete(id: number): Observable | any { 63 | return this.httpClient.delete(this.endpoint + '/' + id, { headers: this.headers }) 64 | .pipe( 65 | tap( // Log the result or error 66 | data => { 67 | // choose to log 68 | }, 69 | error => this.handleError(error) 70 | ) 71 | ); 72 | } 73 | 74 | private handleError(error: HttpErrorResponse) { 75 | if (error.error instanceof ErrorEvent) { 76 | // A client-side or network error occurred. Handle it accordingly. 77 | console.error('An error occurred:', error.error.message); 78 | } else { 79 | // The backend returned an unsuccessful response code. 80 | // The response body may contain clues as to what went wrong, 81 | console.error( 82 | `Backend returned code ${error.status}, ` + 83 | `body was: ${error.error}`); 84 | } 85 | // return an observable with a user-facing error message 86 | return throwError( 87 | 'Something bad happened; please try again later.'); 88 | }; 89 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/core/components/nav/nav.component.css: -------------------------------------------------------------------------------- 1 | #user-name{ 2 | color: blue 3 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/core/components/nav/nav.component.html: -------------------------------------------------------------------------------- 1 |
2 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/core/components/nav/nav.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { NavComponent } from './nav.component'; 4 | 5 | describe('NavComponent', () => { 6 | let component: NavComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ NavComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(NavComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/core/components/nav/nav.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AdalService } from '../../../shared/services/adal.service'; 3 | 4 | @Component({ 5 | selector: '[app-nav]', 6 | templateUrl: './nav.component.html', 7 | styleUrls: ['./nav.component.css'] 8 | }) 9 | export class NavComponent implements OnInit { 10 | 11 | constructor(private adalService: AdalService) { } 12 | 13 | ngOnInit() { 14 | } 15 | 16 | signInOut(){ 17 | if (!this.adalService.isAuthenticated) { 18 | this.adalService.login(); 19 | } else { 20 | if (this.userName) { 21 | this.adalService.logout(); 22 | } 23 | } 24 | } 25 | 26 | get userName() { 27 | if (this.adalService.userInfo) { 28 | return this.adalService.userInfo.userName; 29 | } else { 30 | return null; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/core/core.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { NavComponent } from './components/nav/nav.component'; 4 | import { RouterModule } from '@angular/router'; 5 | 6 | @NgModule({ 7 | imports: [ 8 | CommonModule, 9 | RouterModule 10 | ], 11 | declarations: [NavComponent], 12 | exports: [NavComponent, RouterModule], 13 | }) 14 | export class CoreModule { } 15 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/components/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/frameredirect/components/home/home.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/components/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | home works! 3 |

4 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/components/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/components/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit, Inject } from '@angular/core'; 2 | import { AdalService } from '../../../shared/services/adal.service'; 3 | import { AppConfig, APP_CONFIG } from '../../../app.config'; 4 | import { Router } from '@angular/router'; 5 | 6 | @Component({ 7 | selector: 'app-home', 8 | templateUrl: './home.component.html', 9 | styleUrls: ['./home.component.css'] 10 | }) 11 | export class HomeComponent implements OnInit { 12 | constructor(private adalService: AdalService, @Inject(APP_CONFIG) private config: AppConfig, private router: Router) { } 13 | ngOnInit() { 14 | this.adalService.handleWindowCallback(); 15 | this.router.navigate(['home']); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/frameredirect.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HomeComponent } from './components/home/home.component'; 4 | import { SharedModule } from '../shared/shared.module'; 5 | import { handleRedirectRoutes } from './frameredirect.routing'; 6 | 7 | @NgModule({ 8 | imports: [ 9 | CommonModule, 10 | SharedModule, 11 | handleRedirectRoutes 12 | ], 13 | declarations: [HomeComponent] 14 | }) 15 | export class FrameRedirectModule { } 16 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/frameredirect/frameredirect.routing.ts: -------------------------------------------------------------------------------- 1 | import { RouterModule } from "@angular/router"; 2 | import { HomeComponent } from "./components/home/home.component"; 3 | 4 | export const handleRedirectRoutes = RouterModule.forChild([{ 5 | path: 'frameredirect', 6 | component: HomeComponent 7 | }]) -------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/components/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/home/components/home/home.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/components/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | Home 3 |
4 | Sample demonstrating ADAL.js and Angular 5 |

-------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/components/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/components/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.css'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/home.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HomeComponent } from './components/home/home.component'; 4 | import { routes } from './home.routing'; 5 | 6 | @NgModule({ 7 | imports: [ 8 | CommonModule, 9 | routes 10 | ], 11 | declarations: [HomeComponent] 12 | }) 13 | export class HomeModule { } 14 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/home/home.routing.ts: -------------------------------------------------------------------------------- 1 | import { RouterModule } from "@angular/router"; 2 | import { HomeComponent } from "./components/home/home.component"; 3 | 4 | export const routes = RouterModule.forChild([{ 5 | path: 'home', 6 | component: HomeComponent 7 | }]); -------------------------------------------------------------------------------- /src/client/spa-app/src/app/shared/guards/adal-access.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, NavigationExtras } from "@angular/router"; 3 | import { AdalService } from "../services/adal.service"; 4 | import { Observable } from "rxjs"; 5 | 6 | @Injectable() 7 | export class AdalAccessGuard implements CanActivate { 8 | constructor(private router: Router, private adalService: AdalService) {} 9 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean { 10 | 11 | let navigationExtras: NavigationExtras = { 12 | queryParams: { 'redirectUrl': route.url } 13 | }; 14 | 15 | if (!this.adalService.userInfo) { 16 | this.router.navigate(['accessdenied'], navigationExtras); 17 | } 18 | 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/shared/services/adal-config.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Inject } from "@angular/core"; 2 | import { APP_CONFIG, AppConfig } from "../../app.config"; 3 | 4 | @Injectable() 5 | export class AdalConfigService { 6 | 7 | constructor(@Inject(APP_CONFIG) private config: AppConfig) {} 8 | 9 | get adalSettings() { 10 | return { 11 | tenant: this.config.tenantId, 12 | clientId: this.config.clientId, 13 | redirectUri: this.config.redirectUri, 14 | postLogoutRedirectUri: window.location.origin + '/', 15 | navigateToLoginRequestUrl: true 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/shared/services/adal.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, Subscriber } from 'rxjs'; 3 | import { retry } from 'rxjs/operators'; 4 | import { AdalConfigService } from './adal-config.service'; 5 | import { adal } from 'adal-angular'; 6 | 7 | declare var AuthenticationContext: adal.AuthenticationContextStatic; 8 | let createAuthContextFn: adal.AuthenticationContextStatic = AuthenticationContext; 9 | 10 | @Injectable() 11 | export class AdalService { 12 | private context: adal.AuthenticationContext; 13 | constructor(private configService: AdalConfigService) { 14 | this.context = new createAuthContextFn(configService.adalSettings); 15 | } 16 | login() { 17 | this.context.login(); 18 | } 19 | logout() { 20 | this.context.logOut(); 21 | } 22 | get authContext() { 23 | return this.context; 24 | } 25 | handleWindowCallback() { 26 | this.context.handleWindowCallback(); 27 | } 28 | public get userInfo() { 29 | 30 | return this.context.getCachedUser(); 31 | } 32 | public get accessToken() { 33 | return this.context.getCachedToken(this.configService.adalSettings.clientId); 34 | } 35 | public get isAuthenticated() { 36 | return this.userInfo && this.accessToken; 37 | } 38 | 39 | public isCallback(hash: string) { 40 | return this.context.isCallback(hash); 41 | } 42 | 43 | public getLoginError() { 44 | return this.context.getLoginError(); 45 | } 46 | 47 | public getAccessToken(endpoint: string, callbacks: (message: string, token: string) => any) { 48 | 49 | return this.context.acquireToken(endpoint, callbacks); 50 | } 51 | 52 | public acquireTokenResilient(resource: string): Observable { 53 | return new Observable((subscriber: Subscriber) => 54 | this.context.acquireToken(resource, (message: string, token: string) => { 55 | if (token) { 56 | subscriber.next(token); 57 | } else { 58 | console.error(message) 59 | subscriber.error(message); 60 | } 61 | }) 62 | ).pipe(retry(3)); 63 | } 64 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/shared/services/auth-interceptor.ts: -------------------------------------------------------------------------------- 1 | import { HttpRequest, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http'; 2 | import { Injectable, Inject } from '@angular/core'; 3 | import { AdalService } from './adal.service'; 4 | import { mergeMap } from 'rxjs/internal/operators/mergeMap'; 5 | import { Observable } from 'rxjs'; 6 | import { APP_CONFIG, AppConfig } from '../../app.config'; 7 | 8 | @Injectable() 9 | export class AuthInterceptor implements HttpInterceptor { 10 | constructor(private adalService: AdalService, @Inject(APP_CONFIG) private config: AppConfig) {} 11 | intercept(req: HttpRequest, next: HttpHandler): 12 | Observable> { 13 | return this.adalService.acquireTokenResilient(this.config.resource) 14 | .pipe(mergeMap((token) => { 15 | if (token) { 16 | req = req.clone({ 17 | setHeaders: { 18 | Authorization: 'Bearer ' + token 19 | } 20 | }); 21 | } 22 | return next.handle(req); 23 | })); 24 | } 25 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/shared/shared.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { AdalConfigService } from './services/adal-config.service'; 4 | import { AdalAccessGuard } from './guards/adal-access.guard'; 5 | import { AdalService } from './services/adal.service'; 6 | import { HttpClientModule } from '@angular/common/http'; 7 | 8 | /* "Barrel" of Http Interceptors */ 9 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 10 | import { AuthInterceptor } from './services/auth-interceptor'; 11 | 12 | 13 | /** Http interceptor providers in outside-in order */ 14 | export const httpInterceptorProviders = [ 15 | { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }, 16 | ]; 17 | 18 | @NgModule({ 19 | imports: [ 20 | CommonModule, 21 | HttpClientModule 22 | ], 23 | declarations: [], 24 | providers: [AdalConfigService, AdalService, AdalAccessGuard, httpInterceptorProviders] 25 | }) 26 | export class SharedModule { } 27 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/components/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/app/values/components/home/home.component.css -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/components/home/home.component.html: -------------------------------------------------------------------------------- 1 |

2 | Values 3 |
4 | Here are the values from API 5 |

6 |
7 | {{values | async | json}} 8 |
-------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/components/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(HomeComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it('should create', () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/components/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ValueService } from '../../services/value.service'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | 11 | values : any = []; 12 | constructor(private valueService: ValueService) {} 13 | 14 | ngOnInit() { 15 | this.values = this.valueService.getAll(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/services/value.service.ts: -------------------------------------------------------------------------------- 1 | import { BaseHttpService } from "../../common/basehttp.service"; 2 | import { Injectable, Inject } from "@angular/core"; 3 | import { HttpClient } from "@angular/common/http"; 4 | import { APP_CONFIG, AppConfig } from "../../app.config"; 5 | 6 | @Injectable() 7 | export class ValueService extends BaseHttpService{ 8 | constructor(httpClient: HttpClient, @Inject(APP_CONFIG) config: AppConfig) { 9 | super(httpClient, config.apiEndpoint, 'values'); 10 | } 11 | } -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/values.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { CommonModule } from '@angular/common'; 3 | import { HomeComponent } from './components/home/home.component'; 4 | import { routes } from './values.routing'; 5 | import { ValueService } from './services/value.service'; 6 | 7 | @NgModule({ 8 | imports: [ 9 | CommonModule, 10 | routes 11 | ], 12 | declarations: [HomeComponent], 13 | providers: [ValueService] 14 | }) 15 | export class ValuesModule { } 16 | -------------------------------------------------------------------------------- /src/client/spa-app/src/app/values/values.routing.ts: -------------------------------------------------------------------------------- 1 | import { RouterModule } from "@angular/router"; 2 | import { HomeComponent } from "./components/home/home.component"; 3 | import { AdalAccessGuard } from "../shared/guards/adal-access.guard"; 4 | 5 | export const routes = RouterModule.forChild([ 6 | { 7 | path: 'values', 8 | component: HomeComponent, 9 | canActivate : [AdalAccessGuard] 10 | } 11 | ]) -------------------------------------------------------------------------------- /src/client/spa-app/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/client/spa-app/src/browserslist: -------------------------------------------------------------------------------- 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 | # 5 | # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed 6 | 7 | > 0.5% 8 | last 2 versions 9 | Firefox ESR 10 | not dead 11 | not IE 9-11 -------------------------------------------------------------------------------- /src/client/spa-app/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/client/spa-app/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsaroopchand/angular-adal-sample/f5b8acacba90ae280e85199101c75f50baab15db/src/client/spa-app/src/favicon.ico -------------------------------------------------------------------------------- /src/client/spa-app/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AAD Client-App 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | }; -------------------------------------------------------------------------------- /src/client/spa-app/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 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | 14 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/regexp'; 32 | // import 'core-js/es6/map'; 33 | // import 'core-js/es6/weak-map'; 34 | // import 'core-js/es6/set'; 35 | 36 | /** 37 | * If your app need to indexed by Google Search, your app require polyfills 'core-js/es6/array' 38 | * Google bot use ES5. 39 | * FYI: Googlebot uses a renderer following the similar spec to Chrome 41. 40 | * https://developers.google.com/search/docs/guides/rendering 41 | **/ 42 | // import 'core-js/es6/array'; 43 | 44 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 45 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 46 | 47 | /** IE10 and IE11 requires the following for the Reflect API. */ 48 | // import 'core-js/es6/reflect'; 49 | 50 | /** 51 | * Web Animations `@angular/platform-browser/animations` 52 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 53 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 54 | **/ 55 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 56 | 57 | /** 58 | * By default, zone.js will patch all possible macroTask and DomEvents 59 | * user can disable parts of macroTask/DomEvents patch by setting following flags 60 | */ 61 | 62 | // (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 63 | // (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 64 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 65 | 66 | /* 67 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 68 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 69 | */ 70 | // (window as any).__Zone_enable_cross_context_check = true; 71 | 72 | /*************************************************************************************************** 73 | * Zone JS is required by default for Angular itself. 74 | */ 75 | import 'zone.js/dist/zone'; // Included with Angular CLI. 76 | 77 | 78 | 79 | /*************************************************************************************************** 80 | * APPLICATION IMPORTS 81 | */ 82 | -------------------------------------------------------------------------------- /src/client/spa-app/src/styles.css: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/client/spa-app/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/dist/zone-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 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/client/spa-app/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | -------------------------------------------------------------------------------- /src/client/spa-app/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 | -------------------------------------------------------------------------------- /src/client/spa-app/test.json: -------------------------------------------------------------------------------- 1 | "appRoles": [ 2 | { 3 | "allowedMemberTypes": [ 4 | "User" 5 | ], 6 | "displayName": "Admin", 7 | "id": "d1c2ade8-98f8-45fd-aa4a-6d06b947c66f", 8 | "isEnabled": true, 9 | "description": "Admins have the ability to manage lookups and metadata", 10 | "value": "Admin" 11 | } 12 | ] -------------------------------------------------------------------------------- /src/client/spa-app/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "target": "es5", 13 | "typeRoots": [ 14 | "node_modules/@types" 15 | ], 16 | "lib": [ 17 | "es2018", 18 | "dom" 19 | ] 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/client/spa-app/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-redundant-jsdoc": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "unified-signatures": true, 111 | "variable-name": false, 112 | "whitespace": [ 113 | true, 114 | "check-branch", 115 | "check-decl", 116 | "check-operator", 117 | "check-separator", 118 | "check-type" 119 | ], 120 | "no-output-on-prefix": true, 121 | "use-input-property-decorator": true, 122 | "use-output-property-decorator": true, 123 | "use-host-property-decorator": true, 124 | "no-input-rename": true, 125 | "no-output-rename": true, 126 | "use-life-cycle-interface": true, 127 | "use-pipe-transform-interface": true, 128 | "component-class-suffix": true, 129 | "directive-class-suffix": true 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/server/.gitignore: -------------------------------------------------------------------------------- 1 | obj 2 | bin 3 | _ReSharper* 4 | *.csproj.user 5 | *.ReSharper.user 6 | *.ReSharper 7 | *.user 8 | *.suo 9 | *.cache 10 | ~$* 11 | *~ 12 | *.log 13 | packages 14 | *.ncrunch* 15 | /pkg 16 | /dist 17 | 18 | 19 | # dependencies 20 | /node_modules 21 | 22 | 23 | # IDEs and editors 24 | /.idea 25 | .project 26 | .classpath 27 | .c9/ 28 | *.launch 29 | .settings/ 30 | *.sublime-workspace 31 | .vs 32 | 33 | # IDE - VSCode 34 | .vscode/* 35 | !.vscode/settings.json 36 | !.vscode/tasks.json 37 | !.vscode/launch.json 38 | !.vscode/extensions.json 39 | 40 | # compiled output 41 | /tmp 42 | /out-tsc 43 | /resources 44 | /aot 45 | /src/public 46 | 47 | # e2e 48 | /e2e/*.js 49 | /e2e/*.map 50 | 51 | # System Files 52 | .DS_Store 53 | Thumbs.db 54 | /.vs/config 55 | /Dashboard/node_modules 56 | /Dashboard/src/public 57 | /SfPerfTest/pkg/Debug 58 | /Greeter 59 | /protos 60 | /generate_protos.bat 61 | /csharp 62 | /Service2/PackagRoot/Config/Settings.xml 63 | -------------------------------------------------------------------------------- /src/server/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.AspNetCore.Authorization; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | namespace ServiceApp.Controllers 6 | { 7 | [Route("api/[controller]")] 8 | [ApiController] 9 | [Authorize] 10 | public class ValuesController : ControllerBase 11 | { 12 | // GET api/values 13 | [HttpGet] 14 | public ActionResult> Get() 15 | { 16 | var userName = User?.Identity?.Name; 17 | return new string[] { "value1", "value2" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/server/Extensions/AuthenticationBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | using Microsoft.Extensions.Options; 6 | using ServiceApp.Logging; 7 | using ServiceApp.Models; 8 | using System; 9 | 10 | namespace ServiceApp.Extensions 11 | { 12 | /// 13 | /// ADAL JwtBearer configuration 14 | /// 15 | public static class AuthenticationBuilderExtensions 16 | { 17 | public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action configureOptions) 18 | { 19 | builder.Services.Configure(configureOptions); 20 | builder.Services.AddSingleton, ConfigureAzureOptions>(); 21 | builder.AddJwtBearer(); 22 | return builder; 23 | } 24 | 25 | private class ConfigureAzureOptions : IConfigureNamedOptions 26 | { 27 | private readonly AzureAdOptions _azureOptions; 28 | private readonly ILogger _logger; 29 | 30 | public ConfigureAzureOptions(IOptions azureOptions, ILoggerFactory loggerFactory) 31 | { 32 | _azureOptions = azureOptions.Value; 33 | _logger = loggerFactory.CreateLogger(); 34 | } 35 | 36 | public void Configure(string name, JwtBearerOptions options) 37 | { 38 | options.Audience = _azureOptions.ClientId; 39 | 40 | options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}"; 41 | 42 | options.Events = new MyJwtBearerEvents(_logger); 43 | } 44 | 45 | public void Configure(JwtBearerOptions options) 46 | { 47 | Configure(Options.DefaultName, options); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/server/Extensions/AuthenticationBuilderExtensionsV2.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Options; 5 | using Microsoft.IdentityModel.Tokens; 6 | using ServiceApp.Models; 7 | using System; 8 | 9 | namespace ServiceApp.Extensions 10 | { 11 | /// 12 | /// MSAL JwtBearer Configuration (v2) 13 | /// 14 | public static class AzureAdServiceCollectionExtensionsV2 15 | { 16 | 17 | public static AuthenticationBuilder AddAzureAdBearerV2(this AuthenticationBuilder builder, Action configureOptions) 18 | { 19 | builder.Services.Configure(configureOptions); 20 | builder.Services.AddSingleton, ConfigureAzureOptions>(); 21 | builder.AddJwtBearer(); 22 | return builder; 23 | } 24 | 25 | private class ConfigureAzureOptions : IConfigureNamedOptions 26 | { 27 | private readonly AzureAdOptions _azureOptions; 28 | 29 | public ConfigureAzureOptions(IOptions azureOptions) 30 | { 31 | _azureOptions = azureOptions.Value; 32 | } 33 | 34 | public void Configure(string name, JwtBearerOptions options) 35 | { 36 | options.Audience = _azureOptions.ClientId; 37 | options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}/v2.0/"; 38 | options.TokenValidationParameters.ValidateIssuer = true; 39 | options.TokenValidationParameters.IssuerValidator = ValidateIssuer; 40 | } 41 | 42 | private string ValidateIssuer(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters) 43 | { 44 | Uri issuerUri = new Uri(issuer); 45 | Uri knownIssuerUri = new Uri(_azureOptions.IssuerV2); 46 | 47 | if (knownIssuerUri.AbsolutePath.Equals(issuerUri.AbsolutePath, StringComparison.OrdinalIgnoreCase)) 48 | { 49 | return issuer; 50 | } 51 | else 52 | { 53 | throw new SecurityTokenInvalidIssuerException("Unknown issuer"); 54 | } 55 | } 56 | 57 | public void Configure(JwtBearerOptions options) 58 | { 59 | Configure(Options.DefaultName, options); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/server/Logging/MyJwtBearerEvents.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.Extensions.Logging; 3 | using System.Threading.Tasks; 4 | 5 | namespace ServiceApp.Logging 6 | { 7 | public class MyJwtBearerEvents : JwtBearerEvents 8 | { 9 | private readonly ILogger _logger; 10 | 11 | public MyJwtBearerEvents(ILogger logger) 12 | { 13 | _logger = logger; 14 | } 15 | 16 | public override Task AuthenticationFailed(AuthenticationFailedContext context) 17 | { 18 | _logger.LogError(context.Exception.Message); 19 | return base.AuthenticationFailed(context); 20 | } 21 | 22 | public override Task Challenge(JwtBearerChallengeContext context) 23 | { 24 | return base.Challenge(context); 25 | } 26 | public override Task MessageReceived(MessageReceivedContext context) 27 | { 28 | return base.MessageReceived(context); 29 | } 30 | 31 | /// 32 | /// This method contains the logic that validates the user's tenant and normalizes claims. 33 | /// 34 | /// The validated token context 35 | /// A task 36 | public override Task TokenValidated(TokenValidatedContext context) 37 | { 38 | return base.TokenValidated(context); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/server/Models/AzureAdOptions.cs: -------------------------------------------------------------------------------- 1 | namespace ServiceApp.Models 2 | { 3 | public class AzureAdOptions 4 | { 5 | public string ClientId { get; set; } 6 | public string ClientSecret { get; set; } 7 | public string Instance { get; set; } 8 | public string Domain { get; set; } 9 | public string TenantId { get; set; } 10 | 11 | public string Authority 12 | { 13 | get 14 | { 15 | return $"{Instance}{TenantId}"; 16 | } 17 | } 18 | 19 | public string AuthorityV2 20 | { 21 | get 22 | { 23 | return $"https://login.microsoftonline.com/{this.TenantId}/"; 24 | } 25 | } 26 | 27 | public string IssuerV2 28 | { 29 | get 30 | { 31 | return $"https://sts.windows.net/{this.TenantId}/"; 32 | } 33 | } 34 | } 35 | public class AzureAdOptionsExtended : AzureAdOptions 36 | { 37 | public string CallbackPath { get; set; } 38 | 39 | 40 | public string ResourceId { get; set; } 41 | public string ServiceAddress { get; set; } 42 | 43 | public static AzureAdOptionsExtended Settings { set; get; } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/server/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace ServiceApp 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseStartup(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/server/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:50001", 8 | "sslPort": 44340 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/values", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "ServiceApp": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "api/values", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/server/ServiceApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/server/ServiceApp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27703.2042 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServiceApp", "ServiceApp.csproj", "{4C68976B-7DBF-40D0-9C57-E6C31BF17E03}" 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 | {4C68976B-7DBF-40D0-9C57-E6C31BF17E03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {4C68976B-7DBF-40D0-9C57-E6C31BF17E03}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {4C68976B-7DBF-40D0-9C57-E6C31BF17E03}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {4C68976B-7DBF-40D0-9C57-E6C31BF17E03}.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 = {6497EEBF-FE7F-4D70-BC20-22128D0D2A0B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/server/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.AspNetCore.Mvc; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using ServiceApp.Extensions; 8 | 9 | namespace ServiceApp 10 | { 11 | public class Startup 12 | { 13 | public Startup(IConfiguration configuration) 14 | { 15 | Configuration = configuration; 16 | } 17 | 18 | public IConfiguration Configuration { get; } 19 | 20 | // This method gets called by the runtime. Use this method to add services to the container. 21 | public void ConfigureServices(IServiceCollection services) 22 | { 23 | services.AddAuthentication(sharedOptions => 24 | { 25 | sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 26 | }) 27 | // for MSAL (V2) 28 | //.AddAzureAdBearerV2(options => Configuration.Bind("AzureAd", options)); 29 | // for ADAL (V1) 30 | .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options)); 31 | 32 | services.AddLogging(); 33 | services.AddCors(setup => 34 | { 35 | setup.DefaultPolicyName = "open"; 36 | setup.AddDefaultPolicy(p => { 37 | p.AllowAnyHeader(); 38 | p.AllowAnyMethod(); 39 | p.AllowAnyOrigin(); 40 | p.AllowCredentials(); 41 | }); 42 | }); 43 | 44 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 45 | } 46 | 47 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 48 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 49 | { 50 | if (env.IsDevelopment()) 51 | { 52 | app.UseDeveloperExceptionPage(); 53 | } 54 | else 55 | { 56 | app.UseHsts(); 57 | } 58 | 59 | app.UseCors("open"); 60 | app.UseHttpsRedirection(); 61 | app.UseAuthentication(); 62 | app.UseMvc(); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/server/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/server/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "AzureAd": { 3 | "Instance": "https://login.microsoftonline.com/", 4 | "Domain": "contoso.onmicrosoft.com", // Your AAD Domain 5 | "TenantId": "00000000-0000-0000-0000-000000000000", // Your AAD TenantID 6 | "ClientId": "00000000-0000-0000-0000-000000000000" // Server-APP ClientID 7 | }, 8 | "Logging": { 9 | "LogLevel": { 10 | "Default": "Warning" 11 | } 12 | }, 13 | "AllowedHosts": "*" 14 | } 15 | --------------------------------------------------------------------------------