├── OAuthAspNetWebApiRest.Api
├── Global.asax
├── App_Start
│ ├── FilterConfig.cs
│ ├── RouteConfig.cs
│ ├── WebApiConfig.cs
│ ├── SimpleInjectorWebApiInitializer.cs
│ └── Startup.Auth.cs
├── Startup.cs
├── Controllers
│ ├── ProductController.cs
│ ├── BaseAuthApiController.cs
│ └── AccountController.cs
├── Results
│ └── ChallengeResult.cs
├── Global.asax.cs
├── Models
│ ├── AccountViewModels.cs
│ └── AccountBindingModels.cs
├── Web.Debug.config
├── Web.Release.config
├── Properties
│ └── AssemblyInfo.cs
├── OAuthAspNetWebApiRest.Api.csproj.user
├── packages.config
├── Providers
│ └── ApplicationOAuthProvider.cs
├── Web.config
└── OAuthAspNetWebApiRest.Api.csproj
├── OAuthAspNetWebApiRest.Domain
├── Models
│ ├── User.cs
│ └── Product.cs
├── Class1.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
├── .gitignore
├── OAuthAspNetWebApiRest.Data
├── OAuthAspNetWebApiRest.Data.csproj.user
├── AppUserStore.cs
├── AppDbContext.cs
├── Repositories
│ ├── ProductRepository.cs
│ └── UserRepository.cs
├── packages.config
├── Migrations
│ ├── 201705312114068_FirstMigration.Designer.cs
│ ├── Configuration.cs
│ ├── 201705312114068_FirstMigration.cs
│ └── 201705312114068_FirstMigration.resx
├── Properties
│ └── AssemblyInfo.cs
├── App.config
└── OAuthAspNetWebApiRest.Data.csproj
├── README.md
└── OAuthAspNetWebApiRest.sln
/OAuthAspNetWebApiRest.Api/Global.asax:
--------------------------------------------------------------------------------
1 | <%@ Application Codebehind="Global.asax.cs" Inherits="OAuthAspNetWebApiRest.Api.WebApiApplication" Language="C#" %>
2 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/.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
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Domain/Class1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace OAuthAspNetWebApiRest.Domain
8 | {
9 | public class Class1
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 | }
12 |
13 | public DbSet Products { get; set; }
14 | public static AppDbContext Create()
15 | {
16 | return new AppDbContext();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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.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/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OAuth_AspNet_WebApi_Rest
2 |
3 |
4 | Este projeto foi desenvolvido utilizando ASP.NET Web Api com Autenticação OAuth, com a abordagem code first:
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 |
16 |
17 | Licença
18 | ----
19 |
20 | MIT
21 |
22 |
23 | **Sinta-se a livre!**
24 |
25 |
26 | [Visual Studio Community 2017]:
27 | [ASP NET MVC]:
28 | [Simple Injector]:
29 | [ASP NET Identity]:
30 | [MS SQL Express]:
31 |
32 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Api/App_Start/WebApiConfig.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net.Http;
5 | using System.Web.Http;
6 | using Microsoft.Owin.Security.OAuth;
7 | using Newtonsoft.Json.Serialization;
8 |
9 | namespace OAuthAspNetWebApiRest.Api
10 | {
11 | public static class WebApiConfig
12 | {
13 | public static void Register(HttpConfiguration config)
14 | {
15 | // Web API configuration and services
16 | // Configure Web API to use only bearer token authentication.
17 | config.SuppressDefaultHostAuthentication();
18 | config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
19 |
20 | // Web API routes
21 | config.MapHttpAttributeRoutes();
22 |
23 | config.Routes.MapHttpRoute(
24 | name: "DefaultApi",
25 | routeTemplate: "api/{controller}/{id}",
26 | defaults: new { id = RouteParameter.Optional }
27 | );
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Api/Global.asax.cs:
--------------------------------------------------------------------------------
1 | using System.Web.Http;
2 | using System.Web.Mvc;
3 | using System.Web.Routing;
4 |
5 | namespace OAuthAspNetWebApiRest.Api
6 | {
7 | public class WebApiApplication : System.Web.HttpApplication
8 | {
9 | protected void Application_Start()
10 | {
11 | GlobalConfiguration.Configure(WebApiConfig.Register);
12 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
13 | RouteConfig.RegisterRoutes(RouteTable.Routes);
14 |
15 | //Define Formatters
16 | var formatters = GlobalConfiguration.Configuration.Formatters;
17 | var jsonFormatter = formatters.JsonFormatter;
18 | jsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
19 | jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
20 | jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
21 | GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Data/Migrations/Configuration.cs:
--------------------------------------------------------------------------------
1 | namespace OAuthAspNetWebApiRest.Data.Migrations
2 | {
3 | using Domain.Models;
4 | using System;
5 | using System.Data.Entity;
6 | using System.Data.Entity.Migrations;
7 | using System.Linq;
8 |
9 | internal sealed class Configuration : DbMigrationsConfiguration
10 | {
11 | public Configuration()
12 | {
13 | AutomaticMigrationsEnabled = false;
14 | }
15 |
16 | protected override void Seed(OAuthAspNetWebApiRest.Data.AppDbContext context)
17 | {
18 | // This method will be called after migrating to the latest version.
19 |
20 | // You can use the DbSet.AddOrUpdate() helper extension method
21 | // to avoid creating duplicate seed data. E.g.
22 | //
23 | context.Products.AddOrUpdate(
24 | p => p.Name,
25 | new Product { Name = "Rice", Quantity = 5 },
26 | new Product { Name = "Bean" , Quantity = 10},
27 | new Product { Name = "Tomato", Quantity = 15 }
28 | );
29 |
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Api/Web.Debug.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Api/Web.Release.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
19 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.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}") = "OAuthAspNetWebApiRest.Api", "OAuthAspNetWebApiRest.Api\OAuthAspNetWebApiRest.Api.csproj", "{80660222-8840-4BCC-82F7-FEA302EF0760}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAspNetWebApiRest.Data", "OAuthAspNetWebApiRest.Data\OAuthAspNetWebApiRest.Data.csproj", "{9813BF00-14D2-470D-9F94-638910E1E976}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAspNetWebApiRest.Domain", "OAuthAspNetWebApiRest.Domain\OAuthAspNetWebApiRest.Domain.csproj", "{7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {80660222-8840-4BCC-82F7-FEA302EF0760}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {9813BF00-14D2-470D-9F94-638910E1E976}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {9813BF00-14D2-470D-9F94-638910E1E976}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {9813BF00-14D2-470D-9F94-638910E1E976}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {9813BF00-14D2-470D-9F94-638910E1E976}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | EndGlobal
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 | }
--------------------------------------------------------------------------------
/OAuthAspNetWebApiRest.Api/App_Start/Startup.Auth.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.AspNet.Identity;
3 | using Microsoft.Owin;
4 | using Microsoft.Owin.Security.Cookies;
5 | using Microsoft.Owin.Security.OAuth;
6 | using Owin;
7 | using OAuthAspNetWebApiRest.Api.Providers;
8 | using OAuthAspNetWebApiRest.Data.Repositories;
9 | using OAuthAspNetWebApiRest.Api.App_Start;
10 | using SimpleInjector.Lifestyles;
11 | using OAuthAspNetWebApiRest.Data;
12 |
13 | namespace OAuthAspNetWebApiRest.Api
14 | {
15 | public partial class Startup
16 | {
17 | public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
18 |
19 | public static string PublicClientId { get; private set; }
20 |
21 | // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
22 | public void ConfigureAuth(IAppBuilder app)
23 | {
24 | var container = SimpleInjectorWebApiInitializer.Container;
25 | app.CreatePerOwinContext(AppDbContext.Create);
26 | app.CreatePerOwinContext(UserRepository.Create);
27 | // Enable the application to use a cookie to store information for the signed in user
28 | // and to use a cookie to temporarily store information about a user logging in with a third party login provider
29 | app.UseCookieAuthentication(new CookieAuthenticationOptions());
30 | app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
31 |
32 | // Configure the application for OAuth based flow
33 | PublicClientId = "self";
34 | OAuthOptions = new OAuthAuthorizationServerOptions
35 | {
36 | TokenEndpointPath = new PathString("/Token"),
37 | Provider = new ApplicationOAuthProvider(PublicClientId),
38 | AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
39 | AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
40 | // In production mode set AllowInsecureHttp = false
41 | AllowInsecureHttp = true
42 | };
43 | app.Use(async (context, next) => {
44 | using (AsyncScopedLifestyle.BeginScope(container))
45 | {
46 | await next();
47 | }
48 | });
49 | // Enable the application to use bearer tokens to authenticate users
50 | app.UseOAuthBearerTokens(OAuthOptions);
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/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.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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
32 | public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
33 | {
34 | var userManager = context.OwinContext.GetUserManager();
35 |
36 | User user = await userManager.FindAsync(context.UserName, context.Password);
37 |
38 | if (user == null)
39 | {
40 | context.SetError("invalid_grant", "The user name or password is incorrect.");
41 | return;
42 | }
43 |
44 | ClaimsIdentity oAuthIdentity = await userManager.GenerateUserIdentityAsync(user, OAuthDefaults.AuthenticationType);
45 | ClaimsIdentity cookiesIdentity = await userManager.GenerateUserIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);
46 |
47 | AuthenticationProperties properties = CreateProperties(user.UserName);
48 | AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
49 | context.Validated(ticket);
50 | context.Request.Context.Authentication.SignIn(cookiesIdentity);
51 | }
52 |
53 | public override Task TokenEndpoint(OAuthTokenEndpointContext context)
54 | {
55 | foreach (KeyValuePair property in context.Properties.Dictionary)
56 | {
57 | context.AdditionalResponseParameters.Add(property.Key, property.Value);
58 | }
59 |
60 | return Task.FromResult