├── 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 |
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 |
--------------------------------------------------------------------------------
/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 |
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