├── 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(null); 61 | } 62 | 63 | public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 64 | { 65 | // Resource owner password credentials does not provide a client ID. 66 | if (context.ClientId == null) 67 | { 68 | context.Validated(); 69 | } 70 | 71 | return Task.FromResult(null); 72 | } 73 | 74 | public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) 75 | { 76 | if (context.ClientId == _publicClientId) 77 | { 78 | Uri expectedRootUri = new Uri(context.Request.Uri, "/"); 79 | 80 | if (expectedRootUri.AbsoluteUri == context.RedirectUri) 81 | { 82 | context.Validated(); 83 | } 84 | } 85 | 86 | return Task.FromResult(null); 87 | } 88 | 89 | public static AuthenticationProperties CreateProperties(string userName) 90 | { 91 | IDictionary data = new Dictionary 92 | { 93 | { "userName", userName } 94 | }; 95 | return new AuthenticationProperties(data); 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /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.Domain/OAuthAspNetWebApiRest.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7E6A64EA-4631-4640-ABE2-0184DDB4FA1A} 8 | Library 9 | Properties 10 | OAuthAspNetWebApiRest.Domain 11 | OAuthAspNetWebApiRest.Domain 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 43 | True 44 | 45 | 46 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 47 | True 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 84 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/201705312114068_FirstMigration.cs: -------------------------------------------------------------------------------- 1 | namespace OAuthAspNetWebApiRest.Data.Migrations 2 | { 3 | using System; 4 | using System.Data.Entity.Migrations; 5 | 6 | public partial class FirstMigration : DbMigration 7 | { 8 | public override void Up() 9 | { 10 | CreateTable( 11 | "dbo.Products", 12 | c => new 13 | { 14 | Id = c.Int(nullable: false, identity: true), 15 | Name = c.String(), 16 | Quantity = c.Decimal(nullable: false, precision: 18, scale: 2), 17 | }) 18 | .PrimaryKey(t => t.Id); 19 | 20 | CreateTable( 21 | "dbo.AspNetRoles", 22 | c => new 23 | { 24 | Id = c.String(nullable: false, maxLength: 128), 25 | Name = c.String(nullable: false, maxLength: 256), 26 | }) 27 | .PrimaryKey(t => t.Id) 28 | .Index(t => t.Name, unique: true, name: "RoleNameIndex"); 29 | 30 | CreateTable( 31 | "dbo.AspNetUserRoles", 32 | c => new 33 | { 34 | UserId = c.String(nullable: false, maxLength: 128), 35 | RoleId = c.String(nullable: false, maxLength: 128), 36 | }) 37 | .PrimaryKey(t => new { t.UserId, t.RoleId }) 38 | .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) 39 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 40 | .Index(t => t.UserId) 41 | .Index(t => t.RoleId); 42 | 43 | CreateTable( 44 | "dbo.AspNetUsers", 45 | c => new 46 | { 47 | Id = c.String(nullable: false, maxLength: 128), 48 | Email = c.String(maxLength: 256), 49 | EmailConfirmed = c.Boolean(nullable: false), 50 | PasswordHash = c.String(), 51 | SecurityStamp = c.String(), 52 | PhoneNumber = c.String(), 53 | PhoneNumberConfirmed = c.Boolean(nullable: false), 54 | TwoFactorEnabled = c.Boolean(nullable: false), 55 | LockoutEndDateUtc = c.DateTime(), 56 | LockoutEnabled = c.Boolean(nullable: false), 57 | AccessFailedCount = c.Int(nullable: false), 58 | UserName = c.String(nullable: false, maxLength: 256), 59 | }) 60 | .PrimaryKey(t => t.Id) 61 | .Index(t => t.UserName, unique: true, name: "UserNameIndex"); 62 | 63 | CreateTable( 64 | "dbo.AspNetUserClaims", 65 | c => new 66 | { 67 | Id = c.Int(nullable: false, identity: true), 68 | UserId = c.String(nullable: false, maxLength: 128), 69 | ClaimType = c.String(), 70 | ClaimValue = c.String(), 71 | }) 72 | .PrimaryKey(t => t.Id) 73 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 74 | .Index(t => t.UserId); 75 | 76 | CreateTable( 77 | "dbo.AspNetUserLogins", 78 | c => new 79 | { 80 | LoginProvider = c.String(nullable: false, maxLength: 128), 81 | ProviderKey = c.String(nullable: false, maxLength: 128), 82 | UserId = c.String(nullable: false, maxLength: 128), 83 | }) 84 | .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) 85 | .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) 86 | .Index(t => t.UserId); 87 | 88 | } 89 | 90 | public override void Down() 91 | { 92 | DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); 93 | DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); 94 | DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); 95 | DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); 96 | DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); 97 | DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); 98 | DropIndex("dbo.AspNetUsers", "UserNameIndex"); 99 | DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); 100 | DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); 101 | DropIndex("dbo.AspNetRoles", "RoleNameIndex"); 102 | DropTable("dbo.AspNetUserLogins"); 103 | DropTable("dbo.AspNetUserClaims"); 104 | DropTable("dbo.AspNetUsers"); 105 | DropTable("dbo.AspNetUserRoles"); 106 | DropTable("dbo.AspNetRoles"); 107 | DropTable("dbo.Products"); 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Web.config: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/OAuthAspNetWebApiRest.Data.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9813BF00-14D2-470D-9F94-638910E1E976} 8 | Library 9 | Properties 10 | OAuthAspNetWebApiRest.Data 11 | OAuthAspNetWebApiRest.Data 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 35 | True 36 | 37 | 38 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 39 | True 40 | 41 | 42 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 43 | True 44 | 45 | 46 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 47 | True 48 | 49 | 50 | ..\packages\Microsoft.AspNet.Identity.Owin.2.2.1\lib\net45\Microsoft.AspNet.Identity.Owin.dll 51 | True 52 | 53 | 54 | ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll 55 | True 56 | 57 | 58 | ..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll 59 | True 60 | 61 | 62 | ..\packages\Microsoft.Owin.Security.Cookies.3.1.0\lib\net45\Microsoft.Owin.Security.Cookies.dll 63 | True 64 | 65 | 66 | ..\packages\Microsoft.Owin.Security.OAuth.3.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll 67 | True 68 | 69 | 70 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 71 | True 72 | 73 | 74 | ..\packages\Owin.1.0\lib\net40\Owin.dll 75 | True 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 201705312114068_FirstMigration.cs 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | {7e6a64ea-4631-4640-abe2-0184ddb4fa1a} 102 | OAuthAspNetWebApiRest.Domain 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 201705312114068_FirstMigration.cs 112 | 113 | 114 | 115 | 122 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Data/Migrations/201705312114068_FirstMigration.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 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 122 | 123 | 124 | dbo 125 | 126 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Security.Claims; 5 | using System.Security.Cryptography; 6 | using System.Threading.Tasks; 7 | using System.Web; 8 | using System.Web.Http; 9 | using Microsoft.AspNet.Identity; 10 | using Microsoft.AspNet.Identity.EntityFramework; 11 | using Microsoft.Owin.Security; 12 | using Microsoft.Owin.Security.Cookies; 13 | using Microsoft.Owin.Security.OAuth; 14 | using OAuthAspNetWebApiRest.Api.Models; 15 | using OAuthAspNetWebApiRest.Api.Providers; 16 | using OAuthAspNetWebApiRest.Api.Results; 17 | using OAuthAspNetWebApiRest.Domain.Contracts.Services; 18 | using OAuthAspNetWebApiRest.Domain.Models; 19 | 20 | namespace OAuthAspNetWebApiRest.Api.Controllers 21 | { 22 | [Authorize] 23 | [RoutePrefix("api/Account")] 24 | public class AccountController : BaseAuthApiController 25 | { 26 | private const string LocalLoginProvider = "Local"; 27 | private IUserService _userService; 28 | 29 | public AccountController(IUserService userManager) 30 | { 31 | _userService = userManager; 32 | } 33 | 34 | public ISecureDataFormat AccessTokenFormat { get; private set; } 35 | 36 | [HttpGet] 37 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 38 | [Route("UserInfo")] 39 | public UserInfoViewModel GetUserInfo() 40 | { 41 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 42 | 43 | return new UserInfoViewModel 44 | { 45 | Email = User.Identity.GetUserName(), 46 | HasRegistered = externalLogin == null, 47 | LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null 48 | }; 49 | } 50 | 51 | [HttpPost] 52 | [Route("Logout")] 53 | public IHttpActionResult Logout() 54 | { 55 | Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); 56 | return Ok(); 57 | } 58 | 59 | // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true 60 | [HttpGet] 61 | [Route("ManageInfo")] 62 | public async Task GetManageInfo(string returnUrl, bool generateState = false) 63 | { 64 | IdentityUser user = await _userService.FindByIdAsync(User.Identity.GetUserId()); 65 | 66 | if (user == null) 67 | { 68 | return null; 69 | } 70 | 71 | List logins = new List(); 72 | 73 | foreach (IdentityUserLogin linkedAccount in user.Logins) 74 | { 75 | logins.Add(new UserLoginInfoViewModel 76 | { 77 | LoginProvider = linkedAccount.LoginProvider, 78 | ProviderKey = linkedAccount.ProviderKey 79 | }); 80 | } 81 | 82 | if (user.PasswordHash != null) 83 | { 84 | logins.Add(new UserLoginInfoViewModel 85 | { 86 | LoginProvider = LocalLoginProvider, 87 | ProviderKey = user.UserName, 88 | }); 89 | } 90 | 91 | return new ManageInfoViewModel 92 | { 93 | LocalLoginProvider = LocalLoginProvider, 94 | Email = user.UserName, 95 | Logins = logins, 96 | ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) 97 | }; 98 | } 99 | 100 | [HttpPost] 101 | [Route("ChangePassword")] 102 | public async Task ChangePassword(ChangePasswordBindingModel model) 103 | { 104 | if (!ModelState.IsValid) 105 | { 106 | return BadRequest(ModelState); 107 | } 108 | 109 | IdentityResult result = await _userService.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, 110 | model.NewPassword); 111 | 112 | if (!result.Succeeded) 113 | { 114 | return GetErrorResult(result); 115 | } 116 | 117 | return Ok(); 118 | } 119 | 120 | [HttpPost] 121 | [Route("SetPassword")] 122 | public async Task SetPassword(SetPasswordBindingModel model) 123 | { 124 | if (!ModelState.IsValid) 125 | { 126 | return BadRequest(ModelState); 127 | } 128 | 129 | IdentityResult result = await _userService.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); 130 | 131 | if (!result.Succeeded) 132 | { 133 | return GetErrorResult(result); 134 | } 135 | 136 | return Ok(); 137 | } 138 | 139 | [HttpPost] 140 | [Route("AddExternalLogin")] 141 | public async Task AddExternalLogin(AddExternalLoginBindingModel model) 142 | { 143 | if (!ModelState.IsValid) 144 | { 145 | return BadRequest(ModelState); 146 | } 147 | 148 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 149 | 150 | AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); 151 | 152 | if (ticket == null || ticket.Identity == null || (ticket.Properties != null 153 | && ticket.Properties.ExpiresUtc.HasValue 154 | && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) 155 | { 156 | return BadRequest("External login failure."); 157 | } 158 | 159 | ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); 160 | 161 | if (externalData == null) 162 | { 163 | return BadRequest("The external login is already associated with an account."); 164 | } 165 | 166 | IdentityResult result = await _userService.AddLoginAsync(User.Identity.GetUserId(), 167 | new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); 168 | 169 | if (!result.Succeeded) 170 | { 171 | return GetErrorResult(result); 172 | } 173 | 174 | return Ok(); 175 | } 176 | 177 | [HttpPost] 178 | [Route("RemoveLogin")] 179 | public async Task RemoveLogin(RemoveLoginBindingModel model) 180 | { 181 | if (!ModelState.IsValid) 182 | { 183 | return BadRequest(ModelState); 184 | } 185 | 186 | IdentityResult result; 187 | 188 | if (model.LoginProvider == LocalLoginProvider) 189 | { 190 | result = await _userService.RemovePasswordAsync(User.Identity.GetUserId()); 191 | } 192 | else 193 | { 194 | result = await _userService.RemoveLoginAsync(User.Identity.GetUserId(), 195 | new UserLoginInfo(model.LoginProvider, model.ProviderKey)); 196 | } 197 | 198 | if (!result.Succeeded) 199 | { 200 | return GetErrorResult(result); 201 | } 202 | 203 | return Ok(); 204 | } 205 | 206 | [HttpGet] 207 | [OverrideAuthentication] 208 | [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] 209 | [AllowAnonymous] 210 | [Route("ExternalLogin", Name = "ExternalLogin")] 211 | public async Task GetExternalLogin(string provider, string error = null) 212 | { 213 | if (error != null) 214 | { 215 | return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); 216 | } 217 | 218 | if (!User.Identity.IsAuthenticated) 219 | { 220 | return new ChallengeResult(provider, this); 221 | } 222 | 223 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 224 | 225 | if (externalLogin == null) 226 | { 227 | return InternalServerError(); 228 | } 229 | 230 | if (externalLogin.LoginProvider != provider) 231 | { 232 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 233 | return new ChallengeResult(provider, this); 234 | } 235 | 236 | User user = await _userService.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, 237 | externalLogin.ProviderKey)); 238 | 239 | bool hasRegistered = user != null; 240 | 241 | if (hasRegistered) 242 | { 243 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 244 | 245 | ClaimsIdentity oAuthIdentity = await _userService.GenerateUserIdentityAsync(user, OAuthDefaults.AuthenticationType); 246 | ClaimsIdentity cookieIdentity = await _userService.GenerateUserIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); 247 | 248 | AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 249 | Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); 250 | } 251 | else 252 | { 253 | IEnumerable claims = externalLogin.GetClaims(); 254 | ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); 255 | Authentication.SignIn(identity); 256 | } 257 | 258 | return Ok(); 259 | } 260 | 261 | // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true 262 | [HttpGet] 263 | [AllowAnonymous] 264 | [Route("ExternalLogins")] 265 | public IEnumerable GetExternalLogins(string returnUrl, bool generateState = false) 266 | { 267 | IEnumerable descriptions = Authentication.GetExternalAuthenticationTypes(); 268 | List logins = new List(); 269 | 270 | string state; 271 | 272 | if (generateState) 273 | { 274 | const int strengthInBits = 256; 275 | state = RandomOAuthStateGenerator.Generate(strengthInBits); 276 | } 277 | else 278 | { 279 | state = null; 280 | } 281 | 282 | foreach (AuthenticationDescription description in descriptions) 283 | { 284 | ExternalLoginViewModel login = new ExternalLoginViewModel 285 | { 286 | Name = description.Caption, 287 | Url = Url.Route("ExternalLogin", new 288 | { 289 | provider = description.AuthenticationType, 290 | response_type = "token", 291 | client_id = Startup.PublicClientId, 292 | redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, 293 | state = state 294 | }), 295 | State = state 296 | }; 297 | logins.Add(login); 298 | } 299 | 300 | return logins; 301 | } 302 | 303 | [HttpPost] 304 | [AllowAnonymous] 305 | [Route("Register")] 306 | public async Task Register(RegisterBindingModel model) 307 | { 308 | if (!ModelState.IsValid) 309 | { 310 | return BadRequest(ModelState); 311 | } 312 | 313 | var user = new User() { UserName = model.Email, Email = model.Email }; 314 | 315 | IdentityResult result = await _userService.CreateAsync(user, model.Password); 316 | 317 | if (!result.Succeeded) 318 | { 319 | return GetErrorResult(result); 320 | } 321 | 322 | return Ok(); 323 | } 324 | 325 | [HttpPost] 326 | [OverrideAuthentication] 327 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 328 | [Route("RegisterExternal")] 329 | public async Task RegisterExternal(RegisterExternalBindingModel model) 330 | { 331 | if (!ModelState.IsValid) 332 | { 333 | return BadRequest(ModelState); 334 | } 335 | 336 | var info = await Authentication.GetExternalLoginInfoAsync(); 337 | if (info == null) 338 | { 339 | return InternalServerError(); 340 | } 341 | 342 | var user = new User() { UserName = model.Email, Email = model.Email }; 343 | 344 | IdentityResult result = await _userService.CreateAsync(user); 345 | if (!result.Succeeded) 346 | { 347 | return GetErrorResult(result); 348 | } 349 | 350 | result = await _userService.AddLoginAsync(user.Id, info.Login); 351 | if (!result.Succeeded) 352 | { 353 | return GetErrorResult(result); 354 | } 355 | return Ok(); 356 | } 357 | 358 | protected override void Dispose(bool disposing) 359 | { 360 | if (disposing && _userService != null) 361 | { 362 | _userService.Dispose(); 363 | _userService = null; 364 | } 365 | 366 | base.Dispose(disposing); 367 | } 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /OAuthAspNetWebApiRest.Api/OAuthAspNetWebApiRest.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Debug 8 | AnyCPU 9 | 10 | 11 | 2.0 12 | {80660222-8840-4BCC-82F7-FEA302EF0760} 13 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} 14 | Library 15 | Properties 16 | OAuthAspNetWebApiRest.Api 17 | OAuthAspNetWebApiRest.Api 18 | v4.6.1 19 | false 20 | true 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | true 31 | full 32 | false 33 | bin\ 34 | DEBUG;TRACE 35 | prompt 36 | 4 37 | 38 | 39 | pdbonly 40 | true 41 | bin\ 42 | TRACE 43 | prompt 44 | 4 45 | 46 | 47 | 48 | ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll 49 | True 50 | 51 | 52 | 53 | ..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll 54 | True 55 | 56 | 57 | ..\packages\Microsoft.Owin.Host.SystemWeb.3.1.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll 58 | True 59 | 60 | 61 | ..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll 62 | True 63 | 64 | 65 | ..\packages\Microsoft.Owin.Security.Cookies.3.1.0\lib\net45\Microsoft.Owin.Security.Cookies.dll 66 | True 67 | 68 | 69 | ..\packages\Microsoft.Owin.Security.OAuth.3.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll 70 | True 71 | 72 | 73 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll 74 | True 75 | 76 | 77 | ..\packages\SimpleInjector.4.0.7\lib\net45\SimpleInjector.dll 78 | True 79 | 80 | 81 | ..\packages\SimpleInjector.Integration.Web.4.0.7\lib\net40\SimpleInjector.Integration.Web.dll 82 | True 83 | 84 | 85 | ..\packages\SimpleInjector.Integration.WebApi.4.0.7\lib\net45\SimpleInjector.Integration.WebApi.dll 86 | True 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | True 105 | ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll 106 | 107 | 108 | 109 | 110 | ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 111 | 112 | 113 | 114 | 115 | True 116 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll 117 | 118 | 119 | ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 120 | 121 | 122 | ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll 123 | 124 | 125 | True 126 | ..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll 127 | 128 | 129 | True 130 | ..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll 131 | 132 | 133 | True 134 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll 135 | 136 | 137 | True 138 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll 139 | 140 | 141 | True 142 | ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll 143 | 144 | 145 | True 146 | ..\packages\Antlr.3.4.1.9004\lib\Antlr3.Runtime.dll 147 | 148 | 149 | ..\packages\WebActivator.1.4.4\lib\net40\WebActivator.dll 150 | True 151 | 152 | 153 | 154 | 155 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll 156 | 157 | 158 | ..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll 159 | 160 | 161 | ..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll 162 | 163 | 164 | ..\packages\Microsoft.AspNet.Identity.Owin.2.2.1\lib\net45\Microsoft.AspNet.Identity.Owin.dll 165 | 166 | 167 | ..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll 168 | 169 | 170 | ..\packages\Owin.1.0\lib\net40\Owin.dll 171 | 172 | 173 | ..\packages\Microsoft.AspNet.WebApi.Owin.5.2.3\lib\net45\System.Web.Http.Owin.dll 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | Global.asax 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | Web.config 200 | 201 | 202 | Web.config 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | {9813bf00-14d2-470d-9f94-638910e1e976} 214 | OAuthAspNetWebApiRest.Data 215 | 216 | 217 | {7e6a64ea-4631-4640-abe2-0184ddb4fa1a} 218 | OAuthAspNetWebApiRest.Domain 219 | 220 | 221 | 222 | 10.0 223 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | True 236 | True 237 | 20835 238 | / 239 | http://localhost:20835/ 240 | False 241 | False 242 | 243 | 244 | False 245 | 246 | 247 | 248 | 249 | 250 | 251 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 252 | 253 | 254 | 255 | 256 | 262 | --------------------------------------------------------------------------------