├── SPA_Angular_AspNet_WebApi_Rest ├── app │ ├── home-component │ │ ├── home.js │ │ ├── home.js.map │ │ ├── home.component.html │ │ ├── home.component.js.map │ │ ├── home.component.ts │ │ └── home.component.js │ ├── models │ │ ├── product.ts │ │ ├── user.ts │ │ ├── user.js.map │ │ ├── product.js.map │ │ ├── user.js │ │ └── product.js │ ├── directives │ │ └── alert-component │ │ │ ├── alert.component.html │ │ │ ├── alert.component.ts │ │ │ ├── alert.component.js.map │ │ │ └── alert.component.js │ ├── main.js.map │ ├── main.ts │ ├── app.component.ts │ ├── app.component.html │ ├── app.component.js.map │ ├── main.js │ ├── app-routing.js.map │ ├── app.routing.js.map │ ├── guards │ │ ├── auth.guard.js.map │ │ ├── auth.guard.ts │ │ └── auth.guard.js │ ├── app-routing.js │ ├── app.module.js.map │ ├── services │ │ ├── user.service.js.map │ │ ├── user.service.ts │ │ ├── product.service.js.map │ │ ├── alert.service.js.map │ │ ├── alert.service.ts │ │ ├── product.service.ts │ │ ├── authentication.service.js.map │ │ ├── user.service.js │ │ ├── authentication.service.ts │ │ ├── product.service.js │ │ ├── alert.service.js │ │ └── authentication.service.js │ ├── app.routing.ts │ ├── app.routing.js │ ├── register-component │ │ ├── register.component.js.map │ │ ├── register.component.ts │ │ ├── register.component.js │ │ └── register.component.html │ ├── app.component.js │ ├── login-component │ │ ├── login.component.js.map │ │ ├── login.component.ts │ │ ├── login.component.html │ │ └── login.component.js │ ├── app.module.ts │ └── app.module.js ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 ├── tsconfig.json ├── Content │ └── Site.css ├── typings.json ├── packages.config ├── Web.Debug.config ├── SPA_Angular_AspNet_WebApi_Rest.csproj.user ├── Web.config ├── Web.Release.config ├── Properties │ └── AssemblyInfo.cs ├── package.json ├── Index.html ├── systemjs.config.js └── SPA_Angular_AspNet_WebApi_Rest.csproj ├── .vs └── SPA_Angular_AspNet_WebApi_Rest │ ├── v14 │ └── .suo │ └── v15 │ └── .suo ├── OAuthAspNetWebApiRest.Api ├── Global.asax ├── App_Start │ ├── FilterConfig.cs │ ├── RouteConfig.cs │ ├── WebApiConfig.cs │ ├── SimpleInjectorWebApiInitializer.cs │ ├── Startup.Auth.cs │ └── CorsHandler.cs ├── Startup.cs ├── Controllers │ ├── ProductController.cs │ ├── BaseAuthApiController.cs │ └── AccountController.cs ├── Results │ └── ChallengeResult.cs ├── Models │ ├── AccountViewModels.cs │ └── AccountBindingModels.cs ├── Web.Debug.config ├── Web.Release.config ├── Global.asax.cs ├── Properties │ └── AssemblyInfo.cs ├── OAuthAspNetWebApiRest.Api.csproj.user ├── packages.config ├── Providers │ └── ApplicationOAuthProvider.cs ├── Web.config └── OAuthAspNetWebApiRest.Api.csproj ├── OAuthAspNetWebApiRest.Domain ├── Models │ ├── User.cs │ └── Product.cs ├── Contracts │ ├── Services │ │ ├── IProductService.cs │ │ └── IUserService.cs │ └── Repositories │ │ ├── IProductRepository.cs │ │ └── IUserRepository.cs ├── packages.config ├── Services │ ├── ProductService.cs │ └── UserService.cs ├── App.config ├── Properties │ └── AssemblyInfo.cs └── OAuthAspNetWebApiRest.Domain.csproj ├── OAuthAspNetWebApiRest.Data ├── OAuthAspNetWebApiRest.Data.csproj.user ├── AppUserStore.cs ├── AppDbContext.cs ├── Repositories │ ├── ProductRepository.cs │ └── UserRepository.cs ├── AppDbContextInitialize.cs ├── Migrations │ ├── Configuration.cs │ ├── 201705312114068_FirstMigration.Designer.cs │ ├── 201705312114068_FirstMigration.cs │ └── 201705312114068_FirstMigration.resx ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── App.config └── OAuthAspNetWebApiRest.Data.csproj ├── .gitignore ├── README.md └── SPA_Angular_AspNet_WebApi_Rest.sln /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.js: -------------------------------------------------------------------------------- 1 | //# sourceMappingURL=home.js.map -------------------------------------------------------------------------------- /.vs/SPA_Angular_AspNet_WebApi_Rest/v14/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/.vs/SPA_Angular_AspNet_WebApi_Rest/v14/.suo -------------------------------------------------------------------------------- /.vs/SPA_Angular_AspNet_WebApi_Rest/v15/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/.vs/SPA_Angular_AspNet_WebApi_Rest/v15/.suo -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/product.ts: -------------------------------------------------------------------------------- 1 | export class Product { 2 | id: number; 3 | name: string; 4 | quantity: number; 5 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="OAuthAspNetWebApiRest.Api.WebApiApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"home.js","sourceRoot":"","sources":["home.ts"],"names":[],"mappings":""} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/user.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | id: string; 3 | username: string; 4 | password: string; 5 | email: string; 6 | 7 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/user.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"user.js","sourceRoot":"","sources":["user.ts"],"names":[],"mappings":";;AAAA;IAAA;IAMA,CAAC;IAAD,WAAC;AAAD,CAAC,AAND,IAMC;AANY,oBAAI"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chasoliveira/SPA-Angular/master/SPA_Angular_AspNet_WebApi_Rest/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/product.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"product.js","sourceRoot":"","sources":["product.ts"],"names":[],"mappings":";;AAAA;IAAA;IAIA,CAAC;IAAD,cAAC;AAAD,CAAC,AAJD,IAIC;AAJY,0BAAO"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Models/User.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity.EntityFramework; 2 | 3 | namespace OAuthAspNetWebApiRest.Domain.Models 4 | { 5 | public class User: IdentityUser 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/directives/alert-component/alert.component.html: -------------------------------------------------------------------------------- 1 |
{{message.text}}
-------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/main.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":";;AAAA,8EAA2E;AAC3E,2CAAyC;AACzC,IAAM,QAAQ,GAAG,iDAAsB,EAAE,CAAC;AAC1C,QAAQ,CAAC,eAAe,CAAC,sBAAS,CAAC,CAAC"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/main.ts: -------------------------------------------------------------------------------- 1 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 2 | import { AppModule } from './app.module'; 3 | const platform = platformBrowserDynamic(); 4 | platform.bootstrapModule(AppModule); -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | moduleId: module.id, 5 | selector: 'spa-app', 6 | templateUrl: './app.component.html', 7 | }) 8 | export class AppComponent { 9 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/user.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var User = (function () { 4 | function User() { 5 | } 6 | return User; 7 | }()); 8 | exports.User = User; 9 | //# sourceMappingURL=user.js.map -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Models/Product.cs: -------------------------------------------------------------------------------- 1 | namespace OAuthAspNetWebApiRest.Domain.Models 2 | { 3 | public class Product 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | public decimal Quantity { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/OAuthAspNetWebApiRest.Data.csproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ShowAllFiles 5 | 6 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/models/product.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var Product = (function () { 4 | function Product() { 5 | } 6 | return Product; 7 | }()); 8 | exports.Product = Product; 9 | //# sourceMappingURL=product.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 |
3 |
4 |
5 | 6 | 7 |
8 |
9 |
10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | packages 2 | OAuthAspNetWebApiRest.Api/bin 3 | OAuthAspNetWebApiRest.Api/obj 4 | OAuthAspNetWebApiRest.Data/bin 5 | OAuthAspNetWebApiRest.Data/obj 6 | OAuthAspNetWebApiRest.Domain/bin 7 | OAuthAspNetWebApiRest.Domain/obj 8 | 9 | SPA_Angular_AspNet_WebApi_Rest/bin 10 | SPA_Angular_AspNet_WebApi_Rest/obj 11 | SPA_Angular_AspNet_WebApi_Rest/node_modules -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Contracts/Services/IProductService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using OAuthAspNetWebApiRest.Domain.Models; 4 | 5 | namespace OAuthAspNetWebApiRest.Domain.Contracts.Services 6 | { 7 | public interface IProductService 8 | { 9 | Task> All(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/AppUserStore.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity.EntityFramework; 2 | using OAuthAspNetWebApiRest.Domain.Models; 3 | 4 | namespace OAuthAspNetWebApiRest.Data 5 | { 6 | public class AppUserStore: UserStore 7 | { 8 | public AppUserStore(AppDbContext context):base(context) 9 | { 10 | 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.component.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"app.component.js","sourceRoot":"","sources":["app.component.ts"],"names":[],"mappings":";;;;;;;;AAAA,sCAA0C;AAO1C,IAAa,YAAY;IAAzB;IACA,CAAC;IAAD,mBAAC;AAAD,CAAC,AADD,IACC;AADY,YAAY;IALxB,gBAAS,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,EAAE;QACnB,QAAQ,EAAE,SAAS;QACnB,WAAW,EAAE,sBAAsB;KACtC,CAAC;GACW,YAAY,CACxB;AADY,oCAAY"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace OAuthAspNetWebApiRest.Api 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Contracts/Repositories/IProductRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using OAuthAspNetWebApiRest.Domain.Models; 4 | 5 | namespace OAuthAspNetWebApiRest.Domain.Contracts.Repositories 6 | { 7 | public interface IProductRepository 8 | { 9 | Task> All(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/main.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var platform_browser_dynamic_1 = require("@angular/platform-browser-dynamic"); 4 | var app_module_1 = require("./app.module"); 5 | var platform = platform_browser_dynamic_1.platformBrowserDynamic(); 6 | platform.bootstrapModule(app_module_1.AppModule); 7 | //# sourceMappingURL=main.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "moduleResolution": "node", 6 | "sourceMap": true, 7 | "emitDecoratorMetadata": true, 8 | "experimentalDecorators": true, 9 | "lib": [ "es2015", "dom" ], 10 | "noImplicitAny": true, 11 | "suppressImplicitAnyIndexErrors": true 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Set width on the form input elements since they're 100% wide by default */ 13 | input, 14 | select, 15 | textarea { 16 | max-width: 280px; 17 | } 18 | 19 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Owin; 5 | using Owin; 6 | 7 | [assembly: OwinStartup(typeof(OAuthAspNetWebApiRest.Api.Startup))] 8 | 9 | namespace OAuthAspNetWebApiRest.Api 10 | { 11 | public partial class Startup 12 | { 13 | public void Configuration(IAppBuilder app) 14 | { 15 | ConfigureAuth(app); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spa_angular_aspnet_webapi", 3 | "dependencies": {}, 4 | "globalDependencies": { 5 | "bootstrap": "registry:dt/bootstrap#3.3.5+20160726204056", 6 | "core-js": "registry:dt/core-js#0.0.0+20160725163759", 7 | "jasmine": "registry:dt/jasmine#2.2.0+20160621224255", 8 | "jquery": "registry:dt/jquery#1.10.0+20170123093700", 9 | "node": "registry:dt/node#6.0.0+20160909174046" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app-routing.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"app-routing.js","sourceRoot":"","sources":["app-routing.ts"],"names":[],"mappings":";AAAA,uBAAqC,iBAAiB,CAAC,CAAA;AAEvD,8BAA6B,iBAAiB,CAAC,CAAA;AAC/C,kCAAiC,uCAAuC,CAAC,CAAA;AAEzE,IAAM,UAAU,GAAW;IACvB;QACI,IAAI,EAAE,EAAE;QACR,UAAU,EAAE,GAAG;QACf,SAAS,EAAC,MAAM;KACnB;IACD;QACI,IAAI,EAAE,SAAS;QACf,SAAS,EAAE,oCAAgB;KAC9B;CACJ,CAAC;AAEW,eAAO,GAAG,qBAAY,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC3C,2BAAmB,GAAG,CAAC,4BAAY,EAAE,oCAAgB,CAAC,CAAC"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |

olá {{currentUser.userName}}!

3 |

Você está logado!!

4 |

Veja nossos Produtos:

5 |

Carregando...

6 |
    7 |
  • 8 | {{p.Name}} ({{p.Quantity | number : '1.2-2'}}) 9 |
  • 10 |
11 |

Logout

12 |
-------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/directives/alert-component/alert.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | import { AlertService } from '../../services/alert.service'; 4 | 5 | @Component({ 6 | moduleId: module.id, 7 | selector: 'alert', 8 | templateUrl: 'alert.component.html' 9 | }) 10 | 11 | export class AlertComponent { 12 | message: any; 13 | 14 | constructor(private alertService: AlertService) { } 15 | 16 | ngOnInit() { 17 | this.alertService.getMessage().subscribe(message => { this.message = message; }); 18 | } 19 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.routing.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"app.routing.js","sourceRoot":"","sources":["app.routing.ts"],"names":[],"mappings":";;AAAA,0CAAuD;AAIvD,kEAAgE;AAChE,qEAAmE;AACnE,8EAA4E;AAE5E,kDAAgD;AAEhD,IAAM,SAAS,GAAW;IACtB;QACI,IAAI,EAAE,EAAE;QACR,UAAU,EAAE,GAAG;QACf,SAAS,EAAE,MAAM;KACpB;IACD,EAAE,IAAI,EAAE,EAAE,EAAE,SAAS,EAAE,8BAAa,EAAE,WAAW,EAAE,CAAC,sBAAS,CAAC,EAAE;IAChE,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,gCAAc,EAAE;IAC5C,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,sCAAiB,EAAE;IAElD,6BAA6B;IAC7B,EAAE,IAAI,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,EAAE;CACjC,CAAC;AAEW,QAAA,OAAO,GAAwB,qBAAY,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/directives/alert-component/alert.component.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"alert.component.js","sourceRoot":"","sources":["alert.component.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAAkD;AAElD,8DAA4D;AAQ5D,IAAa,cAAc;IAGvB,wBAAoB,YAA0B;QAA1B,iBAAY,GAAZ,YAAY,CAAc;IAAI,CAAC;IAEnD,iCAAQ,GAAR;QAAA,iBAEC;QADG,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE,CAAC,SAAS,CAAC,UAAA,OAAO,IAAM,KAAI,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IACrF,CAAC;IACL,qBAAC;AAAD,CAAC,AARD,IAQC;AARY,cAAc;IAN1B,gBAAS,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,EAAE;QACnB,QAAQ,EAAE,OAAO;QACjB,WAAW,EAAE,sBAAsB;KACtC,CAAC;qCAKoC,4BAAY;GAHrC,cAAc,CAQ1B;AARY,wCAAc"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/AppDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity.EntityFramework; 2 | using OAuthAspNetWebApiRest.Domain.Models; 3 | using System.Data.Entity; 4 | 5 | namespace OAuthAspNetWebApiRest.Data 6 | { 7 | public class AppDbContext : IdentityDbContext 8 | { 9 | public AppDbContext() : base("DefaultConnection", throwIfV1Schema: false) 10 | { 11 | new AppDbContextInitialize(this); 12 | } 13 | 14 | public DbSet Products { get; set; } 15 | public static AppDbContext Create() 16 | { 17 | return new AppDbContext(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/guards/auth.guard.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"auth.guard.js","sourceRoot":"","sources":["auth.guard.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA2C;AAC3C,0CAAmG;AAGnG,IAAa,SAAS;IAElB,mBAAoB,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAI,CAAC;IAEvC,+BAAW,GAAX,UAAY,KAA6B,EAAE,KAA0B;QACjE,EAAE,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;YACtC,2BAA2B;YAC3B,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;QAED,8DAA8D;QAC9D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,WAAW,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAC5E,MAAM,CAAC,KAAK,CAAC;IACjB,CAAC;IACL,gBAAC;AAAD,CAAC,AAdD,IAcC;AAdY,SAAS;IADrB,iBAAU,EAAE;qCAGmB,eAAM;GAFzB,SAAS,CAcrB;AAdY,8BAAS"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app-routing.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var router_1 = require('@angular/router'); 3 | var app_component_1 = require('./app.component'); 4 | var product_component_1 = require('./product-component/product.component'); 5 | var appRouters = [ 6 | { 7 | path: '', 8 | redirectTo: '/', 9 | pathMatch: 'full' 10 | }, 11 | { 12 | path: 'product', 13 | component: product_component_1.ProductComponent 14 | } 15 | ]; 16 | exports.routing = router_1.RouterModule.forRoot(appRouters); 17 | exports.routertedComponents = [app_component_1.AppComponent, product_component_1.ProductComponent]; 18 | //# sourceMappingURL=app-routing.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.module.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"app.module.js","sourceRoot":"","sources":["app.module.ts"],"names":[],"mappings":";;;;;;;;AAAA,sCAAyC;AACzC,8DAA0D;AAC1D,sCAAwD;AACxD,wCAA6C;AAE7C,iDAA+C;AAE/C,6CAAwC;AAExC,8DAA4D;AAC5D,gFAA8E;AAC9E,kDAAgD;AAChD,0DAAwD;AACxD,4EAA0E;AAC1E,wDAAsD;AACtD,kEAAgE;AAChE,qEAAmE;AACnE,8EAA4E;AA0B5E,IAAa,SAAS;IAAtB;IAAyB,CAAC;IAAD,gBAAC;AAAD,CAAC,AAA1B,IAA0B;AAAb,SAAS;IAxBrB,eAAQ,CAAC;QACN,OAAO,EAAE;YACL,gCAAa;YACb,mBAAW;YACX,qBAAO;YACP,iBAAU;YACV,kBAAW;SACd;QACD,YAAY,EAAE;YACV,4BAAY;YACZ,gCAAc;YACd,8BAAa;YACb,gCAAc;YACd,sCAAiB;SACpB;QACD,SAAS,EAAE;YACP,sBAAS;YACT,4BAAY;YACZ,8CAAqB;YACrB,0BAAW;YACX,gCAAc;SACjB;QACD,SAAS,EAAE,CAAC,4BAAY,CAAC;KAC5B,CAAC;GACW,SAAS,CAAI;AAAb,8BAAS"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Routing; 7 | 8 | namespace OAuthAspNetWebApiRest.Api 9 | { 10 | public class RouteConfig 11 | { 12 | public static void RegisterRoutes(RouteCollection routes) 13 | { 14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 | 16 | routes.MapRoute( 17 | name: "Default", 18 | url: "{controller}/{action}/{id}", 19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/guards/auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3 | 4 | @Injectable() 5 | export class AuthGuard implements CanActivate { 6 | 7 | constructor(private router: Router) { } 8 | 9 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 10 | if (localStorage.getItem('currentUser')) { 11 | // logged in so return true 12 | return true; 13 | } 14 | 15 | // not logged in so redirect to login page with the return url 16 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 17 | return false; 18 | } 19 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Repositories/ProductRepository.cs: -------------------------------------------------------------------------------- 1 | using OAuthAspNetWebApiRest.Domain.Contracts.Repositories; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using OAuthAspNetWebApiRest.Domain.Models; 5 | using System.Data.Entity; 6 | 7 | namespace OAuthAspNetWebApiRest.Data.Repositories 8 | { 9 | public class ProductRepository: IProductRepository 10 | { 11 | private readonly AppDbContext _context; 12 | public ProductRepository(AppDbContext context) 13 | { 14 | _context = context; 15 | } 16 | 17 | public async Task> All() 18 | { 19 | var products = await _context.Products.ToListAsync(); 20 | return products; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/AppDbContextInitialize.cs: -------------------------------------------------------------------------------- 1 | using OAuthAspNetWebApiRest.Domain.Models; 2 | using System.Data.Entity.Migrations; 3 | 4 | namespace OAuthAspNetWebApiRest.Data 5 | { 6 | public class AppDbContextInitialize 7 | { 8 | public AppDbContextInitialize(AppDbContext context) 9 | { 10 | context.Database.CreateIfNotExists(); 11 | 12 | context.Products.AddOrUpdate( 13 | p => p.Name, 14 | new Product { Name = "Rice", Quantity = 5 }, 15 | new Product { Name = "Bean", Quantity = 10 }, 16 | new Product { Name = "Tomato", Quantity = 15 }, 17 | new Product { Name = "Steack", Quantity = 20 } 18 | ); 19 | context.SaveChanges(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Services/ProductService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using OAuthAspNetWebApiRest.Domain.Contracts.Services; 5 | using OAuthAspNetWebApiRest.Domain.Models; 6 | using OAuthAspNetWebApiRest.Domain.Contracts.Repositories; 7 | 8 | namespace OAuthAspNetWebApiRest.Domain.Services 9 | { 10 | public class ProductService : IProductService 11 | { 12 | private readonly IProductRepository _productRepository; 13 | public ProductService(IProductRepository productRepository) 14 | { 15 | _productRepository = productRepository; 16 | } 17 | public Task> All() 18 | { 19 | return _productRepository.All(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/Configuration.cs: -------------------------------------------------------------------------------- 1 | namespace OAuthAspNetWebApiRest.Data.Migrations 2 | { 3 | using Domain.Models; 4 | using System.Data.Entity.Migrations; 5 | 6 | internal sealed class Configuration : DbMigrationsConfiguration 7 | { 8 | public Configuration() 9 | { 10 | AutomaticMigrationsEnabled = false; 11 | } 12 | 13 | protected override void Seed(AppDbContext context) 14 | { 15 | context.Database.CreateIfNotExists(); 16 | 17 | context.Products.AddOrUpdate( 18 | p => p.Name, 19 | new Product { Name = "Rice", Quantity = 5 }, 20 | new Product { Name = "Bean" , Quantity = 10}, 21 | new Product { Name = "Tomato", Quantity = 15 } 22 | ); 23 | 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.component.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"home.component.js","sourceRoot":"","sources":["home.component.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAAkD;AAElD,iEAA+D;AAE/D,uCAAqC;AAOrC,IAAa,aAAa;IAGtB,uBAAoB,cAA8B;QAA9B,mBAAc,GAAd,cAAc,CAAgB;QAFlD,aAAQ,GAAc,EAAE,CAAC;IAGzB,CAAC;IAED,gCAAQ,GAAR;QACI,IAAI,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;QAC3D,EAAE,CAAC,CAAC,IAAI,CAAC;YACL,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;QACvE,IAAI,CAAC,YAAY,EAAE,CAAC;IACxB,CAAC;IACO,oCAAY,GAApB;QAAA,iBAGC;QAFG,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;aACvB,IAAI,CAAC,UAAA,CAAC,IAAM,KAAI,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC;IACL,oBAAC;AAAD,CAAC,AAhBD,IAgBC;AAhBY,aAAa;IALzB,gBAAS,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,EAAE;QACnB,WAAW,EAAE,qBAAqB;KAErC,CAAC;qCAIsC,gCAAc;GAHzC,aAAa,CAgBzB;AAhBY,sCAAa"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/user.service.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"user.service.js","sourceRoot":"","sources":["user.service.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA2C;AAC3C,sCAAwE;AAKxE,IAAa,WAAW;IACpB,qBAAoB,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QACtB,eAAU,GAAG,oCAAoC,CAAC;IADxB,CAAC;IAGnC,4BAAM,GAAN,UAAO,IAAU;QACb,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAI,IAAI,CAAC,UAAU,cAAW,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,UAAC,QAAkB,IAAK,OAAA,QAAQ,CAAC,IAAI,EAAE,EAAf,CAAe,CAAC,CAAC;IAC5G,CAAC;IAED,yBAAyB;IACjB,yBAAG,GAAX;QACI,6CAA6C;QAC7C,IAAI,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;QAClE,EAAE,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,YAAY,CAAC,CAAC,CAAC;YAC1C,IAAI,OAAO,GAAG,IAAI,cAAO,CAAC,EAAE,eAAe,EAAE,SAAS,GAAG,WAAW,CAAC,YAAY,EAAE,CAAC,CAAC;YACrF,MAAM,CAAC,IAAI,qBAAc,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QACpD,CAAC;IACL,CAAC;IACL,kBAAC;AAAD,CAAC,AAjBD,IAiBC;AAjBY,WAAW;IADvB,iBAAU,EAAE;qCAEiB,WAAI;GADrB,WAAW,CAiBvB;AAjBY,kCAAW"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.routing.ts: -------------------------------------------------------------------------------- 1 | import { Routes, RouterModule } from '@angular/router'; 2 | 3 | import { ModuleWithProviders } from '@angular/core'; 4 | 5 | import { HomeComponent } from './home-component/home.component'; 6 | import { LoginComponent } from './login-component/login.component'; 7 | import { RegisterComponent } from './register-component/register.component'; 8 | 9 | import { AuthGuard } from './guards/auth.guard'; 10 | 11 | const appRoutes: Routes = [ 12 | { 13 | path: '', 14 | redirectTo: '/', 15 | pathMatch: 'full' 16 | }, 17 | { path: '', component: HomeComponent, canActivate: [AuthGuard] }, 18 | { path: 'login', component: LoginComponent }, 19 | { path: 'register', component: RegisterComponent }, 20 | 21 | // otherwise redirect to home 22 | { path: '**', redirectTo: '' } 23 | ]; 24 | 25 | export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes); -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/WebApiConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Http; 2 | using Microsoft.Owin.Security.OAuth; 3 | using System.Web.Http.Cors; 4 | 5 | namespace OAuthAspNetWebApiRest.Api 6 | { 7 | public static class WebApiConfig 8 | { 9 | public static void Register(HttpConfiguration config) 10 | { 11 | // Web API configuration and services 12 | // Configure Web API to use only bearer token authentication. 13 | config.SuppressDefaultHostAuthentication(); 14 | config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 15 | 16 | // Web API routes 17 | config.MapHttpAttributeRoutes(); 18 | 19 | config.Routes.MapHttpRoute( 20 | name: "DefaultApi", 21 | routeTemplate: "api/{controller}/{id}", 22 | defaults: new { id = RouteParameter.Optional } 23 | ); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Product } from './../models/product'; 3 | import { ProductService } from './../services/product.service'; 4 | 5 | import 'rxjs/add/operator/toPromise'; 6 | 7 | @Component({ 8 | moduleId: module.id, 9 | templateUrl: 'home.component.html', 10 | }) 11 | export class HomeComponent implements OnInit { 12 | products: Product[] = []; 13 | currentUser: any; 14 | hasLoaded: boolean = false; 15 | constructor(private productService: ProductService) { 16 | } 17 | 18 | ngOnInit() { 19 | let user = JSON.parse(localStorage.getItem('currentUser')); 20 | if (user) 21 | this.currentUser = JSON.parse(localStorage.getItem('currentUser')); 22 | this.loadProducts(); 23 | } 24 | private loadProducts() { 25 | this.productService.getAll() 26 | .then(p => { this.products = p;}); 27 | } 28 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Http, Headers, RequestOptions, Response } from '@angular/http'; 3 | 4 | import { User } from '../models/user'; 5 | 6 | @Injectable() 7 | export class UserService { 8 | constructor(private http: Http) { } 9 | private accountUrl = "http://localhost:20835/api/Account"; 10 | 11 | create(user: User) { 12 | return this.http.post(`${this.accountUrl}/Register`, user).map((response: Response) => response.json()); 13 | } 14 | 15 | // private helper methods 16 | private jwt() { 17 | // create authorization header with jwt token 18 | let currentUser = JSON.parse(localStorage.getItem('currentUser')); 19 | if (currentUser && currentUser.access_token) { 20 | let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.access_token }); 21 | return new RequestOptions({ headers: headers }); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Controllers/ProductController.cs: -------------------------------------------------------------------------------- 1 | using OAuthAspNetWebApiRest.Domain.Contracts.Services; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using System.Web.Http; 5 | 6 | namespace OAuthAspNetWebApiRest.Api.Controllers 7 | { 8 | [Authorize] 9 | public class ProductController : ApiController 10 | { 11 | private readonly IProductService _productService; 12 | public ProductController(IProductService productService) 13 | { 14 | _productService = productService; 15 | } 16 | [HttpGet] 17 | public async Task Get() 18 | { 19 | try 20 | { 21 | IEnumerable products = await _productService.All(); 22 | return Ok(products); 23 | } 24 | catch (System.Exception ex) 25 | { 26 | return BadRequest(ex.Message); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.routing.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var router_1 = require("@angular/router"); 4 | var home_component_1 = require("./home-component/home.component"); 5 | var login_component_1 = require("./login-component/login.component"); 6 | var register_component_1 = require("./register-component/register.component"); 7 | var auth_guard_1 = require("./guards/auth.guard"); 8 | var appRoutes = [ 9 | { 10 | path: '', 11 | redirectTo: '/', 12 | pathMatch: 'full' 13 | }, 14 | { path: '', component: home_component_1.HomeComponent, canActivate: [auth_guard_1.AuthGuard] }, 15 | { path: 'login', component: login_component_1.LoginComponent }, 16 | { path: 'register', component: register_component_1.RegisterComponent }, 17 | // otherwise redirect to home 18 | { path: '**', redirectTo: '' } 19 | ]; 20 | exports.routing = router_1.RouterModule.forRoot(appRoutes); 21 | //# sourceMappingURL=app.routing.js.map -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/201705312114068_FirstMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | namespace OAuthAspNetWebApiRest.Data.Migrations 3 | { 4 | using System.CodeDom.Compiler; 5 | using System.Data.Entity.Migrations; 6 | using System.Data.Entity.Migrations.Infrastructure; 7 | using System.Resources; 8 | 9 | [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] 10 | public sealed partial class FirstMigration : IMigrationMetadata 11 | { 12 | private readonly ResourceManager Resources = new ResourceManager(typeof(FirstMigration)); 13 | 14 | string IMigrationMetadata.Id 15 | { 16 | get { return "201705312114068_FirstMigration"; } 17 | } 18 | 19 | string IMigrationMetadata.Source 20 | { 21 | get { return null; } 22 | } 23 | 24 | string IMigrationMetadata.Target 25 | { 26 | get { return Resources.GetString("Target"); } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/register-component/register.component.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"register.component.js","sourceRoot":"","sources":["register.component.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA0C;AAC1C,0CAAyC;AAEzC,yDAAuD;AACvD,2DAAyD;AAOzD,IAAa,iBAAiB;IAI1B,2BACY,MAAc,EACd,WAAwB,EACxB,YAA0B;QAF1B,WAAM,GAAN,MAAM,CAAQ;QACd,gBAAW,GAAX,WAAW,CAAa;QACxB,iBAAY,GAAZ,YAAY,CAAc;QANtC,UAAK,GAAQ,EAAE,CAAC;QAChB,YAAO,GAAG,KAAK,CAAC;IAK0B,CAAC;IAE3C,oCAAQ,GAAR;QAAA,iBAYC;QAXG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;aAC9B,SAAS,CACV,UAAA,IAAI;YACA,KAAI,CAAC,YAAY,CAAC,OAAO,CAAC,yBAAyB,EAAE,IAAI,CAAC,CAAC;YAC3D,KAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;QACrC,CAAC,EACD,UAAA,KAAK;YACD,KAAI,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC/B,KAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACzB,CAAC,CAAC,CAAC;IACX,CAAC;IACL,wBAAC;AAAD,CAAC,AAtBD,IAsBC;AAtBY,iBAAiB;IAL7B,gBAAS,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,EAAE;QACnB,WAAW,EAAE,yBAAyB;KACzC,CAAC;qCAOsB,eAAM;QACD,0BAAW;QACV,4BAAY;GAP7B,iBAAiB,CAsB7B;AAtBY,8CAAiB"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/register-component/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | import { UserService } from '../services/user.service'; 5 | import { AlertService } from '../services/alert.service'; 6 | 7 | @Component({ 8 | moduleId: module.id, 9 | templateUrl: 'register.component.html' 10 | }) 11 | 12 | export class RegisterComponent { 13 | model: any = {}; 14 | loading = false; 15 | 16 | constructor( 17 | private router: Router, 18 | private userService: UserService, 19 | private alertService: AlertService) { } 20 | 21 | register() { 22 | this.loading = true; 23 | this.userService.create(this.model) 24 | .subscribe( 25 | data => { 26 | this.alertService.success('Registration successful', true); 27 | this.router.navigate(['/login']); 28 | }, 29 | error => { 30 | this.alertService.error(error); 31 | this.loading = false; 32 | }); 33 | } 34 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Contracts/Services/IUserService.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNet.Identity; 4 | using OAuthAspNetWebApiRest.Domain.Models; 5 | 6 | namespace OAuthAspNetWebApiRest.Domain.Contracts.Services 7 | { 8 | public interface IUserService 9 | { 10 | Task FindAsync(UserLoginInfo userLoginInfo); 11 | Task FindByIdAsync(string id); 12 | Task AddPasswordAsync(string id, string newPassword); 13 | Task AddLoginAsync(string id, UserLoginInfo userLoginInfo); 14 | Task ChangePasswordAsync(string id, string oldPassword, string newPassword); 15 | Task CreateAsync(User user, string password); 16 | Task CreateAsync(User user); 17 | Task GenerateUserIdentityAsync(User user, string authenticationType); 18 | Task RemovePasswordAsync(string id); 19 | Task RemoveLoginAsync(string id, UserLoginInfo userLoginInfo); 20 | void Dispose(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Results/ChallengeResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Web.Http; 9 | 10 | namespace OAuthAspNetWebApiRest.Api.Results 11 | { 12 | public class ChallengeResult : IHttpActionResult 13 | { 14 | public ChallengeResult(string loginProvider, ApiController controller) 15 | { 16 | LoginProvider = loginProvider; 17 | Request = controller.Request; 18 | } 19 | 20 | public string LoginProvider { get; set; } 21 | public HttpRequestMessage Request { get; set; } 22 | 23 | public Task ExecuteAsync(CancellationToken cancellationToken) 24 | { 25 | Request.GetOwinContext().Authentication.Challenge(LoginProvider); 26 | 27 | HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 28 | response.RequestMessage = Request; 29 | return Task.FromResult(response); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Contracts/Repositories/IUserRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity; 2 | using OAuthAspNetWebApiRest.Domain.Models; 3 | using System.Security.Claims; 4 | using System.Threading.Tasks; 5 | 6 | namespace OAuthAspNetWebApiRest.Domain.Contracts.Repostiories 7 | { 8 | public interface IUserRepository 9 | { 10 | Task FindAsync(UserLoginInfo userLoginInfo); 11 | Task FindByIdAsync(string id); 12 | Task AddPasswordAsync(string id, string newPassword); 13 | Task AddLoginAsync(string id, UserLoginInfo userLoginInfo); 14 | Task ChangePasswordAsync(string id, string oldPassword, string newPassword); 15 | Task CreateAsync(User user, string password); 16 | Task CreateAsync(User user); 17 | Task GenerateUserIdentityAsync(User user, string authenticationType); 18 | Task RemovePasswordAsync(string id); 19 | Task RemoveLoginAsync(string id, UserLoginInfo userLoginInfo); 20 | void Dispose(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | Object.defineProperty(exports, "__esModule", { value: true }); 9 | var core_1 = require("@angular/core"); 10 | var AppComponent = (function () { 11 | function AppComponent() { 12 | } 13 | return AppComponent; 14 | }()); 15 | AppComponent = __decorate([ 16 | core_1.Component({ 17 | moduleId: module.id, 18 | selector: 'spa-app', 19 | templateUrl: './app.component.html', 20 | }) 21 | ], AppComponent); 22 | exports.AppComponent = AppComponent; 23 | //# sourceMappingURL=app.component.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/product.service.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"product.service.js","sourceRoot":"","sources":["product.service.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA2C;AAC3C,sCAAwE;AAExE,iCAA8B;AAC9B,uCAAqC;AACrC,mCAAiC;AAKjC,IAAa,cAAc;IACvB,wBAAoB,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QAEtB,eAAU,GAAG,oCAAoC,CAAC;IAFxB,CAAC;IAInC,+BAAM,GAAN;QACI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC;aAC5C,SAAS,EAAE;aACX,IAAI,CAAC,UAAA,GAAG,IAAI,OAAA,GAAG,CAAC,IAAI,EAAe,EAAvB,CAAuB,CAAC;aACpC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACjC,CAAC;IACO,oCAAW,GAAnB,UAAoB,KAAU;QAC1B,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,KAAK,CAAC,CAAC;QAC1C,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;IAClD,CAAC;IAEO,4BAAG,GAAX;QACI,6CAA6C;QAC7C,IAAI,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;QAClE,EAAE,CAAC,CAAC,WAAW,IAAI,WAAW,CAAC,YAAY,CAAC,CAAC,CAAC;YAC1C,IAAI,OAAO,GAAG,IAAI,cAAO,CAAC;gBACtB,eAAe,EAAE,SAAS,GAAG,WAAW,CAAC,YAAY,EAAE,eAAe,EAAE,IAAI;aAC/E,CAAC,CAAC;YACH,MAAM,CAAC,IAAI,qBAAc,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;QACpD,CAAC;IACL,CAAC;IACL,qBAAC;AAAD,CAAC,AA1BD,IA0BC;AA1BY,cAAc;IAD1B,iBAAU,EAAE;qCAEiB,WAAI;GADrB,cAAc,CA0B1B;AA1BY,wCAAc"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Models/AccountViewModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace OAuthAspNetWebApiRest.Api.Models 5 | { 6 | // Models returned by AccountController actions. 7 | 8 | public class ExternalLoginViewModel 9 | { 10 | public string Name { get; set; } 11 | 12 | public string Url { get; set; } 13 | 14 | public string State { get; set; } 15 | } 16 | 17 | public class ManageInfoViewModel 18 | { 19 | public string LocalLoginProvider { get; set; } 20 | 21 | public string Email { get; set; } 22 | 23 | public IEnumerable Logins { get; set; } 24 | 25 | public IEnumerable ExternalLoginProviders { get; set; } 26 | } 27 | 28 | public class UserInfoViewModel 29 | { 30 | public string Email { get; set; } 31 | 32 | public bool HasRegistered { get; set; } 33 | 34 | public string LoginProvider { get; set; } 35 | } 36 | 37 | public class UserLoginInfoViewModel 38 | { 39 | public string LoginProvider { get; set; } 40 | 41 | public string ProviderKey { get; set; } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SPA-Angular 2 | 3 | 4 | Este projeto foi desenvolvido utilizando ASP.NET Web Api e Angular, com Autenticação OAuth: 5 | 6 | 7 | ### Tecnologias 8 | 9 | 10 | * [Visual Studio Community 2017] - Ambiente de Desenvolvimento. 11 | * [ASP NET MVC] - Biblioteca para desenvolvimento de websites dinâmicos. 12 | * [Simple Injector] - Biblioteca de Injeção de Dependência. 13 | * [ASP NET Identity] - Biblioteca de Autenticação com superte a Perfil, Integrção com OAuth. 14 | * [MS SQL Express] - Ferramenta de Banco de Dados Relacional. 15 | * [Angular] - Biblioteca para aplicações web com apenas uma página. 16 | * [Node.JS] - Engine de contrução em tempo de execução de aplicações JavaScript. 17 | 18 | 19 | ### 20 | Licença 21 | ---- 22 | 23 | MIT 24 | 25 | 26 | **Sinta-se a livre!** 27 | 28 | 29 | [Visual Studio Community 2017]: 30 | [ASP NET MVC]: 31 | [Simple Injector]: 32 | [ASP NET Identity]: 33 | [MS SQL Express]: 34 | [Angular]: 35 | [Node.Js]: 36 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/alert.service.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"alert.service.js","sourceRoot":"","sources":["alert.service.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA2C;AAC3C,0CAA0D;AAE1D,wCAAuC;AAGvC,IAAa,YAAY;IAIrB,sBAAoB,MAAc;QAAlC,iBAaC;QAbmB,WAAM,GAAN,MAAM,CAAQ;QAH1B,YAAO,GAAG,IAAI,iBAAO,EAAO,CAAC;QAC7B,8BAAyB,GAAG,KAAK,CAAC;QAGtC,sCAAsC;QACtC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,UAAA,KAAK;YACzB,EAAE,CAAC,CAAC,KAAK,YAAY,wBAAe,CAAC,CAAC,CAAC;gBACnC,EAAE,CAAC,CAAC,KAAI,CAAC,yBAAyB,CAAC,CAAC,CAAC;oBACjC,yCAAyC;oBACzC,KAAI,CAAC,yBAAyB,GAAG,KAAK,CAAC;gBAC3C,CAAC;gBAAC,IAAI,CAAC,CAAC;oBACJ,cAAc;oBACd,KAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;gBACxB,CAAC;YACL,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAED,8BAAO,GAAP,UAAQ,OAAe,EAAE,yBAAiC;QAAjC,0CAAA,EAAA,iCAAiC;QACtD,IAAI,CAAC,yBAAyB,GAAG,yBAAyB,CAAC;QAC3D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED,4BAAK,GAAL,UAAM,OAAe,EAAE,yBAAiC;QAAjC,0CAAA,EAAA,iCAAiC;QACpD,IAAI,CAAC,yBAAyB,GAAG,yBAAyB,CAAC;QAC3D,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;IACxD,CAAC;IAED,iCAAU,GAAV;QACI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;IACvC,CAAC;IACL,mBAAC;AAAD,CAAC,AAhCD,IAgCC;AAhCY,YAAY;IADxB,iBAAU,EAAE;qCAKmB,eAAM;GAJzB,YAAY,CAgCxB;AAhCY,oCAAY"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/login-component/login.component.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"login.component.js","sourceRoot":"","sources":["login.component.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAAkD;AAClD,0CAAyD;AAEzD,6EAA2E;AAC3E,2DAAyD;AAOzD,IAAa,cAAc;IAKvB,wBACY,KAAqB,EACrB,MAAc,EACd,qBAA4C,EAC5C,YAA0B;QAH1B,UAAK,GAAL,KAAK,CAAgB;QACrB,WAAM,GAAN,MAAM,CAAQ;QACd,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,iBAAY,GAAZ,YAAY,CAAc;QARtC,UAAK,GAAQ,EAAE,CAAC;QAChB,YAAO,GAAG,KAAK,CAAC;IAO0B,CAAC;IAE3C,iCAAQ,GAAR;QACI,qBAAqB;QACrB,IAAI,CAAC,qBAAqB,CAAC,MAAM,EAAE,CAAC;QAEpC,yDAAyD;QACzD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,WAAW,CAAC,IAAI,GAAG,CAAC;IACzE,CAAC;IAED,8BAAK,GAAL;QAAA,iBAWC;QAVG,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC;aACrE,IAAI,CAAC,UAAA,IAAI;YACN,KAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAI,CAAC,SAAS,CAAC,CAAC,CAAC;QAC3C,CAAC,CAAC;aACD,KAAK,CAAC,UAAA,KAAK;YACR,KAAI,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAC/B,KAAI,CAAC,OAAO,GAAG,KAAK,CAAC;YACrB,KAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC;IACX,CAAC;IACL,qBAAC;AAAD,CAAC,AA/BD,IA+BC;AA/BY,cAAc;IAL1B,gBAAS,CAAC;QACP,QAAQ,EAAE,MAAM,CAAC,EAAE;QACnB,WAAW,EAAE,sBAAsB;KACtC,CAAC;qCAQqB,uBAAc;QACb,eAAM;QACS,8CAAqB;QAC9B,4BAAY;GAT7B,cAAc,CA+B1B;AA/BY,wCAAc"} -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Web.Debug.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Web.Debug.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/SPA_Angular_AspNet_WebApi_Rest.csproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | true 5 | ShowAllFiles 6 | 2.2 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | CurrentPage 15 | True 16 | False 17 | False 18 | False 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | True 28 | True 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Web.Release.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Web.config: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 23 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Web.Release.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/alert.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, NavigationStart } from '@angular/router'; 3 | import { Observable } from 'rxjs'; 4 | import { Subject } from 'rxjs/Subject'; 5 | 6 | @Injectable() 7 | export class AlertService { 8 | private subject = new Subject(); 9 | private keepAfterNavigationChange = false; 10 | 11 | constructor(private router: Router) { 12 | // clear alert message on route change 13 | router.events.subscribe(event => { 14 | if (event instanceof NavigationStart) { 15 | if (this.keepAfterNavigationChange) { 16 | // only keep for a single location change 17 | this.keepAfterNavigationChange = false; 18 | } else { 19 | // clear alert 20 | this.subject.next(); 21 | } 22 | } 23 | }); 24 | } 25 | 26 | success(message: string, keepAfterNavigationChange = false) { 27 | this.keepAfterNavigationChange = keepAfterNavigationChange; 28 | this.subject.next({ type: 'success', text: message }); 29 | } 30 | 31 | error(message: string, keepAfterNavigationChange = false) { 32 | this.keepAfterNavigationChange = keepAfterNavigationChange; 33 | this.subject.next({ type: 'error', text: message }); 34 | } 35 | 36 | getMessage(): Observable { 37 | return this.subject.asObservable(); 38 | } 39 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/login-component/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router, ActivatedRoute } from '@angular/router'; 3 | 4 | import { AuthenticationService } from '../services/authentication.service'; 5 | import { AlertService } from '../services/alert.service'; 6 | 7 | @Component({ 8 | moduleId: module.id, 9 | templateUrl: 'login.component.html' 10 | }) 11 | 12 | export class LoginComponent implements OnInit { 13 | model: any = {}; 14 | loading = false; 15 | returnUrl: string; 16 | 17 | constructor( 18 | private route: ActivatedRoute, 19 | private router: Router, 20 | private authenticationService: AuthenticationService, 21 | private alertService: AlertService) { } 22 | 23 | ngOnInit() { 24 | // reset login status 25 | this.authenticationService.logout(); 26 | 27 | // get return url from route parameters or default to '/' 28 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 29 | } 30 | 31 | login() { 32 | this.loading = true; 33 | this.authenticationService.login(this.model.username, this.model.password) 34 | .then(data => { 35 | this.router.navigate([this.returnUrl]); 36 | }) 37 | .catch(error => { 38 | this.alertService.error(error); 39 | this.loading = false; 40 | this.router.navigate(['/']); 41 | }); 42 | } 43 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Web.Http; 3 | using System.Web.Mvc; 4 | using System.Web.Routing; 5 | 6 | namespace OAuthAspNetWebApiRest.Api 7 | { 8 | public class WebApiApplication : System.Web.HttpApplication 9 | { 10 | protected void Application_Start() 11 | { 12 | GlobalConfiguration.Configure(WebApiConfig.Register); 13 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 14 | RouteConfig.RegisterRoutes(RouteTable.Routes); 15 | 16 | //Define Formatters 17 | var formatters = GlobalConfiguration.Configuration.Formatters; 18 | var jsonFormatter = formatters.JsonFormatter; 19 | jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; 20 | jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 21 | jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; 22 | GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 23 | } 24 | 25 | protected void Application_BeginRequest() 26 | { 27 | if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") 28 | { 29 | if (!Request.Path.Contains("/Token")) 30 | Response.Flush(); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/product.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Headers, Http, Response, RequestOptions, RequestMethod } from '@angular/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | import 'rxjs/add/operator/map' 5 | import 'rxjs/add/operator/toPromise'; 6 | import 'rxjs/add/operator/first'; 7 | 8 | import { Product } from './../models/product'; 9 | 10 | @Injectable() 11 | export class ProductService { 12 | constructor(private http: Http) { } 13 | 14 | private producturl = "http://localhost:20835/api/product"; 15 | 16 | getAll() { 17 | return this.http.get(this.producturl, this.jwt()) 18 | .toPromise() 19 | .then(res => res.json() as Product[]) 20 | .catch(this.handleError); 21 | } 22 | private handleError(error: any): Promise { 23 | console.error('An error occurred', error); 24 | return Promise.reject(error.message || error); 25 | } 26 | 27 | private jwt() { 28 | // create authorization header with jwt token 29 | let currentUser = JSON.parse(localStorage.getItem('currentUser')); 30 | if (currentUser && currentUser.access_token) { 31 | let headers = new Headers({ 32 | 'Content-Type': 'application/json', 33 | 'Authorization': 'Bearer ' + currentUser.access_token, withCredentials: true 34 | }); 35 | return new RequestOptions({ method: RequestMethod.Get, headers: headers }); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("OAuthAspNetWebApiRest.Api")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("OAuthAspNetWebApiRest.Api")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("815e716b-889a-4b13-b9b0-d691aa851148")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SPA_Angular_AspNet_WebApi_Rest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SPA_Angular_AspNet_WebApi_Rest")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0c5fce17-e38e-4b2d-9e4f-187535e0a18d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { HttpModule, JsonpModule } from '@angular/http'; 4 | import { FormsModule } from '@angular/forms'; 5 | 6 | import { AppComponent } from './app.component'; 7 | 8 | import { routing } from './app.routing'; 9 | 10 | import { ProductService } from './services/product.service'; 11 | import { AlertComponent } from './directives/alert-component/alert.component'; 12 | import { AuthGuard } from './guards/auth.guard'; 13 | import { AlertService } from './services/alert.service'; 14 | import { AuthenticationService } from './services/authentication.service'; 15 | import { UserService } from './services/user.service'; 16 | import { HomeComponent } from './home-component/home.component'; 17 | import { LoginComponent } from './login-component/login.component'; 18 | import { RegisterComponent } from './register-component/register.component'; 19 | 20 | @NgModule({ 21 | imports: [ 22 | BrowserModule, 23 | FormsModule, 24 | routing, 25 | HttpModule, 26 | JsonpModule, 27 | ], 28 | declarations: [ 29 | AppComponent, 30 | AlertComponent, 31 | HomeComponent, 32 | LoginComponent, 33 | RegisterComponent 34 | ], 35 | providers: [ 36 | AuthGuard, 37 | AlertService, 38 | AuthenticationService, 39 | UserService, 40 | ProductService 41 | ], 42 | bootstrap: [AppComponent] 43 | }) 44 | export class AppModule { } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("OAuthAspNetWebApiRest.Data")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("OAuthAspNetWebApiRest.Data")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9813bf00-14d2-470d-9f94-638910e1e976")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("OAuthAspNetWebApiRest.Domain")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("OAuthAspNetWebApiRest.Domain")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("7e6a64ea-4631-4640-abe2-0184ddb4fa1a")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/authentication.service.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"authentication.service.js","sourceRoot":"","sources":["authentication.service.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,sCAA2C;AAC3C,sCAAyF;AAEzF,iCAA8B;AAG9B,IAAa,qBAAqB;IAC9B,+BAAoB,IAAU;QAAV,SAAI,GAAJ,IAAI,CAAM;QACtB,oBAAe,GAAG,wBAAwB,CAAC;IADjB,CAAC;IAEnC,qCAAK,GAAL,UAAM,QAAgB,EAAE,QAAgB;QACpC,IAAI,IAAI,GAAE,cAAY,QAAQ,kBAAa,QAAQ,yBAAsB,CAAC;QAC1E,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAClB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAI,IAAI,CAAC,eAAe,WAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC;aAC7E,SAAS,EAAE;aACX,IAAI,CAAC,UAAA,QAAQ;YACV,0DAA0D;YAC1D,IAAI,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;YAC3B,EAAE,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;gBAC5B,kGAAkG;gBAClG,YAAY,CAAC,OAAO,CAAC,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9D,CAAC;QACL,CAAC,CAAC;aACD,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACjC,CAAC;IAED,sCAAM,GAAN;QACI,iDAAiD;QACjD,YAAY,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;IAC3C,CAAC;IACO,2CAAW,GAAnB,UAAoB,KAAU;QAC1B,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,KAAK,CAAC,CAAC;QAC1C,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;IAClD,CAAC;IACO,6CAAa,GAArB;QACI,IAAI,OAAO,GAAG,IAAI,cAAO,CAAC;YACtB,cAAc,EAAE,mCAAmC,EAAE,eAAe,EAAE,IAAI;SAC7E,CAAC,CAAC;QACH,MAAM,CAAC,IAAI,qBAAc,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;IACpD,CAAC;IACO,yCAAS,GAAjB,UAAkB,GAAW;QACzB,IAAI,eAAe,GAAG,IAAI,sBAAe,EAAE,CAAC;QAC5C,GAAG,CAAC,CAAC,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC;YAClB,eAAe,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;QAC1C,CAAC;QACD,MAAM,CAAC,eAAe,CAAC,QAAQ,EAAE,CAAC;IACtC,CAAC;IACL,4BAAC;AAAD,CAAC,AAxCD,IAwCC;AAxCY,qBAAqB;IADjC,iBAAU,EAAE;qCAEiB,WAAI;GADrB,qBAAqB,CAwCjC;AAxCY,sDAAqB"} -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/guards/auth.guard.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var router_1 = require("@angular/router"); 14 | var AuthGuard = (function () { 15 | function AuthGuard(router) { 16 | this.router = router; 17 | } 18 | AuthGuard.prototype.canActivate = function (route, state) { 19 | if (localStorage.getItem('currentUser')) { 20 | // logged in so return true 21 | return true; 22 | } 23 | // not logged in so redirect to login page with the return url 24 | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 25 | return false; 26 | }; 27 | return AuthGuard; 28 | }()); 29 | AuthGuard = __decorate([ 30 | core_1.Injectable(), 31 | __metadata("design:paramtypes", [router_1.Router]) 32 | ], AuthGuard); 33 | exports.AuthGuard = AuthGuard; 34 | //# sourceMappingURL=auth.guard.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/directives/alert-component/alert.component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var alert_service_1 = require("../../services/alert.service"); 14 | var AlertComponent = (function () { 15 | function AlertComponent(alertService) { 16 | this.alertService = alertService; 17 | } 18 | AlertComponent.prototype.ngOnInit = function () { 19 | var _this = this; 20 | this.alertService.getMessage().subscribe(function (message) { _this.message = message; }); 21 | }; 22 | return AlertComponent; 23 | }()); 24 | AlertComponent = __decorate([ 25 | core_1.Component({ 26 | moduleId: module.id, 27 | selector: 'alert', 28 | templateUrl: 'alert.component.html' 29 | }), 30 | __metadata("design:paramtypes", [alert_service_1.AlertService]) 31 | ], AlertComponent); 32 | exports.AlertComponent = AlertComponent; 33 | //# sourceMappingURL=alert.component.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spa_angular_aspnet_webapi", 3 | "version": "1.0.0", 4 | "description": "Projeto para demonstrar o suso do angular com o aspnet mvc", 5 | "scripts": { 6 | "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ", 7 | "lint": "tslint ./app/**/*.ts -t verbose", 8 | "lite": "lite-server", 9 | "pree2e": "webdriver-manager update", 10 | "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"", 11 | "test-once": "tsc && karma start karma.conf.js --single-run", 12 | "tsc": "tsc", 13 | "tsc:w": "tsc -w" 14 | }, 15 | "keywords": [], 16 | "author": "Charles Oliveira", 17 | "license": "MIT", 18 | "dependencies": { 19 | 20 | "@angular/common": "4.0.2", 21 | "@angular/compiler": "4.0.2", 22 | "@angular/core": "4.0.2", 23 | "@angular/forms": "4.0.2", 24 | "@angular/http": "4.0.2", 25 | "@angular/platform-browser": "4.0.2", 26 | "@angular/platform-browser-dynamic": "4.0.2", 27 | "@angular/router": "4.0.2", 28 | "angular-in-memory-web-api": "~0.2.4", 29 | "systemjs": "0.19.40", 30 | "core-js": "^2.4.1", 31 | "rxjs": "5.0.1", 32 | "zone.js": "^0.7.4" 33 | }, 34 | "devDependencies": { 35 | "concurrently": "^3.2.0", 36 | "lite-server": "^2.2.2", 37 | "typescript": "~2.0.10", 38 | "canonical-path": "0.0.2", 39 | "tslint": "^3.15.1", 40 | "lodash": "^4.16.4", 41 | "jasmine-core": "~2.4.1", 42 | "karma": "^1.3.0", 43 | "karma-chrome-launcher": "^2.0.0", 44 | "karma-cli": "^1.0.1", 45 | "karma-jasmine": "^1.0.2", 46 | "karma-jasmine-html-reporter": "^0.2.2", 47 | "protractor": "~4.0.14", 48 | "rimraf": "^2.5.4", 49 | "@types/node": "^6.0.46", 50 | "@types/jasmine": "2.5.36" 51 | }, 52 | "repository": {} 53 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/Index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | SPA ASP.NET Angular 7 | 8 | 9 | 10 | 11 | 12 | 28 |
29 | 30 |
31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 42 | 43 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/OAuthAspNetWebApiRest.Api.csproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | true 5 | ShowAllFiles 6 | 600 7 | True 8 | False 9 | True 10 | 11 | False 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | CurrentPage 20 | True 21 | False 22 | False 23 | False 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | True 33 | True 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/systemjs.config.js: -------------------------------------------------------------------------------- 1 | /**  2 |  * System configuration for Angular samples  3 |  * Adjust as necessary for your application needs.  4 |  */ 5 | (function (global) { 6 | System.config({ 7 | paths: { 8 | // paths serve as alias  9 | 'npm:': 'node_modules/' 10 | }, 11 | // map tells the System loader where to look for things  12 | map: { 13 | // our app is within the app folder  14 | app: 'app', 15 | 16 | // angular bundles  17 | '@angular/core': 'npm:@angular/core/bundles/core.umd.js', 18 | '@angular/common': 'npm:@angular/common/bundles/common.umd.js', 19 | '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', 20 | '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', 21 | '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', 22 | '@angular/http': 'npm:@angular/http/bundles/http.umd.js', 23 | '@angular/router': 'npm:@angular/router/bundles/router.umd.js', 24 | '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 25 | 26 | // other libraries  27 | 'rxjs': 'npm:rxjs', 28 | 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js', 29 | 30 | 'moment': 'npm:moment/moment.js', 31 | 'ng2-bootstrap': 'npm:ng2-bootstrap/bundles/ngx-bootstrap.umd.js', 32 | }, 33 | // packages tells the System loader how to load when no filename and/or no extension  34 | packages: { 35 | app: { 36 | defaultExtension: 'js' 37 | }, 38 | rxjs: { 39 | defaultExtension: 'js' 40 | } 41 | } 42 | }); 43 | })(this); -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/user.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var http_1 = require("@angular/http"); 14 | var UserService = (function () { 15 | function UserService(http) { 16 | this.http = http; 17 | this.accountUrl = "http://localhost:20835/api/Account"; 18 | } 19 | UserService.prototype.create = function (user) { 20 | return this.http.post(this.accountUrl + "/Register", user).map(function (response) { return response.json(); }); 21 | }; 22 | // private helper methods 23 | UserService.prototype.jwt = function () { 24 | // create authorization header with jwt token 25 | var currentUser = JSON.parse(localStorage.getItem('currentUser')); 26 | if (currentUser && currentUser.access_token) { 27 | var headers = new http_1.Headers({ 'Authorization': 'Bearer ' + currentUser.access_token }); 28 | return new http_1.RequestOptions({ headers: headers }); 29 | } 30 | }; 31 | return UserService; 32 | }()); 33 | UserService = __decorate([ 34 | core_1.Injectable(), 35 | __metadata("design:paramtypes", [http_1.Http]) 36 | ], UserService); 37 | exports.UserService = UserService; 38 | //# sourceMappingURL=user.service.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/home-component/home.component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var product_service_1 = require("./../services/product.service"); 14 | require("rxjs/add/operator/toPromise"); 15 | var HomeComponent = (function () { 16 | function HomeComponent(productService) { 17 | this.productService = productService; 18 | this.products = []; 19 | } 20 | HomeComponent.prototype.ngOnInit = function () { 21 | var user = JSON.parse(localStorage.getItem('currentUser')); 22 | if (user) 23 | this.currentUser = JSON.parse(localStorage.getItem('currentUser')); 24 | this.loadProducts(); 25 | }; 26 | HomeComponent.prototype.loadProducts = function () { 27 | var _this = this; 28 | this.productService.getAll() 29 | .then(function (p) { _this.products = p; }); 30 | }; 31 | return HomeComponent; 32 | }()); 33 | HomeComponent = __decorate([ 34 | core_1.Component({ 35 | moduleId: module.id, 36 | templateUrl: 'home.component.html', 37 | }), 38 | __metadata("design:paramtypes", [product_service_1.ProductService]) 39 | ], HomeComponent); 40 | exports.HomeComponent = HomeComponent; 41 | //# sourceMappingURL=home.component.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/login-component/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Login

3 |
4 |
5 | 6 | 7 |
Username is required
8 |
9 |
10 | 11 | 12 |
Password is required
13 |
14 |
15 | 16 | 17 | Register 18 |
19 |
20 |
-------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/authentication.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Http, Headers, Response, RequestOptions, URLSearchParams, RequestMethod } from '@angular/http'; 3 | import { Observable } from 'rxjs/Observable'; 4 | import 'rxjs/add/operator/map' 5 | 6 | @Injectable() 7 | export class AuthenticationService { 8 | constructor(private http: Http) { } 9 | private authenticateUrl = "http://localhost:20835"; 10 | login(username: string, password: string) { 11 | var body = `username=${username}&password=${password}&grant_type=password`; 12 | var bodyEconded = this.urlEncode({username:username, password: password, grant_type:'password'}); 13 | console.log(body); 14 | return this.http.post(`${this.authenticateUrl}/Token`, bodyEconded, this.headerOptions()) 15 | .toPromise() 16 | .then(response => { 17 | // login successful if there's a jwt token in the response 18 | let user = response.json(); 19 | if (user && user.access_token) { 20 | // store user details and jwt token in local storage to keep user logged in between page refreshes 21 | localStorage.setItem('currentUser', JSON.stringify(user)); 22 | } 23 | }) 24 | .catch(this.handleError); 25 | } 26 | 27 | logout() { 28 | // remove user from local storage to log user out 29 | localStorage.removeItem('currentUser'); 30 | } 31 | private handleError(error: any): Promise { 32 | console.error('An error occurred', error); 33 | return Promise.reject(error.message || error); 34 | } 35 | private headerOptions() { 36 | let headers = new Headers({ 37 | 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF8' 38 | }); 39 | return new RequestOptions({ method: RequestMethod.Post,headers: headers }); 40 | } 41 | private urlEncode(obj: Object): string { 42 | let urlSearchParams = new URLSearchParams(); 43 | for (let key in obj) { 44 | urlSearchParams.append(key, obj[key]); 45 | } 46 | return urlSearchParams.toString(); 47 | } 48 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/SimpleInjectorWebApiInitializer.cs: -------------------------------------------------------------------------------- 1 | [assembly: WebActivator.PostApplicationStartMethod(typeof(OAuthAspNetWebApiRest.Api.App_Start.SimpleInjectorWebApiInitializer), "Initialize")] 2 | 3 | namespace OAuthAspNetWebApiRest.Api.App_Start 4 | { 5 | using System.Web.Http; 6 | using SimpleInjector; 7 | using SimpleInjector.Integration.WebApi; 8 | using Domain.Contracts.Repostiories; 9 | using Data.Repositories; 10 | using Data; 11 | using Microsoft.AspNet.Identity; 12 | using Domain.Models; 13 | using Domain.Services; 14 | using Domain.Contracts.Services; 15 | using SimpleInjector.Lifestyles; 16 | using Domain.Contracts.Repositories; 17 | 18 | public static class SimpleInjectorWebApiInitializer 19 | { 20 | public static Container Container; 21 | static SimpleInjectorWebApiInitializer() 22 | { 23 | Container = new Container(); 24 | } 25 | /// Initialize the container and register it as Web API Dependency Resolver. 26 | public static void Initialize() 27 | { 28 | 29 | Container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); 30 | 31 | InitializeContainer(Container); 32 | 33 | Container.RegisterWebApiControllers(GlobalConfiguration.Configuration); 34 | 35 | Container.Verify(); 36 | 37 | GlobalConfiguration.Configuration.DependencyResolver = 38 | new SimpleInjectorWebApiDependencyResolver(Container); 39 | } 40 | 41 | private static void InitializeContainer(Container container) 42 | { 43 | container.Register(Lifestyle.Scoped); 44 | //container.Register(container.GetInstance); 45 | container.Register, AppUserStore>(Lifestyle.Scoped); 46 | container.Register(Lifestyle.Scoped); 47 | container.Register(Lifestyle.Scoped); 48 | container.Register(Lifestyle.Scoped); 49 | container.Register(Lifestyle.Scoped); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/register-component/register.component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var router_1 = require("@angular/router"); 14 | var user_service_1 = require("../services/user.service"); 15 | var alert_service_1 = require("../services/alert.service"); 16 | var RegisterComponent = (function () { 17 | function RegisterComponent(router, userService, alertService) { 18 | this.router = router; 19 | this.userService = userService; 20 | this.alertService = alertService; 21 | this.model = {}; 22 | this.loading = false; 23 | } 24 | RegisterComponent.prototype.register = function () { 25 | var _this = this; 26 | this.loading = true; 27 | this.userService.create(this.model) 28 | .subscribe(function (data) { 29 | _this.alertService.success('Registration successful', true); 30 | _this.router.navigate(['/login']); 31 | }, function (error) { 32 | _this.alertService.error(error); 33 | _this.loading = false; 34 | }); 35 | }; 36 | return RegisterComponent; 37 | }()); 38 | RegisterComponent = __decorate([ 39 | core_1.Component({ 40 | moduleId: module.id, 41 | templateUrl: 'register.component.html' 42 | }), 43 | __metadata("design:paramtypes", [router_1.Router, 44 | user_service_1.UserService, 45 | alert_service_1.AlertService]) 46 | ], RegisterComponent); 47 | exports.RegisterComponent = RegisterComponent; 48 | //# sourceMappingURL=register.component.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/product.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var http_1 = require("@angular/http"); 14 | require("rxjs/add/operator/map"); 15 | require("rxjs/add/operator/toPromise"); 16 | require("rxjs/add/operator/first"); 17 | var ProductService = (function () { 18 | function ProductService(http) { 19 | this.http = http; 20 | this.producturl = "http://localhost:20835/api/product"; 21 | } 22 | ProductService.prototype.getAll = function () { 23 | return this.http.get(this.producturl, this.jwt()) 24 | .toPromise() 25 | .then(function (res) { return res.json(); }) 26 | .catch(this.handleError); 27 | }; 28 | ProductService.prototype.handleError = function (error) { 29 | console.error('An error occurred', error); 30 | return Promise.reject(error.message || error); 31 | }; 32 | ProductService.prototype.jwt = function () { 33 | // create authorization header with jwt token 34 | var currentUser = JSON.parse(localStorage.getItem('currentUser')); 35 | if (currentUser && currentUser.access_token) { 36 | var headers = new http_1.Headers({ 37 | 'Authorization': 'Bearer ' + currentUser.access_token, withCredentials: true 38 | }); 39 | return new http_1.RequestOptions({ headers: headers }); 40 | } 41 | }; 42 | return ProductService; 43 | }()); 44 | ProductService = __decorate([ 45 | core_1.Injectable(), 46 | __metadata("design:paramtypes", [http_1.Http]) 47 | ], ProductService); 48 | exports.ProductService = ProductService; 49 | //# sourceMappingURL=product.service.js.map -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.AspNet.Identity; 4 | using Microsoft.Owin; 5 | using Microsoft.Owin.Security.Cookies; 6 | using Microsoft.Owin.Security.OAuth; 7 | using Owin; 8 | using OAuthAspNetWebApiRest.Api.Providers; 9 | using OAuthAspNetWebApiRest.Data.Repositories; 10 | using OAuthAspNetWebApiRest.Api.App_Start; 11 | using SimpleInjector.Lifestyles; 12 | using OAuthAspNetWebApiRest.Data; 13 | 14 | namespace OAuthAspNetWebApiRest.Api 15 | { 16 | public partial class Startup 17 | { 18 | public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 19 | 20 | public static string PublicClientId { get; private set; } 21 | 22 | // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 23 | public void ConfigureAuth(IAppBuilder app) 24 | { 25 | //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 26 | 27 | var container = SimpleInjectorWebApiInitializer.Container; 28 | app.CreatePerOwinContext(AppDbContext.Create); 29 | app.CreatePerOwinContext(UserRepository.Create); 30 | // Enable the application to use a cookie to store information for the signed in user 31 | // and to use a cookie to temporarily store information about a user logging in with a third party login provider 32 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 33 | app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 34 | 35 | // Configure the application for OAuth based flow 36 | PublicClientId = "self"; 37 | OAuthOptions = new OAuthAuthorizationServerOptions 38 | { 39 | TokenEndpointPath = new PathString("/Token"), 40 | Provider = new ApplicationOAuthProvider(PublicClientId), 41 | AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 42 | AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 43 | // In production mode set AllowInsecureHttp = false 44 | AllowInsecureHttp = true 45 | }; 46 | app.Use(async (context, next) => { 47 | using (AsyncScopedLifestyle.BeginScope(container)) 48 | { 49 | await next(); 50 | } 51 | }); 52 | 53 | // Enable the application to use bearer tokens to authenticate users 54 | app.UseOAuthBearerTokens(OAuthOptions); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/Services/UserService.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNet.Identity; 4 | using Microsoft.AspNet.Identity.EntityFramework; 5 | using OAuthAspNetWebApiRest.Domain.Contracts.Services; 6 | using OAuthAspNetWebApiRest.Domain.Models; 7 | using OAuthAspNetWebApiRest.Domain.Contracts.Repostiories; 8 | 9 | namespace OAuthAspNetWebApiRest.Domain.Services 10 | { 11 | public class UserService : IUserService 12 | { 13 | private readonly IUserRepository _userRepository; 14 | public UserService(IUserRepository userRepository) 15 | { 16 | _userRepository = userRepository; 17 | } 18 | public Task AddLoginAsync(string id, UserLoginInfo userLoginInfo) 19 | { 20 | return _userRepository.AddLoginAsync(id, userLoginInfo); 21 | } 22 | 23 | public Task AddPasswordAsync(string id, string newPassword) 24 | { 25 | return _userRepository.AddPasswordAsync(id, newPassword); 26 | } 27 | 28 | public Task ChangePasswordAsync(string id, string oldPassword, string newPassword) 29 | { 30 | return _userRepository.ChangePasswordAsync(id, oldPassword, newPassword); 31 | } 32 | 33 | public Task CreateAsync(User user) 34 | { 35 | return _userRepository.CreateAsync(user); 36 | } 37 | 38 | public Task CreateAsync(User user, string password) 39 | { 40 | return _userRepository.CreateAsync(user, password); 41 | } 42 | 43 | public void Dispose() 44 | { 45 | _userRepository.Dispose(); 46 | } 47 | 48 | public Task FindAsync(UserLoginInfo userLoginInfo) 49 | { 50 | return _userRepository.FindAsync(userLoginInfo); 51 | } 52 | 53 | public Task FindByIdAsync(string id) 54 | { 55 | return _userRepository.FindByIdAsync(id); 56 | } 57 | 58 | public Task GenerateUserIdentityAsync(User user, string authenticationType) 59 | { 60 | return _userRepository.GenerateUserIdentityAsync(user, authenticationType); 61 | } 62 | 63 | public Task RemoveLoginAsync(string id, UserLoginInfo userLoginInfo) 64 | { 65 | return _userRepository.RemoveLoginAsync(id, userLoginInfo); 66 | } 67 | 68 | public Task RemovePasswordAsync(string id) 69 | { 70 | return _userRepository.RemovePasswordAsync(id); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Repositories/UserRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity; 2 | using OAuthAspNetWebApiRest.Domain.Contracts.Repostiories; 3 | using OAuthAspNetWebApiRest.Domain.Models; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using Microsoft.Owin; 7 | using Microsoft.AspNet.Identity.Owin; 8 | 9 | namespace OAuthAspNetWebApiRest.Data.Repositories 10 | { 11 | public class UserRepository : UserManager, IUserRepository 12 | { 13 | public UserRepository(IUserStore store) : base(store) 14 | { 15 | // Configure validation logic for usernames 16 | UserValidator = new UserValidator(this) 17 | { 18 | AllowOnlyAlphanumericUserNames = false, 19 | RequireUniqueEmail = true 20 | }; 21 | // Configure validation logic for passwords 22 | PasswordValidator = new PasswordValidator 23 | { 24 | RequiredLength = 6, 25 | RequireNonLetterOrDigit = true, 26 | RequireDigit = true, 27 | RequireLowercase = true, 28 | RequireUppercase = true, 29 | }; 30 | } 31 | public static UserRepository Create(IdentityFactoryOptions options, IOwinContext context) 32 | { 33 | var manager = new UserRepository(new AppUserStore(context.Get())); 34 | // Configure validation logic for usernames 35 | manager.UserValidator = new UserValidator(manager) 36 | { 37 | AllowOnlyAlphanumericUserNames = false, 38 | RequireUniqueEmail = true 39 | }; 40 | // Configure validation logic for passwords 41 | manager.PasswordValidator = new PasswordValidator 42 | { 43 | RequiredLength = 6, 44 | RequireNonLetterOrDigit = true, 45 | RequireDigit = true, 46 | RequireLowercase = true, 47 | RequireUppercase = true, 48 | }; 49 | var dataProtectionProvider = options.DataProtectionProvider; 50 | if (dataProtectionProvider != null) 51 | { 52 | manager.UserTokenProvider = new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity")); 53 | } 54 | return manager; 55 | } 56 | 57 | public async Task GenerateUserIdentityAsync(User user, string authenticationType) 58 | { 59 | var userIdentity = await CreateIdentityAsync(user, authenticationType); 60 | return userIdentity; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPA_Angular_AspNet_WebApi_Rest", "SPA_Angular_AspNet_WebApi_Rest\SPA_Angular_AspNet_WebApi_Rest.csproj", "{0C5FCE17-E38E-4B2D-9E4F-187535E0A18D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAspNetWebApiRest.Domain", "OAuthAspNetWebApiRest.Domain\OAuthAspNetWebApiRest.Domain.csproj", "{7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAspNetWebApiRest.Data", "OAuthAspNetWebApiRest.Data\OAuthAspNetWebApiRest.Data.csproj", "{9813BF00-14D2-470D-9F94-638910E1E976}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAspNetWebApiRest.Api", "OAuthAspNetWebApiRest.Api\OAuthAspNetWebApiRest.Api.csproj", "{80660222-8840-4BCC-82F7-FEA302EF0760}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {0C5FCE17-E38E-4B2D-9E4F-187535E0A18D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {0C5FCE17-E38E-4B2D-9E4F-187535E0A18D}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {0C5FCE17-E38E-4B2D-9E4F-187535E0A18D}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {0C5FCE17-E38E-4B2D-9E4F-187535E0A18D}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {9813BF00-14D2-470D-9F94-638910E1E976}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {9813BF00-14D2-470D-9F94-638910E1E976}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {9813BF00-14D2-470D-9F94-638910E1E976}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {9813BF00-14D2-470D-9F94-638910E1E976}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | EndGlobal 41 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/App_Start/CorsHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Net.Http; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace OAuthAspNetWebApiRest.Api.App_Start 7 | { 8 | public class CorsHandler : DelegatingHandler 9 | { 10 | private const string Origin = "Origin"; 11 | private const string AccessControlRequestMethod = "Access-Control-Request-Method"; 12 | private const string AccessControlRequestHeaders = "Access-Control-Request-Headers"; 13 | private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin"; 14 | private const string AccessControlAllowMethods = "Access-Control-Allow-Methods"; 15 | private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; 16 | 17 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 18 | { 19 | var isCorsRequest = request.Headers.Contains(Origin); 20 | var isPreflightRequest = request.Method == HttpMethod.Options; 21 | 22 | if (isCorsRequest) 23 | { 24 | if (isPreflightRequest) 25 | { 26 | var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); 27 | response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); 28 | 29 | string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault(); 30 | if (accessControlRequestMethod != null) 31 | { 32 | response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod); 33 | } 34 | 35 | string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders)); 36 | if (!string.IsNullOrEmpty(requestedHeaders)) 37 | { 38 | response.Headers.Add(AccessControlAllowHeaders, requestedHeaders); 39 | } 40 | 41 | var tcs = new TaskCompletionSource(); 42 | tcs.SetResult(response); 43 | return tcs.Task; 44 | } 45 | 46 | return base.SendAsync(request, cancellationToken).ContinueWith(t => 47 | { 48 | HttpResponseMessage resp = t.Result; 49 | resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); 50 | return resp; 51 | }); 52 | } 53 | return base.SendAsync(request, cancellationToken); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/app.module.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | Object.defineProperty(exports, "__esModule", { value: true }); 9 | var core_1 = require("@angular/core"); 10 | var platform_browser_1 = require("@angular/platform-browser"); 11 | var http_1 = require("@angular/http"); 12 | var forms_1 = require("@angular/forms"); 13 | var app_component_1 = require("./app.component"); 14 | var app_routing_1 = require("./app.routing"); 15 | var product_service_1 = require("./services/product.service"); 16 | var alert_component_1 = require("./directives/alert-component/alert.component"); 17 | var auth_guard_1 = require("./guards/auth.guard"); 18 | var alert_service_1 = require("./services/alert.service"); 19 | var authentication_service_1 = require("./services/authentication.service"); 20 | var user_service_1 = require("./services/user.service"); 21 | var home_component_1 = require("./home-component/home.component"); 22 | var login_component_1 = require("./login-component/login.component"); 23 | var register_component_1 = require("./register-component/register.component"); 24 | var AppModule = (function () { 25 | function AppModule() { 26 | } 27 | return AppModule; 28 | }()); 29 | AppModule = __decorate([ 30 | core_1.NgModule({ 31 | imports: [ 32 | platform_browser_1.BrowserModule, 33 | forms_1.FormsModule, 34 | app_routing_1.routing, 35 | http_1.HttpModule, 36 | http_1.JsonpModule, 37 | ], 38 | declarations: [ 39 | app_component_1.AppComponent, 40 | alert_component_1.AlertComponent, 41 | home_component_1.HomeComponent, 42 | login_component_1.LoginComponent, 43 | register_component_1.RegisterComponent 44 | ], 45 | providers: [ 46 | auth_guard_1.AuthGuard, 47 | alert_service_1.AlertService, 48 | authentication_service_1.AuthenticationService, 49 | user_service_1.UserService, 50 | product_service_1.ProductService 51 | ], 52 | bootstrap: [app_component_1.AppComponent] 53 | }) 54 | ], AppModule); 55 | exports.AppModule = AppModule; 56 | //# sourceMappingURL=app.module.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/login-component/login.component.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var router_1 = require("@angular/router"); 14 | var authentication_service_1 = require("../services/authentication.service"); 15 | var alert_service_1 = require("../services/alert.service"); 16 | var LoginComponent = (function () { 17 | function LoginComponent(route, router, authenticationService, alertService) { 18 | this.route = route; 19 | this.router = router; 20 | this.authenticationService = authenticationService; 21 | this.alertService = alertService; 22 | this.model = {}; 23 | this.loading = false; 24 | } 25 | LoginComponent.prototype.ngOnInit = function () { 26 | // reset login status 27 | this.authenticationService.logout(); 28 | // get return url from route parameters or default to '/' 29 | this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; 30 | }; 31 | LoginComponent.prototype.login = function () { 32 | var _this = this; 33 | this.loading = true; 34 | this.authenticationService.login(this.model.username, this.model.password) 35 | .then(function (data) { 36 | _this.router.navigate([_this.returnUrl]); 37 | }) 38 | .catch(function (error) { 39 | _this.alertService.error(error); 40 | _this.loading = false; 41 | _this.router.navigate(['/']); 42 | }); 43 | }; 44 | return LoginComponent; 45 | }()); 46 | LoginComponent = __decorate([ 47 | core_1.Component({ 48 | moduleId: module.id, 49 | templateUrl: 'login.component.html' 50 | }), 51 | __metadata("design:paramtypes", [router_1.ActivatedRoute, 52 | router_1.Router, 53 | authentication_service_1.AuthenticationService, 54 | alert_service_1.AlertService]) 55 | ], LoginComponent); 56 | exports.LoginComponent = LoginComponent; 57 | //# sourceMappingURL=login.component.js.map -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/alert.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var router_1 = require("@angular/router"); 14 | var Subject_1 = require("rxjs/Subject"); 15 | var AlertService = (function () { 16 | function AlertService(router) { 17 | var _this = this; 18 | this.router = router; 19 | this.subject = new Subject_1.Subject(); 20 | this.keepAfterNavigationChange = false; 21 | // clear alert message on route change 22 | router.events.subscribe(function (event) { 23 | if (event instanceof router_1.NavigationStart) { 24 | if (_this.keepAfterNavigationChange) { 25 | // only keep for a single location change 26 | _this.keepAfterNavigationChange = false; 27 | } 28 | else { 29 | // clear alert 30 | _this.subject.next(); 31 | } 32 | } 33 | }); 34 | } 35 | AlertService.prototype.success = function (message, keepAfterNavigationChange) { 36 | if (keepAfterNavigationChange === void 0) { keepAfterNavigationChange = false; } 37 | this.keepAfterNavigationChange = keepAfterNavigationChange; 38 | this.subject.next({ type: 'success', text: message }); 39 | }; 40 | AlertService.prototype.error = function (message, keepAfterNavigationChange) { 41 | if (keepAfterNavigationChange === void 0) { keepAfterNavigationChange = false; } 42 | this.keepAfterNavigationChange = keepAfterNavigationChange; 43 | this.subject.next({ type: 'error', text: message }); 44 | }; 45 | AlertService.prototype.getMessage = function () { 46 | return this.subject.asObservable(); 47 | }; 48 | return AlertService; 49 | }()); 50 | AlertService = __decorate([ 51 | core_1.Injectable(), 52 | __metadata("design:paramtypes", [router_1.Router]) 53 | ], AlertService); 54 | exports.AlertService = AlertService; 55 | //# sourceMappingURL=alert.service.js.map -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Models/AccountBindingModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using Newtonsoft.Json; 4 | 5 | namespace OAuthAspNetWebApiRest.Api.Models 6 | { 7 | // Models used as parameters to AccountController actions. 8 | 9 | public class AddExternalLoginBindingModel 10 | { 11 | [Required] 12 | [Display(Name = "External access token")] 13 | public string ExternalAccessToken { get; set; } 14 | } 15 | 16 | public class ChangePasswordBindingModel 17 | { 18 | [Required] 19 | [DataType(DataType.Password)] 20 | [Display(Name = "Current password")] 21 | public string OldPassword { get; set; } 22 | 23 | [Required] 24 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 25 | [DataType(DataType.Password)] 26 | [Display(Name = "New password")] 27 | public string NewPassword { get; set; } 28 | 29 | [DataType(DataType.Password)] 30 | [Display(Name = "Confirm new password")] 31 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 32 | public string ConfirmPassword { get; set; } 33 | } 34 | 35 | public class RegisterBindingModel 36 | { 37 | [Required] 38 | [Display(Name = "Email")] 39 | public string Email { get; set; } 40 | 41 | [Required] 42 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 43 | [DataType(DataType.Password)] 44 | [Display(Name = "Password")] 45 | public string Password { get; set; } 46 | 47 | [DataType(DataType.Password)] 48 | [Display(Name = "Confirm password")] 49 | [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 50 | public string ConfirmPassword { get; set; } 51 | } 52 | 53 | public class RegisterExternalBindingModel 54 | { 55 | [Required] 56 | [Display(Name = "Email")] 57 | public string Email { get; set; } 58 | } 59 | 60 | public class RemoveLoginBindingModel 61 | { 62 | [Required] 63 | [Display(Name = "Login provider")] 64 | public string LoginProvider { get; set; } 65 | 66 | [Required] 67 | [Display(Name = "Provider key")] 68 | public string ProviderKey { get; set; } 69 | } 70 | 71 | public class SetPasswordBindingModel 72 | { 73 | [Required] 74 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 75 | [DataType(DataType.Password)] 76 | [Display(Name = "New password")] 77 | public string NewPassword { get; set; } 78 | 79 | [DataType(DataType.Password)] 80 | [Display(Name = "Confirm new password")] 81 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 82 | public string ConfirmPassword { get; set; } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/register-component/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |

Faça seu Registro

3 |
4 |
5 | 6 | 7 |
O E-mail é obrigatório
8 |
9 |
10 | 11 | 12 |
O nome de usuário é obrigatório
13 |
14 |
15 | 16 | 17 |
A Senha é obrigatória
18 |
19 |
20 | 21 | 22 |
Confirmação de Senha é requerida
23 |
Confirmação de Senha deve ser igual a Senha
24 |
25 |
26 | 27 | 28 | Cancel 29 |
30 |
31 |
-------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/app/services/authentication.service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { 3 | var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; 4 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 5 | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 6 | return c > 3 && r && Object.defineProperty(target, key, r), r; 7 | }; 8 | var __metadata = (this && this.__metadata) || function (k, v) { 9 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); 10 | }; 11 | Object.defineProperty(exports, "__esModule", { value: true }); 12 | var core_1 = require("@angular/core"); 13 | var http_1 = require("@angular/http"); 14 | require("rxjs/add/operator/map"); 15 | var AuthenticationService = (function () { 16 | function AuthenticationService(http) { 17 | this.http = http; 18 | this.authenticateUrl = "http://localhost:20835"; 19 | } 20 | AuthenticationService.prototype.login = function (username, password) { 21 | var body = "username=" + username + "&password=" + password + "&grant_type=password"; 22 | console.log(body); 23 | return this.http.post(this.authenticateUrl + "/Token", body, this.headerOptions()) 24 | .toPromise() 25 | .then(function (response) { 26 | // login successful if there's a jwt token in the response 27 | var user = response.json(); 28 | if (user && user.access_token) { 29 | // store user details and jwt token in local storage to keep user logged in between page refreshes 30 | localStorage.setItem('currentUser', JSON.stringify(user)); 31 | } 32 | }) 33 | .catch(this.handleError); 34 | }; 35 | AuthenticationService.prototype.logout = function () { 36 | // remove user from local storage to log user out 37 | localStorage.removeItem('currentUser'); 38 | }; 39 | AuthenticationService.prototype.handleError = function (error) { 40 | console.error('An error occurred', error); 41 | return Promise.reject(error.message || error); 42 | }; 43 | AuthenticationService.prototype.headerOptions = function () { 44 | var headers = new http_1.Headers({ 45 | 'Content-Type': 'application/x-www-form-urlencoded', withCredentials: true 46 | }); 47 | return new http_1.RequestOptions({ headers: headers }); 48 | }; 49 | AuthenticationService.prototype.urlEncode = function (obj) { 50 | var urlSearchParams = new http_1.URLSearchParams(); 51 | for (var key in obj) { 52 | urlSearchParams.append(key, obj[key]); 53 | } 54 | return urlSearchParams.toString(); 55 | }; 56 | return AuthenticationService; 57 | }()); 58 | AuthenticationService = __decorate([ 59 | core_1.Injectable(), 60 | __metadata("design:paramtypes", [http_1.Http]) 61 | ], AuthenticationService); 62 | exports.AuthenticationService = AuthenticationService; 63 | //# sourceMappingURL=authentication.service.js.map -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Controllers/BaseAuthApiController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Identity; 2 | using Microsoft.Owin.Security; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Security.Claims; 9 | using System.Security.Cryptography; 10 | using System.Web; 11 | using System.Web.Http; 12 | 13 | namespace OAuthAspNetWebApiRest.Api.Controllers 14 | { 15 | public class BaseAuthApiController : ApiController 16 | { 17 | 18 | #region Helpers 19 | 20 | public IAuthenticationManager Authentication 21 | { 22 | get { return Request.GetOwinContext().Authentication; } 23 | } 24 | 25 | public IHttpActionResult GetErrorResult(IdentityResult result) 26 | { 27 | if (result == null) 28 | { 29 | return InternalServerError(); 30 | } 31 | 32 | if (!result.Succeeded) 33 | { 34 | if (result.Errors != null) 35 | { 36 | foreach (string error in result.Errors) 37 | { 38 | ModelState.AddModelError("", error); 39 | } 40 | } 41 | 42 | if (ModelState.IsValid) 43 | { 44 | // No ModelState errors are available to send, so just return an empty BadRequest. 45 | return BadRequest(); 46 | } 47 | 48 | return BadRequest(ModelState); 49 | } 50 | 51 | return null; 52 | } 53 | 54 | internal class ExternalLoginData 55 | { 56 | public string LoginProvider { get; set; } 57 | public string ProviderKey { get; set; } 58 | public string UserName { get; set; } 59 | 60 | public IList GetClaims() 61 | { 62 | IList claims = new List(); 63 | claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); 64 | 65 | if (UserName != null) 66 | { 67 | claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); 68 | } 69 | 70 | return claims; 71 | } 72 | 73 | public static ExternalLoginData FromIdentity(ClaimsIdentity identity) 74 | { 75 | if (identity == null) 76 | { 77 | return null; 78 | } 79 | 80 | Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); 81 | 82 | if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) 83 | || String.IsNullOrEmpty(providerKeyClaim.Value)) 84 | { 85 | return null; 86 | } 87 | 88 | if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) 89 | { 90 | return null; 91 | } 92 | 93 | return new ExternalLoginData 94 | { 95 | LoginProvider = providerKeyClaim.Issuer, 96 | ProviderKey = providerKeyClaim.Value, 97 | UserName = identity.FindFirstValue(ClaimTypes.Name) 98 | }; 99 | } 100 | } 101 | 102 | internal static class RandomOAuthStateGenerator 103 | { 104 | private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); 105 | 106 | public static string Generate(int strengthInBits) 107 | { 108 | const int bitsPerByte = 8; 109 | 110 | if (strengthInBits % bitsPerByte != 0) 111 | { 112 | throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); 113 | } 114 | 115 | int strengthInBytes = strengthInBits / bitsPerByte; 116 | 117 | byte[] data = new byte[strengthInBytes]; 118 | _random.GetBytes(data); 119 | return HttpServerUtility.UrlTokenEncode(data); 120 | } 121 | } 122 | 123 | #endregion 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Providers/ApplicationOAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNet.Identity; 7 | using Microsoft.AspNet.Identity.EntityFramework; 8 | using Microsoft.AspNet.Identity.Owin; 9 | using Microsoft.Owin.Security; 10 | using Microsoft.Owin.Security.Cookies; 11 | using Microsoft.Owin.Security.OAuth; 12 | using OAuthAspNetWebApiRest.Api.Models; 13 | using OAuthAspNetWebApiRest.Data.Repositories; 14 | using OAuthAspNetWebApiRest.Domain.Models; 15 | 16 | namespace OAuthAspNetWebApiRest.Api.Providers 17 | { 18 | public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 19 | { 20 | private readonly string _publicClientId; 21 | 22 | public ApplicationOAuthProvider(string publicClientId) 23 | { 24 | if (publicClientId == null) 25 | { 26 | throw new ArgumentNullException("publicClientId"); 27 | } 28 | 29 | _publicClientId = publicClientId; 30 | } 31 | public override Task MatchEndpoint(OAuthMatchEndpointContext context) 32 | { 33 | if (context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint) 34 | { 35 | context.OwinContext.Response.StatusCode = 200; 36 | context.RequestCompleted(); 37 | 38 | return Task.FromResult(null); 39 | } 40 | 41 | return base.MatchEndpoint(context); 42 | } 43 | public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 44 | { 45 | var userManager = context.OwinContext.GetUserManager(); 46 | 47 | User user = await userManager.FindAsync(context.UserName, context.Password); 48 | 49 | if (user == null) 50 | { 51 | context.SetError("invalid_grant", "The user name or password is incorrect."); 52 | return; 53 | } 54 | 55 | ClaimsIdentity oAuthIdentity = await userManager.GenerateUserIdentityAsync(user, OAuthDefaults.AuthenticationType); 56 | ClaimsIdentity cookiesIdentity = await userManager.GenerateUserIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); 57 | 58 | AuthenticationProperties properties = CreateProperties(user.UserName); 59 | AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 60 | context.Validated(ticket); 61 | context.Request.Context.Authentication.SignIn(cookiesIdentity); 62 | } 63 | 64 | public override Task TokenEndpoint(OAuthTokenEndpointContext context) 65 | { 66 | foreach (KeyValuePair property in context.Properties.Dictionary) 67 | { 68 | context.AdditionalResponseParameters.Add(property.Key, property.Value); 69 | } 70 | 71 | return Task.FromResult(null); 72 | } 73 | 74 | public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 75 | { 76 | // Resource owner password credentials does not provide a client ID. 77 | if (context.ClientId == null) 78 | { 79 | context.Validated(); 80 | } 81 | 82 | return Task.FromResult(null); 83 | } 84 | 85 | public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) 86 | { 87 | if (context.ClientId == _publicClientId) 88 | { 89 | Uri expectedRootUri = new Uri(context.Request.Uri, "/"); 90 | 91 | if (expectedRootUri.AbsoluteUri == context.RedirectUri) 92 | { 93 | context.Validated(); 94 | } 95 | } 96 | 97 | return Task.FromResult(null); 98 | } 99 | 100 | public static AuthenticationProperties CreateProperties(string userName) 101 | { 102 | IDictionary data = new Dictionary 103 | { 104 | { "userName", userName } 105 | }; 106 | return new AuthenticationProperties(data); 107 | } 108 | } 109 | } -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Domain/OAuthAspNetWebApiRest.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A} 8 | Library 9 | Properties 10 | OAuthAspNetWebApiRest.Domain 11 | OAuthAspNetWebApiRest.Domain 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 43 | True 44 | 45 | 46 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 47 | True 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 83 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/201705312114068_FirstMigration.cs: -------------------------------------------------------------------------------- 1 | namespace OAuthAspNetWebApiRest.Data.Migrations 2 | { 3 | using System; 4 | using System.Data.Entity.Migrations; 5 | 6 | public partial class FirstMigration : DbMigration 7 | { 8 | public override void Up() 9 | { 10 | CreateTable( 11 | "dbo.Products", 12 | c => new 13 | { 14 | Id = c.Int(nullable: false, identity: true), 15 | Name = c.String(), 16 | Quantity = c.Decimal(nullable: false, precision: 18, scale: 2), 17 | }) 18 | .PrimaryKey(t => t.Id); 19 | 20 | CreateTable( 21 | "dbo.AspNetRoles", 22 | c => new 23 | { 24 | Id = c.String(nullable: false, maxLength: 128), 25 | Name = c.String(nullable: false, maxLength: 256), 26 | }) 27 | .PrimaryKey(t => t.Id) 28 | .Index(t => t.Name, unique: true, name: "RoleNameIndex"); 29 | 30 | CreateTable( 31 | "dbo.AspNetUserRoles", 32 | c => new 33 | { 34 | UserId = c.String(nullable: false, maxLength: 128), 35 | RoleId = c.String(nullable: false, maxLength: 128), 36 | }) 37 | .PrimaryKey(t => new { t.UserId, t.RoleId }) 38 | .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) 39 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 40 | .Index(t => t.UserId) 41 | .Index(t => t.RoleId); 42 | 43 | CreateTable( 44 | "dbo.AspNetUsers", 45 | c => new 46 | { 47 | Id = c.String(nullable: false, maxLength: 128), 48 | Email = c.String(maxLength: 256), 49 | EmailConfirmed = c.Boolean(nullable: false), 50 | PasswordHash = c.String(), 51 | SecurityStamp = c.String(), 52 | PhoneNumber = c.String(), 53 | PhoneNumberConfirmed = c.Boolean(nullable: false), 54 | TwoFactorEnabled = c.Boolean(nullable: false), 55 | LockoutEndDateUtc = c.DateTime(), 56 | LockoutEnabled = c.Boolean(nullable: false), 57 | AccessFailedCount = c.Int(nullable: false), 58 | UserName = c.String(nullable: false, maxLength: 256), 59 | }) 60 | .PrimaryKey(t => t.Id) 61 | .Index(t => t.UserName, unique: true, name: "UserNameIndex"); 62 | 63 | CreateTable( 64 | "dbo.AspNetUserClaims", 65 | c => new 66 | { 67 | Id = c.Int(nullable: false, identity: true), 68 | UserId = c.String(nullable: false, maxLength: 128), 69 | ClaimType = c.String(), 70 | ClaimValue = c.String(), 71 | }) 72 | .PrimaryKey(t => t.Id) 73 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 74 | .Index(t => t.UserId); 75 | 76 | CreateTable( 77 | "dbo.AspNetUserLogins", 78 | c => new 79 | { 80 | LoginProvider = c.String(nullable: false, maxLength: 128), 81 | ProviderKey = c.String(nullable: false, maxLength: 128), 82 | UserId = c.String(nullable: false, maxLength: 128), 83 | }) 84 | .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) 85 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 86 | .Index(t => t.UserId); 87 | 88 | } 89 | 90 | public override void Down() 91 | { 92 | DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); 93 | DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); 94 | DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); 95 | DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); 96 | DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); 97 | DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); 98 | DropIndex("dbo.AspNetUsers", "UserNameIndex"); 99 | DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); 100 | DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); 101 | DropIndex("dbo.AspNetRoles", "RoleNameIndex"); 102 | DropTable("dbo.AspNetUserLogins"); 103 | DropTable("dbo.AspNetUserClaims"); 104 | DropTable("dbo.AspNetUsers"); 105 | DropTable("dbo.AspNetUserRoles"); 106 | DropTable("dbo.AspNetRoles"); 107 | DropTable("dbo.Products"); 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Web.config: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/OAuthAspNetWebApiRest.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9813BF00-14D2-470D-9F94-638910E1E976} 8 | Library 9 | Properties 10 | OAuthAspNetWebApiRest.Data 11 | OAuthAspNetWebApiRest.Data 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 43 | True 44 | 45 | 46 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 47 | True 48 | 49 | 50 | ..\packages\Microsoft.AspNet.Identity.Owin.2.2.1\lib\net45\Microsoft.AspNet.Identity.Owin.dll 51 | True 52 | 53 | 54 | ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll 55 | True 56 | 57 | 58 | ..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll 59 | True 60 | 61 | 62 | ..\packages\Microsoft.Owin.Security.Cookies.3.1.0\lib\net45\Microsoft.Owin.Security.Cookies.dll 63 | True 64 | 65 | 66 | ..\packages\Microsoft.Owin.Security.OAuth.3.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll 67 | True 68 | 69 | 70 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 71 | True 72 | 73 | 74 | ..\packages\Owin.1.0\lib\net40\Owin.dll 75 | True 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 201705312114068_FirstMigration.cs 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | {7e6a64ea-4631-4640-abe2-0184ddb4fa1a} 103 | OAuthAspNetWebApiRest.Domain 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 201705312114068_FirstMigration.cs 113 | 114 | 115 | 116 | 123 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/201705312114068_FirstMigration.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | H4sIAAAAAAAEAN1c227juBm+L9B3EHTVFlkrh85gGti7yDpJG3RyaJzZ9m5AS7QjjERpJSqbYLFP1os+Ul+hPyVKoihSlmxZcooFFjEP33/gR/In9XP+++//TH949T3jBUexG5CZeTI5Ng1M7MBxyXpmJnT13Sfzh+9//7vpleO/Gj/l7c5YO+hJ4pn5TGl4blmx/Yx9FE98146COFjRiR34FnIC6/T4+C/WyYmFAcIELMOYPiaEuj5Of8DPeUBsHNIEebeBg72Yl0PNIkU17pCP4xDZeGbeXyT0+SIO7zD9J15ehO4jjunkElFkGheei0CjBfZWpoEICSiioO/5lxgvaBSQ9SKEAuQ9vYUY2q2QF2Nux3nZvK1Jx6fMJKvsmEPZSUwDvyPgyRn3kSV338rTZuFD8OIVeJu+MatTT87MhyhwEpuahizrfO5FrJ3Wz9DYJZNsmCYc5shoanxU0AbYxf47MuaJR5MIzwhOaIS8I+MhWXqu/Xf89hR8w2RGEs8TDQAToK5SAEUgPcQRfXvEK27WjWMaVrWfJXcsugl9MotvCD07NY07EI6WHi74IXhnQYMI/xUTHCGKnQdEKY4Iw8Cph2vSJVns/7k0ICTMMdO4Ra+fMVnT55kJf5rGtfuKnbyEa/CFuDAloRONErxJyD8SxJXJBF1i2/WRZxoPEfzF5/kn01jYiBmpslgUMLVK9jRyKnfCY+DhJmLdFrTNCDPJO04yyOsI4H4Jom8TEfHIaN2vJNxpW8KdnSxXZ58+fETO2cc/47MPw5NPQYeT00+t6NA4fJ1JePrhYy9S79CLu06HXpIPi3EUm8Yj9tLa+NkNsyW7Mt5febPrKPDZ7yq/stqviyCJbGZMoG3yhKI1pjtSmkH1T+sc9fCpzTSt01vZlBm0zUzIRQw9G3J99yu3NeOYG3bdlRnG/8mWPBwPrsAvXg/LYgspEO2u3MjHhZU/BkBCRDrr/IDiGFYF528oft57WLHAdhIBWRcU+eHepT08BwTfJf6STYfhZPU2NE+/BNfIhmjxirBeO+N9DuxvQUKviAMnHfyF2kV0Bz+fXL89QC/qXNg2juNrIDN25gEc5jbF0M1wbMUaOyyZe8j11XEJU+9rXl8GJEJxLRIR61QhSJMmn4O1Sxo0yeslTbJitSa8rqsmDKFBEV4t6ZGWqtXIqnoLyVL/9h+TpbCHH5Qd+mF3rIguHT4mdO8bRyrpJ+QlfYvaajakc7z/2ZDCHv5sSNWE4hfXYSFDi5NK3hjgW7VXH4I2zzlJs6GnQ8XMoYUPswbopstFHAe2m84CxR0Vv2Go6g8BlrH5uiGzRr6yAMOA6G4I1IYSsM2USXVPLrGHKTYu7OxeeI5iGzl1N4JBTgfF8h1VoVh5dVFV7k81mcB0HLFOiJ1QYpipLqH1aeES2w2Rt9FLUs+WWxizvZAh11ziEBMmcKMn2ghX31QwBQo50qBs8tDUEhjXTEQxpNQNtDK+LEc4uyoYhHKqaFbDNR6T7YVsCocMwDKF8W2kau/MBqMXPyc0Dqp8aBiPXtIRRUMvHuTsj15VhwxFr6rx74Ne2emvcUylo+B45KoePIffJuveGIpZFcsPjFhZ1AZ9KPTAUX63FIasCL+qPk+Ddvw8E/PQUB53BrnAtPqhOzaNMkTkQ198A7eaIfgtR61/NfTbACLzrAmw5OIGUP6JrAaUza4OGuV3W40q8Z29A2x+UdUIy1d0CVZgTB1b/D4oNNR/RZSp3CrKLywrKFCbEq2CcgFHwQJ5Jasa3sIplcvJuje0gebGUFPQm/u6wX5VhKgxPNe1H8tzjmksV8VAG6Og7pZLwYvG8lzXfiznBNIYrtidN+3P3c2ubqs9ET0/zRf7QlE3tbJ0MF4wtTR5Y9NbFIYuWQt5ZLzEWGRJZPPvFt2zqvwMw7JjRXJVoW0hiQYRWmOpFkSDptduFFOWsrZE7C5j7vi1ZsIuqFlwc0HSRlcfsnzxzTuwv7NO+ly6Yneshwwc5hqs81mwkV4TC2Ov7WmwdD7koUhxKT0PvMQn+rBH3zv7biT2z0raI5QJUyJKWVpHmlqSE2qxUs3rtYC1Ooqtxlg3p7ca4Er40n2Um7uPPdQjDVB92et5sIrQcPsB00Po3J6fCETH604JepT8uk1E0V3BjTaAunBxq0FLw/DuA6Xutp8ZxbNeRABe1BFDSJyogQl17VGruS0iZrWmPaKUwCJCSlUdtBTTVCpKihVb4Wk8qm7RXkI9MUVEr9e2R1akqIjQiuotsBU6y3XtURVZLCKworo9dpnSIi+bB7xnac+JO29a2eXBbruWBmM/K2M/m56QiyACCcUdsXi2QQ2Mlx8kq7Rn8J1Zld0d7cYqDYZ+Jap8za8uRI0pCHrMyif6ymLflKKgx+vG3b0ypHaYl5sU0otDvXR4n/KD9OaXYbWTddaEPXzJ3Agb/VtMsZ8RafGzN/dczJb1vMEtIu4KmJalpZinxyen0qOyw3ngZcWx4ykuIhSvvKrDNUBymcucujF9bId3K+QFRfYziv7go9c/ikjbPJByxnggNfiY5C6rp9/0MA6KLzU3xMGvM/PXtNd5emvI/kqLj4yb+Atxf06g4glGzPitnuvbr8/Vp94Dff3S3qs3//qadT0y7iNYwM6NY8mX24xw9U1MJ22yrjto0+2lzPudRZX3JkpUaRZs/7xk6dJenpbstOgqn4/shKh4ItIXXi8u1D0B2QZL+/zDgZ80ff7RzVj1c5BtVNM+BUmDgB0fgrRfe/KeI+4vivPpuw22DmtDqqX07zTR62n7HeB2SM3fghnvLKu9t91RkbTeG/aY1N57pvqhJKeXOUzj5qQPmYbe8HHunWafj5WzqUg7GyndfGj+6O7JDzEBuEV++SEQiCcYjpRQPjSBdFfih0igzRnkh8CfsbaxMdjTevsaPUu8nkYnj6UyEbwpDzz7XABn6mUA453FcGX+eMu854wQNSHVapWk7GuXOllSJ6xkoFZg2UQvVJ+lKQvOpmBNWFbcLKCbVXxfbzSLt2kWq8k2bpLNt4RG2bxNs2xNvu8Yue3K7FzVI4MNy2BTQtkB5bLXkplbm1khniYF4YBS17c3tMJyzVfxg8lU397MPmnbITO9/tEadkDhHz2FXTh21yUE+ydQCbYre1/R5oasgnwLljTKm0h3HLeYIgc2xouIuitkU6hmt7Tp6/v05ot9K1hi54bcJzRMKJiM/aVXuTJiW3mT/DT9vqrz9D5M/52YPkwANV12u31Pfkxczyn0vlbcqmggWIzA70TZWFJ2N7p+K5DuAtISiLuvCG2esB96ABbfkwV6wdvoBvT7jNfIfivv0HQgmwei6vbppYvWEfJjjlH2h5/AYcd//f5/JHTEfPtXAAA= 122 | 123 | 124 | dbo 125 | 126 | -------------------------------------------------------------------------------- /SPA_Angular_AspNet_WebApi_Rest/SPA_Angular_AspNet_WebApi_Rest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Debug 9 | AnyCPU 10 | 11 | 12 | 2.0 13 | {0C5FCE17-E38E-4B2D-9E4F-187535E0A18D} 14 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} 15 | Library 16 | Properties 17 | SPA_Angular_AspNet_WebApi_Rest 18 | SPA_Angular_AspNet_WebApi_Rest 19 | v4.6.1 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 2.1 29 | 30 | 31 | true 32 | full 33 | false 34 | bin\ 35 | DEBUG;TRACE 36 | prompt 37 | 4 38 | 39 | 40 | pdbonly 41 | true 42 | bin\ 43 | TRACE 44 | prompt 45 | 4 46 | 47 | 48 | 49 | ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.4\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll 50 | True 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | Web.config 81 | 82 | 83 | Web.config 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 10.0 138 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | True 149 | True 150 | 12480 151 | / 152 | http://localhost:12480/ 153 | False 154 | False 155 | 156 | 157 | False 158 | 159 | 160 | 161 | 162 | 163 | 164 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 165 | 166 | 167 | 168 | 169 | 176 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Security.Claims; 5 | using System.Security.Cryptography; 6 | using System.Threading.Tasks; 7 | using System.Web; 8 | using System.Web.Http; 9 | using Microsoft.AspNet.Identity; 10 | using Microsoft.AspNet.Identity.EntityFramework; 11 | using Microsoft.Owin.Security; 12 | using Microsoft.Owin.Security.Cookies; 13 | using Microsoft.Owin.Security.OAuth; 14 | using OAuthAspNetWebApiRest.Api.Models; 15 | using OAuthAspNetWebApiRest.Api.Providers; 16 | using OAuthAspNetWebApiRest.Api.Results; 17 | using OAuthAspNetWebApiRest.Domain.Contracts.Services; 18 | using OAuthAspNetWebApiRest.Domain.Models; 19 | 20 | namespace OAuthAspNetWebApiRest.Api.Controllers 21 | { 22 | [Authorize] 23 | [RoutePrefix("api/Account")] 24 | public class AccountController : BaseAuthApiController 25 | { 26 | private const string LocalLoginProvider = "Local"; 27 | private IUserService _userService; 28 | 29 | public AccountController(IUserService userManager) 30 | { 31 | _userService = userManager; 32 | } 33 | 34 | public ISecureDataFormat AccessTokenFormat { get; private set; } 35 | 36 | [HttpGet] 37 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 38 | [Route("UserInfo")] 39 | public UserInfoViewModel GetUserInfo() 40 | { 41 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 42 | 43 | return new UserInfoViewModel 44 | { 45 | Email = User.Identity.GetUserName(), 46 | HasRegistered = externalLogin == null, 47 | LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null 48 | }; 49 | } 50 | 51 | [HttpPost] 52 | [Route("Logout")] 53 | public IHttpActionResult Logout() 54 | { 55 | Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); 56 | return Ok(); 57 | } 58 | 59 | // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true 60 | [HttpGet] 61 | [Route("ManageInfo")] 62 | public async Task GetManageInfo(string returnUrl, bool generateState = false) 63 | { 64 | IdentityUser user = await _userService.FindByIdAsync(User.Identity.GetUserId()); 65 | 66 | if (user == null) 67 | { 68 | return null; 69 | } 70 | 71 | List logins = new List(); 72 | 73 | foreach (IdentityUserLogin linkedAccount in user.Logins) 74 | { 75 | logins.Add(new UserLoginInfoViewModel 76 | { 77 | LoginProvider = linkedAccount.LoginProvider, 78 | ProviderKey = linkedAccount.ProviderKey 79 | }); 80 | } 81 | 82 | if (user.PasswordHash != null) 83 | { 84 | logins.Add(new UserLoginInfoViewModel 85 | { 86 | LoginProvider = LocalLoginProvider, 87 | ProviderKey = user.UserName, 88 | }); 89 | } 90 | 91 | return new ManageInfoViewModel 92 | { 93 | LocalLoginProvider = LocalLoginProvider, 94 | Email = user.UserName, 95 | Logins = logins, 96 | ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) 97 | }; 98 | } 99 | 100 | [HttpPost] 101 | [Route("ChangePassword")] 102 | public async Task ChangePassword(ChangePasswordBindingModel model) 103 | { 104 | if (!ModelState.IsValid) 105 | { 106 | return BadRequest(ModelState); 107 | } 108 | 109 | IdentityResult result = await _userService.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, 110 | model.NewPassword); 111 | 112 | if (!result.Succeeded) 113 | { 114 | return GetErrorResult(result); 115 | } 116 | 117 | return Ok(); 118 | } 119 | 120 | [HttpPost] 121 | [Route("SetPassword")] 122 | public async Task SetPassword(SetPasswordBindingModel model) 123 | { 124 | if (!ModelState.IsValid) 125 | { 126 | return BadRequest(ModelState); 127 | } 128 | 129 | IdentityResult result = await _userService.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); 130 | 131 | if (!result.Succeeded) 132 | { 133 | return GetErrorResult(result); 134 | } 135 | 136 | return Ok(); 137 | } 138 | 139 | [HttpPost] 140 | [Route("AddExternalLogin")] 141 | public async Task AddExternalLogin(AddExternalLoginBindingModel model) 142 | { 143 | if (!ModelState.IsValid) 144 | { 145 | return BadRequest(ModelState); 146 | } 147 | 148 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 149 | 150 | AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); 151 | 152 | if (ticket == null || ticket.Identity == null || (ticket.Properties != null 153 | && ticket.Properties.ExpiresUtc.HasValue 154 | && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) 155 | { 156 | return BadRequest("External login failure."); 157 | } 158 | 159 | ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); 160 | 161 | if (externalData == null) 162 | { 163 | return BadRequest("The external login is already associated with an account."); 164 | } 165 | 166 | IdentityResult result = await _userService.AddLoginAsync(User.Identity.GetUserId(), 167 | new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); 168 | 169 | if (!result.Succeeded) 170 | { 171 | return GetErrorResult(result); 172 | } 173 | 174 | return Ok(); 175 | } 176 | 177 | [HttpPost] 178 | [Route("RemoveLogin")] 179 | public async Task RemoveLogin(RemoveLoginBindingModel model) 180 | { 181 | if (!ModelState.IsValid) 182 | { 183 | return BadRequest(ModelState); 184 | } 185 | 186 | IdentityResult result; 187 | 188 | if (model.LoginProvider == LocalLoginProvider) 189 | { 190 | result = await _userService.RemovePasswordAsync(User.Identity.GetUserId()); 191 | } 192 | else 193 | { 194 | result = await _userService.RemoveLoginAsync(User.Identity.GetUserId(), 195 | new UserLoginInfo(model.LoginProvider, model.ProviderKey)); 196 | } 197 | 198 | if (!result.Succeeded) 199 | { 200 | return GetErrorResult(result); 201 | } 202 | 203 | return Ok(); 204 | } 205 | 206 | [HttpGet] 207 | [OverrideAuthentication] 208 | [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] 209 | [AllowAnonymous] 210 | [Route("ExternalLogin", Name = "ExternalLogin")] 211 | public async Task GetExternalLogin(string provider, string error = null) 212 | { 213 | if (error != null) 214 | { 215 | return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); 216 | } 217 | 218 | if (!User.Identity.IsAuthenticated) 219 | { 220 | return new ChallengeResult(provider, this); 221 | } 222 | 223 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 224 | 225 | if (externalLogin == null) 226 | { 227 | return InternalServerError(); 228 | } 229 | 230 | if (externalLogin.LoginProvider != provider) 231 | { 232 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 233 | return new ChallengeResult(provider, this); 234 | } 235 | 236 | User user = await _userService.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, 237 | externalLogin.ProviderKey)); 238 | 239 | bool hasRegistered = user != null; 240 | 241 | if (hasRegistered) 242 | { 243 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 244 | 245 | ClaimsIdentity oAuthIdentity = await _userService.GenerateUserIdentityAsync(user, OAuthDefaults.AuthenticationType); 246 | ClaimsIdentity cookieIdentity = await _userService.GenerateUserIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); 247 | 248 | AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 249 | Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); 250 | } 251 | else 252 | { 253 | IEnumerable claims = externalLogin.GetClaims(); 254 | ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); 255 | Authentication.SignIn(identity); 256 | } 257 | 258 | return Ok(); 259 | } 260 | 261 | // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true 262 | [HttpGet] 263 | [AllowAnonymous] 264 | [Route("ExternalLogins")] 265 | public IEnumerable GetExternalLogins(string returnUrl, bool generateState = false) 266 | { 267 | IEnumerable descriptions = Authentication.GetExternalAuthenticationTypes(); 268 | List logins = new List(); 269 | 270 | string state; 271 | 272 | if (generateState) 273 | { 274 | const int strengthInBits = 256; 275 | state = RandomOAuthStateGenerator.Generate(strengthInBits); 276 | } 277 | else 278 | { 279 | state = null; 280 | } 281 | 282 | foreach (AuthenticationDescription description in descriptions) 283 | { 284 | ExternalLoginViewModel login = new ExternalLoginViewModel 285 | { 286 | Name = description.Caption, 287 | Url = Url.Route("ExternalLogin", new 288 | { 289 | provider = description.AuthenticationType, 290 | response_type = "token", 291 | client_id = Startup.PublicClientId, 292 | redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, 293 | state = state 294 | }), 295 | State = state 296 | }; 297 | logins.Add(login); 298 | } 299 | 300 | return logins; 301 | } 302 | 303 | [HttpPost] 304 | [AllowAnonymous] 305 | [Route("Register")] 306 | public async Task Register(RegisterBindingModel model) 307 | { 308 | if (!ModelState.IsValid) 309 | { 310 | return BadRequest(ModelState); 311 | } 312 | 313 | var user = new User() { UserName = model.Email, Email = model.Email }; 314 | 315 | IdentityResult result = await _userService.CreateAsync(user, model.Password); 316 | 317 | if (!result.Succeeded) 318 | { 319 | return GetErrorResult(result); 320 | } 321 | 322 | return Ok(); 323 | } 324 | 325 | [HttpPost] 326 | [OverrideAuthentication] 327 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 328 | [Route("RegisterExternal")] 329 | public async Task RegisterExternal(RegisterExternalBindingModel model) 330 | { 331 | if (!ModelState.IsValid) 332 | { 333 | return BadRequest(ModelState); 334 | } 335 | 336 | var info = await Authentication.GetExternalLoginInfoAsync(); 337 | if (info == null) 338 | { 339 | return InternalServerError(); 340 | } 341 | 342 | var user = new User() { UserName = model.Email, Email = model.Email }; 343 | 344 | IdentityResult result = await _userService.CreateAsync(user); 345 | if (!result.Succeeded) 346 | { 347 | return GetErrorResult(result); 348 | } 349 | 350 | result = await _userService.AddLoginAsync(user.Id, info.Login); 351 | if (!result.Succeeded) 352 | { 353 | return GetErrorResult(result); 354 | } 355 | return Ok(); 356 | } 357 | 358 | protected override void Dispose(bool disposing) 359 | { 360 | if (disposing && _userService != null) 361 | { 362 | _userService.Dispose(); 363 | _userService = null; 364 | } 365 | 366 | base.Dispose(disposing); 367 | } 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/OAuthAspNetWebApiRest.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Debug 8 | AnyCPU 9 | 10 | 11 | 2.0 12 | {80660222-8840-4BCC-82F7-FEA302EF0760} 13 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} 14 | Library 15 | Properties 16 | OAuthAspNetWebApiRest.Api 17 | OAuthAspNetWebApiRest.Api 18 | v4.6.1 19 | false 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | true 31 | full 32 | false 33 | bin\ 34 | DEBUG;TRACE 35 | prompt 36 | 4 37 | 38 | 39 | pdbonly 40 | true 41 | bin\ 42 | TRACE 43 | prompt 44 | 4 45 | 46 | 47 | 48 | ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll 49 | True 50 | 51 | 52 | 53 | ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll 54 | True 55 | 56 | 57 | ..\packages\Microsoft.Owin.Cors.3.1.0\lib\net45\Microsoft.Owin.Cors.dll 58 | 59 | 60 | ..\packages\Microsoft.Owin.Host.SystemWeb.3.1.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll 61 | True 62 | 63 | 64 | ..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll 65 | True 66 | 67 | 68 | ..\packages\Microsoft.Owin.Security.Cookies.3.1.0\lib\net45\Microsoft.Owin.Security.Cookies.dll 69 | True 70 | 71 | 72 | ..\packages\Microsoft.Owin.Security.OAuth.3.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll 73 | True 74 | 75 | 76 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 77 | True 78 | 79 | 80 | ..\packages\SimpleInjector.4.0.7\lib\net45\SimpleInjector.dll 81 | True 82 | 83 | 84 | ..\packages\SimpleInjector.Integration.Web.4.0.7\lib\net40\SimpleInjector.Integration.Web.dll 85 | True 86 | 87 | 88 | ..\packages\SimpleInjector.Integration.WebApi.4.0.7\lib\net45\SimpleInjector.Integration.WebApi.dll 89 | True 90 | 91 | 92 | 93 | 94 | 95 | ..\packages\Microsoft.AspNet.Cors.5.2.3\lib\net45\System.Web.Cors.dll 96 | True 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | ..\packages\Microsoft.AspNet.WebApi.Cors.5.2.3\lib\net45\System.Web.Http.Cors.dll 105 | True 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | True 116 | ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll 117 | 118 | 119 | 120 | 121 | ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 122 | 123 | 124 | 125 | 126 | True 127 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll 128 | 129 | 130 | ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 131 | 132 | 133 | ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll 134 | 135 | 136 | True 137 | ..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll 138 | 139 | 140 | True 141 | ..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll 142 | 143 | 144 | True 145 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll 146 | 147 | 148 | True 149 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll 150 | 151 | 152 | True 153 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll 154 | 155 | 156 | True 157 | ..\packages\Antlr.3.4.1.9004\lib\Antlr3.Runtime.dll 158 | 159 | 160 | ..\packages\WebActivator.1.4.4\lib\net40\WebActivator.dll 161 | True 162 | 163 | 164 | 165 | 166 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 167 | 168 | 169 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 170 | 171 | 172 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 173 | 174 | 175 | ..\packages\Microsoft.AspNet.Identity.Owin.2.2.1\lib\net45\Microsoft.AspNet.Identity.Owin.dll 176 | 177 | 178 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 179 | 180 | 181 | ..\packages\Owin.1.0\lib\net40\Owin.dll 182 | 183 | 184 | ..\packages\Microsoft.AspNet.WebApi.Owin.5.2.3\lib\net45\System.Web.Http.Owin.dll 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | Global.asax 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | Web.config 212 | 213 | 214 | Web.config 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | {9813bf00-14d2-470d-9f94-638910e1e976} 226 | OAuthAspNetWebApiRest.Data 227 | 228 | 229 | {7e6a64ea-4631-4640-abe2-0184ddb4fa1a} 230 | OAuthAspNetWebApiRest.Domain 231 | 232 | 233 | 234 | 10.0 235 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | True 248 | True 249 | 20835 250 | / 251 | http://localhost:20835/ 252 | False 253 | False 254 | 255 | 256 | False 257 | 258 | 259 | 260 | 261 | 262 | 263 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 264 | 265 | 266 | 267 | 268 | 274 | --------------------------------------------------------------------------------