├── .gitattributes ├── .gitignore ├── .vs ├── WebAPI_NG_TokenbasedAuth │ └── v14 │ │ └── .suo └── config │ └── applicationhost.config ├── WebAPI_NG_TokenbasedAuth.sln └── WebAPI_NG_TokenbasedAuth ├── App_Data ├── aspnet-WebAPI_NG_TokenbasedAuth-20151001025617.mdf └── aspnet-WebAPI_NG_TokenbasedAuth-20151001025617_log.ldf ├── App_Start ├── BundleConfig.cs ├── FilterConfig.cs ├── IdentityConfig.cs ├── RouteConfig.cs ├── Startup.Auth.cs └── WebApiConfig.cs ├── Areas └── HelpPage │ ├── ApiDescriptionExtensions.cs │ ├── App_Start │ └── HelpPageConfig.cs │ ├── Controllers │ └── HelpController.cs │ ├── HelpPage.css │ ├── HelpPageAreaRegistration.cs │ ├── HelpPageConfigurationExtensions.cs │ ├── ModelDescriptions │ ├── CollectionModelDescription.cs │ ├── ComplexTypeModelDescription.cs │ ├── DictionaryModelDescription.cs │ ├── EnumTypeModelDescription.cs │ ├── EnumValueDescription.cs │ ├── IModelDocumentationProvider.cs │ ├── KeyValuePairModelDescription.cs │ ├── ModelDescription.cs │ ├── ModelDescriptionGenerator.cs │ ├── ModelNameAttribute.cs │ ├── ModelNameHelper.cs │ ├── ParameterAnnotation.cs │ ├── ParameterDescription.cs │ └── SimpleTypeModelDescription.cs │ ├── Models │ └── HelpPageApiModel.cs │ ├── SampleGeneration │ ├── HelpPageSampleGenerator.cs │ ├── HelpPageSampleKey.cs │ ├── ImageSample.cs │ ├── InvalidSample.cs │ ├── ObjectGenerator.cs │ ├── SampleDirection.cs │ └── TextSample.cs │ ├── Views │ ├── Help │ │ ├── Api.cshtml │ │ ├── DisplayTemplates │ │ │ ├── ApiGroup.cshtml │ │ │ ├── CollectionModelDescription.cshtml │ │ │ ├── ComplexTypeModelDescription.cshtml │ │ │ ├── DictionaryModelDescription.cshtml │ │ │ ├── EnumTypeModelDescription.cshtml │ │ │ ├── HelpPageApiModel.cshtml │ │ │ ├── ImageSample.cshtml │ │ │ ├── InvalidSample.cshtml │ │ │ ├── KeyValuePairModelDescription.cshtml │ │ │ ├── ModelDescriptionLink.cshtml │ │ │ ├── Parameters.cshtml │ │ │ ├── Samples.cshtml │ │ │ ├── SimpleTypeModelDescription.cshtml │ │ │ └── TextSample.cshtml │ │ ├── Index.cshtml │ │ └── ResourceModel.cshtml │ ├── Shared │ │ └── _Layout.cshtml │ ├── Web.config │ └── _ViewStart.cshtml │ └── XmlDocumentationProvider.cs ├── Content ├── Site.css ├── bootstrap-theme.css ├── bootstrap-theme.css.map ├── bootstrap-theme.min.css ├── bootstrap.css ├── bootstrap.css.map └── bootstrap.min.css ├── Controllers ├── AccountController.cs ├── EmployeeAPIController.cs ├── EmployeeController.cs ├── HomeController.cs ├── LoginController.cs └── ValuesController.cs ├── Global.asax ├── Global.asax.cs ├── Models ├── AccountBindingModels.cs ├── AccountViewModels.cs ├── EmployeeModel.cs └── IdentityModels.cs ├── Project_Readme.html ├── Properties └── AssemblyInfo.cs ├── Providers └── ApplicationOAuthProvider.cs ├── Results └── ChallengeResult.cs ├── Scripts ├── MyScripts │ ├── EmpService.js │ ├── EmployeeController.js │ ├── LoginLogic.js │ └── Module.js ├── _references.js ├── angular-mocks.js ├── angular.js ├── angular.min.js ├── angular.min.js.map ├── bootstrap.js ├── bootstrap.min.js ├── jquery-2.1.4.intellisense.js ├── jquery-2.1.4.js ├── jquery-2.1.4.min.js ├── jquery-2.1.4.min.map ├── jquery.validate-vsdoc.js ├── jquery.validate.js ├── jquery.validate.min.js ├── jquery.validate.unobtrusive.js ├── jquery.validate.unobtrusive.min.js ├── modernizr-2.6.2.js ├── respond.js └── respond.min.js ├── Startup.cs ├── Views ├── Employee │ └── Index.cshtml ├── Home │ └── Index.cshtml ├── Login │ ├── Index.cshtml │ └── SecurityInfo.cshtml ├── Shared │ ├── Error.cshtml │ └── _Layout.cshtml ├── Web.config └── _ViewStart.cshtml ├── Web.Debug.config ├── Web.Release.config ├── Web.config ├── WebAPI_NG_TokenbasedAuth.csproj ├── WebAPI_NG_TokenbasedAuth.csproj.user ├── favicon.ico ├── fonts ├── glyphicons-halflings-regular.eot ├── glyphicons-halflings-regular.svg ├── glyphicons-halflings-regular.ttf ├── glyphicons-halflings-regular.woff └── glyphicons-halflings-regular.woff2 ├── obj └── Debug │ ├── DesignTimeResolveAssemblyReferencesInput.cache │ ├── TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs │ ├── TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs │ ├── TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs │ ├── WebAPI_NG_TokenbasedAuth.csproj.FileListAbsolute.txt │ ├── WebAPI_NG_TokenbasedAuth.csprojResolveAssemblyReference.cache │ ├── WebAPI_NG_TokenbasedAuth.dll │ └── WebAPI_NG_TokenbasedAuth.pdb └── packages.config /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /.vs/WebAPI_NG_TokenbasedAuth/v14/.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/.vs/WebAPI_NG_TokenbasedAuth/v14/.suo -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAPI_NG_TokenbasedAuth", "WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth.csproj", "{8524E183-AE33-4CF2-8B53-7FC421367196}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {8524E183-AE33-4CF2-8B53-7FC421367196}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {8524E183-AE33-4CF2-8B53-7FC421367196}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {8524E183-AE33-4CF2-8B53-7FC421367196}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {8524E183-AE33-4CF2-8B53-7FC421367196}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Data/aspnet-WebAPI_NG_TokenbasedAuth-20151001025617.mdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/App_Data/aspnet-WebAPI_NG_TokenbasedAuth-20151001025617.mdf -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Data/aspnet-WebAPI_NG_TokenbasedAuth-20151001025617_log.ldf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/App_Data/aspnet-WebAPI_NG_TokenbasedAuth-20151001025617_log.ldf -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth 5 | { 6 | public class BundleConfig 7 | { 8 | // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 9 | public static void RegisterBundles(BundleCollection bundles) 10 | { 11 | bundles.Add(new ScriptBundle("~/bundles/jquery").Include( 12 | "~/Scripts/jquery-{version}.js")); 13 | 14 | // Use the development version of Modernizr to develop with and learn from. Then, when you're 15 | // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. 16 | bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( 17 | "~/Scripts/modernizr-*")); 18 | 19 | bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( 20 | "~/Scripts/bootstrap.js", 21 | "~/Scripts/respond.js")); 22 | 23 | bundles.Add(new StyleBundle("~/Content/css").Include( 24 | "~/Content/bootstrap.css", 25 | "~/Content/site.css")); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Start/IdentityConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNet.Identity; 3 | using Microsoft.AspNet.Identity.EntityFramework; 4 | using Microsoft.AspNet.Identity.Owin; 5 | using Microsoft.Owin; 6 | using WebAPI_NG_TokenbasedAuth.Models; 7 | 8 | namespace WebAPI_NG_TokenbasedAuth 9 | { 10 | // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. 11 | 12 | public class ApplicationUserManager : UserManager 13 | { 14 | public ApplicationUserManager(IUserStore store) 15 | : base(store) 16 | { 17 | } 18 | 19 | public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) 20 | { 21 | var manager = new ApplicationUserManager(new UserStore(context.Get())); 22 | // Configure validation logic for usernames 23 | manager.UserValidator = new UserValidator(manager) 24 | { 25 | AllowOnlyAlphanumericUserNames = false, 26 | RequireUniqueEmail = true 27 | }; 28 | // Configure validation logic for passwords 29 | manager.PasswordValidator = new PasswordValidator 30 | { 31 | RequiredLength = 6, 32 | RequireNonLetterOrDigit = true, 33 | RequireDigit = true, 34 | RequireLowercase = true, 35 | RequireUppercase = true, 36 | }; 37 | var dataProtectionProvider = options.DataProtectionProvider; 38 | if (dataProtectionProvider != null) 39 | { 40 | manager.UserTokenProvider = new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity")); 41 | } 42 | return manager; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 WebAPI_NG_TokenbasedAuth 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 = "Login", action = "SecurityInfo", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.AspNet.Identity; 5 | using Microsoft.AspNet.Identity.EntityFramework; 6 | using Microsoft.Owin; 7 | using Microsoft.Owin.Security.Cookies; 8 | using Microsoft.Owin.Security.Google; 9 | using Microsoft.Owin.Security.OAuth; 10 | using Owin; 11 | using WebAPI_NG_TokenbasedAuth.Providers; 12 | using WebAPI_NG_TokenbasedAuth.Models; 13 | 14 | namespace WebAPI_NG_TokenbasedAuth 15 | { 16 | public partial class Startup 17 | { 18 | public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 19 | 20 | public static string PublicClientId { get; private set; } 21 | 22 | // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 23 | public void ConfigureAuth(IAppBuilder app) 24 | { 25 | // Configure the db context and user manager to use a single instance per request 26 | app.CreatePerOwinContext(ApplicationDbContext.Create); 27 | app.CreatePerOwinContext(ApplicationUserManager.Create); 28 | 29 | // Enable the application to use a cookie to store information for the signed in user 30 | // and to use a cookie to temporarily store information about a user logging in with a third party login provider 31 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 32 | app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 33 | 34 | // Configure the application for OAuth based flow 35 | PublicClientId = "self"; 36 | OAuthOptions = new OAuthAuthorizationServerOptions 37 | { 38 | TokenEndpointPath = new PathString("/Token"), 39 | Provider = new ApplicationOAuthProvider(PublicClientId), 40 | AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 41 | AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 42 | // In production mode set AllowInsecureHttp = false 43 | AllowInsecureHttp = true 44 | }; 45 | 46 | // Enable the application to use bearer tokens to authenticate users 47 | app.UseOAuthBearerTokens(OAuthOptions); 48 | 49 | // Uncomment the following lines to enable logging in with third party login providers 50 | //app.UseMicrosoftAccountAuthentication( 51 | // clientId: "", 52 | // clientSecret: ""); 53 | 54 | //app.UseTwitterAuthentication( 55 | // consumerKey: "", 56 | // consumerSecret: ""); 57 | 58 | //app.UseFacebookAuthentication( 59 | // appId: "", 60 | // appSecret: ""); 61 | 62 | //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 63 | //{ 64 | // ClientId = "", 65 | // ClientSecret = "" 66 | //}); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 WebAPI_NG_TokenbasedAuth 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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ApiDescriptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Web; 4 | using System.Web.Http.Description; 5 | 6 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 7 | { 8 | public static class ApiDescriptionExtensions 9 | { 10 | /// 11 | /// Generates an URI-friendly ID for the . E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" 12 | /// 13 | /// The . 14 | /// The ID as a string. 15 | public static string GetFriendlyId(this ApiDescription description) 16 | { 17 | string path = description.RelativePath; 18 | string[] urlParts = path.Split('?'); 19 | string localPath = urlParts[0]; 20 | string queryKeyString = null; 21 | if (urlParts.Length > 1) 22 | { 23 | string query = urlParts[1]; 24 | string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; 25 | queryKeyString = String.Join("_", queryKeys); 26 | } 27 | 28 | StringBuilder friendlyPath = new StringBuilder(); 29 | friendlyPath.AppendFormat("{0}-{1}", 30 | description.HttpMethod.Method, 31 | localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); 32 | if (queryKeyString != null) 33 | { 34 | friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); 35 | } 36 | return friendlyPath.ToString(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/App_Start/HelpPageConfig.cs: -------------------------------------------------------------------------------- 1 | // Uncomment the following to provide samples for PageResult. Must also add the Microsoft.AspNet.WebApi.OData 2 | // package to your project. 3 | ////#define Handle_PageResultOfT 4 | 5 | using System; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.Diagnostics.CodeAnalysis; 10 | using System.Linq; 11 | using System.Net.Http.Headers; 12 | using System.Reflection; 13 | using System.Web; 14 | using System.Web.Http; 15 | #if Handle_PageResultOfT 16 | using System.Web.Http.OData; 17 | #endif 18 | 19 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 20 | { 21 | /// 22 | /// Use this class to customize the Help Page. 23 | /// For example you can set a custom to supply the documentation 24 | /// or you can provide the samples for the requests/responses. 25 | /// 26 | public static class HelpPageConfig 27 | { 28 | [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", 29 | MessageId = "WebAPI_NG_TokenbasedAuth.Areas.HelpPage.TextSample.#ctor(System.String)", 30 | Justification = "End users may choose to merge this string with existing localized resources.")] 31 | [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", 32 | MessageId = "bsonspec", 33 | Justification = "Part of a URI.")] 34 | public static void Register(HttpConfiguration config) 35 | { 36 | //// Uncomment the following to use the documentation from XML documentation file. 37 | //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); 38 | 39 | //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. 40 | //// Also, the string arrays will be used for IEnumerable. The sample objects will be serialized into different media type 41 | //// formats by the available formatters. 42 | //config.SetSampleObjects(new Dictionary 43 | //{ 44 | // {typeof(string), "sample string"}, 45 | // {typeof(IEnumerable), new string[]{"sample 1", "sample 2"}} 46 | //}); 47 | 48 | // Extend the following to provide factories for types not handled automatically (those lacking parameterless 49 | // constructors) or for which you prefer to use non-default property values. Line below provides a fallback 50 | // since automatic handling will fail and GeneratePageResult handles only a single type. 51 | #if Handle_PageResultOfT 52 | config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); 53 | #endif 54 | 55 | // Extend the following to use a preset object directly as the sample for all actions that support a media 56 | // type, regardless of the body parameter or return type. The lines below avoid display of binary content. 57 | // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. 58 | config.SetSampleForMediaType( 59 | new TextSample("Binary JSON content. See http://bsonspec.org for details."), 60 | new MediaTypeHeaderValue("application/bson")); 61 | 62 | //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format 63 | //// and have IEnumerable as the body parameter or return type. 64 | //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable)); 65 | 66 | //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" 67 | //// and action named "Put". 68 | //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); 69 | 70 | //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" 71 | //// on the controller named "Values" and action named "Get" with parameter "id". 72 | //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); 73 | 74 | //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent. 75 | //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. 76 | //config.SetActualRequestType(typeof(string), "Values", "Get"); 77 | 78 | //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent. 79 | //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. 80 | //config.SetActualResponseType(typeof(string), "Values", "Post"); 81 | } 82 | 83 | #if Handle_PageResultOfT 84 | private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) 85 | { 86 | if (type.IsGenericType) 87 | { 88 | Type openGenericType = type.GetGenericTypeDefinition(); 89 | if (openGenericType == typeof(PageResult<>)) 90 | { 91 | // Get the T in PageResult 92 | Type[] typeParameters = type.GetGenericArguments(); 93 | Debug.Assert(typeParameters.Length == 1); 94 | 95 | // Create an enumeration to pass as the first parameter to the PageResult constuctor 96 | Type itemsType = typeof(List<>).MakeGenericType(typeParameters); 97 | object items = sampleGenerator.GetSampleObject(itemsType); 98 | 99 | // Fill in the other information needed to invoke the PageResult constuctor 100 | Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; 101 | object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; 102 | 103 | // Call PageResult(IEnumerable items, Uri nextPageLink, long? count) constructor 104 | ConstructorInfo constructor = type.GetConstructor(parameterTypes); 105 | return constructor.Invoke(parameters); 106 | } 107 | } 108 | 109 | return null; 110 | } 111 | #endif 112 | } 113 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Controllers/HelpController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Web.Http; 3 | using System.Web.Mvc; 4 | using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions; 5 | using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Controllers 8 | { 9 | /// 10 | /// The controller that will handle requests for the help page. 11 | /// 12 | public class HelpController : Controller 13 | { 14 | private const string ErrorViewName = "Error"; 15 | 16 | public HelpController() 17 | : this(GlobalConfiguration.Configuration) 18 | { 19 | } 20 | 21 | public HelpController(HttpConfiguration config) 22 | { 23 | Configuration = config; 24 | } 25 | 26 | public HttpConfiguration Configuration { get; private set; } 27 | 28 | public ActionResult Index() 29 | { 30 | ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); 31 | return View(Configuration.Services.GetApiExplorer().ApiDescriptions); 32 | } 33 | 34 | public ActionResult Api(string apiId) 35 | { 36 | if (!String.IsNullOrEmpty(apiId)) 37 | { 38 | HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); 39 | if (apiModel != null) 40 | { 41 | return View(apiModel); 42 | } 43 | } 44 | 45 | return View(ErrorViewName); 46 | } 47 | 48 | public ActionResult ResourceModel(string modelName) 49 | { 50 | if (!String.IsNullOrEmpty(modelName)) 51 | { 52 | ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); 53 | ModelDescription modelDescription; 54 | if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) 55 | { 56 | return View(modelDescription); 57 | } 58 | } 59 | 60 | return View(ErrorViewName); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/HelpPage.css: -------------------------------------------------------------------------------- 1 | .help-page h1, 2 | .help-page .h1, 3 | .help-page h2, 4 | .help-page .h2, 5 | .help-page h3, 6 | .help-page .h3, 7 | #body.help-page, 8 | .help-page-table th, 9 | .help-page-table pre, 10 | .help-page-table p { 11 | font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; 12 | } 13 | 14 | .help-page pre.wrapped { 15 | white-space: -moz-pre-wrap; 16 | white-space: -pre-wrap; 17 | white-space: -o-pre-wrap; 18 | white-space: pre-wrap; 19 | } 20 | 21 | .help-page .warning-message-container { 22 | margin-top: 20px; 23 | padding: 0 10px; 24 | color: #525252; 25 | background: #EFDCA9; 26 | border: 1px solid #CCCCCC; 27 | } 28 | 29 | .help-page-table { 30 | width: 100%; 31 | border-collapse: collapse; 32 | text-align: left; 33 | margin: 0px 0px 20px 0px; 34 | border-top: 1px solid #D4D4D4; 35 | } 36 | 37 | .help-page-table th { 38 | text-align: left; 39 | font-weight: bold; 40 | border-bottom: 1px solid #D4D4D4; 41 | padding: 5px 6px 5px 6px; 42 | } 43 | 44 | .help-page-table td { 45 | border-bottom: 1px solid #D4D4D4; 46 | padding: 10px 8px 10px 8px; 47 | vertical-align: top; 48 | } 49 | 50 | .help-page-table pre, 51 | .help-page-table p { 52 | margin: 0px; 53 | padding: 0px; 54 | font-family: inherit; 55 | font-size: 100%; 56 | } 57 | 58 | .help-page-table tbody tr:hover td { 59 | background-color: #F3F3F3; 60 | } 61 | 62 | .help-page a:hover { 63 | background-color: transparent; 64 | } 65 | 66 | .help-page .sample-header { 67 | border: 2px solid #D4D4D4; 68 | background: #00497E; 69 | color: #FFFFFF; 70 | padding: 8px 15px; 71 | border-bottom: none; 72 | display: inline-block; 73 | margin: 10px 0px 0px 0px; 74 | } 75 | 76 | .help-page .sample-content { 77 | display: block; 78 | border-width: 0; 79 | padding: 15px 20px; 80 | background: #FFFFFF; 81 | border: 2px solid #D4D4D4; 82 | margin: 0px 0px 10px 0px; 83 | } 84 | 85 | .help-page .api-name { 86 | width: 40%; 87 | } 88 | 89 | .help-page .api-documentation { 90 | width: 60%; 91 | } 92 | 93 | .help-page .parameter-name { 94 | width: 20%; 95 | } 96 | 97 | .help-page .parameter-documentation { 98 | width: 40%; 99 | } 100 | 101 | .help-page .parameter-type { 102 | width: 20%; 103 | } 104 | 105 | .help-page .parameter-annotations { 106 | width: 20%; 107 | } 108 | 109 | .help-page h1, 110 | .help-page .h1 { 111 | font-size: 36px; 112 | line-height: normal; 113 | } 114 | 115 | .help-page h2, 116 | .help-page .h2 { 117 | font-size: 24px; 118 | } 119 | 120 | .help-page h3, 121 | .help-page .h3 { 122 | font-size: 20px; 123 | } 124 | 125 | #body.help-page { 126 | font-size: 14px; 127 | line-height: 143%; 128 | color: #333; 129 | } 130 | 131 | .help-page a { 132 | color: #0000EE; 133 | text-decoration: none; 134 | } 135 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/HelpPageAreaRegistration.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Http; 2 | using System.Web.Mvc; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 5 | { 6 | public class HelpPageAreaRegistration : AreaRegistration 7 | { 8 | public override string AreaName 9 | { 10 | get 11 | { 12 | return "HelpPage"; 13 | } 14 | } 15 | 16 | public override void RegisterArea(AreaRegistrationContext context) 17 | { 18 | context.MapRoute( 19 | "HelpPage_Default", 20 | "Help/{action}/{apiId}", 21 | new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); 22 | 23 | HelpPageConfig.Register(GlobalConfiguration.Configuration); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class CollectionModelDescription : ModelDescription 4 | { 5 | public ModelDescription ElementDescription { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ComplexTypeModelDescription : ModelDescription 6 | { 7 | public ComplexTypeModelDescription() 8 | { 9 | Properties = new Collection(); 10 | } 11 | 12 | public Collection Properties { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class DictionaryModelDescription : KeyValuePairModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class EnumTypeModelDescription : ModelDescription 7 | { 8 | public EnumTypeModelDescription() 9 | { 10 | Values = new Collection(); 11 | } 12 | 13 | public Collection Values { get; private set; } 14 | } 15 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class EnumValueDescription 4 | { 5 | public string Documentation { get; set; } 6 | 7 | public string Name { get; set; } 8 | 9 | public string Value { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 5 | { 6 | public interface IModelDocumentationProvider 7 | { 8 | string GetDocumentation(MemberInfo member); 9 | 10 | string GetDocumentation(Type type); 11 | } 12 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class KeyValuePairModelDescription : ModelDescription 4 | { 5 | public ModelDescription KeyModelDescription { get; set; } 6 | 7 | public ModelDescription ValueModelDescription { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Describes a type model. 7 | /// 8 | public abstract class ModelDescription 9 | { 10 | public string Documentation { get; set; } 11 | 12 | public Type ModelType { get; set; } 13 | 14 | public string Name { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Collections.Specialized; 5 | using System.ComponentModel.DataAnnotations; 6 | using System.Globalization; 7 | using System.Reflection; 8 | using System.Runtime.Serialization; 9 | using System.Web.Http; 10 | using System.Web.Http.Description; 11 | using System.Xml.Serialization; 12 | using Newtonsoft.Json; 13 | 14 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 15 | { 16 | /// 17 | /// Generates model descriptions for given types. 18 | /// 19 | public class ModelDescriptionGenerator 20 | { 21 | // Modify this to support more data annotation attributes. 22 | private readonly IDictionary> AnnotationTextGenerator = new Dictionary> 23 | { 24 | { typeof(RequiredAttribute), a => "Required" }, 25 | { typeof(RangeAttribute), a => 26 | { 27 | RangeAttribute range = (RangeAttribute)a; 28 | return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); 29 | } 30 | }, 31 | { typeof(MaxLengthAttribute), a => 32 | { 33 | MaxLengthAttribute maxLength = (MaxLengthAttribute)a; 34 | return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); 35 | } 36 | }, 37 | { typeof(MinLengthAttribute), a => 38 | { 39 | MinLengthAttribute minLength = (MinLengthAttribute)a; 40 | return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); 41 | } 42 | }, 43 | { typeof(StringLengthAttribute), a => 44 | { 45 | StringLengthAttribute strLength = (StringLengthAttribute)a; 46 | return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); 47 | } 48 | }, 49 | { typeof(DataTypeAttribute), a => 50 | { 51 | DataTypeAttribute dataType = (DataTypeAttribute)a; 52 | return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); 53 | } 54 | }, 55 | { typeof(RegularExpressionAttribute), a => 56 | { 57 | RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; 58 | return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); 59 | } 60 | }, 61 | }; 62 | 63 | // Modify this to add more default documentations. 64 | private readonly IDictionary DefaultTypeDocumentation = new Dictionary 65 | { 66 | { typeof(Int16), "integer" }, 67 | { typeof(Int32), "integer" }, 68 | { typeof(Int64), "integer" }, 69 | { typeof(UInt16), "unsigned integer" }, 70 | { typeof(UInt32), "unsigned integer" }, 71 | { typeof(UInt64), "unsigned integer" }, 72 | { typeof(Byte), "byte" }, 73 | { typeof(Char), "character" }, 74 | { typeof(SByte), "signed byte" }, 75 | { typeof(Uri), "URI" }, 76 | { typeof(Single), "decimal number" }, 77 | { typeof(Double), "decimal number" }, 78 | { typeof(Decimal), "decimal number" }, 79 | { typeof(String), "string" }, 80 | { typeof(Guid), "globally unique identifier" }, 81 | { typeof(TimeSpan), "time interval" }, 82 | { typeof(DateTime), "date" }, 83 | { typeof(DateTimeOffset), "date" }, 84 | { typeof(Boolean), "boolean" }, 85 | }; 86 | 87 | private Lazy _documentationProvider; 88 | 89 | public ModelDescriptionGenerator(HttpConfiguration config) 90 | { 91 | if (config == null) 92 | { 93 | throw new ArgumentNullException("config"); 94 | } 95 | 96 | _documentationProvider = new Lazy(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); 97 | GeneratedModels = new Dictionary(StringComparer.OrdinalIgnoreCase); 98 | } 99 | 100 | public Dictionary GeneratedModels { get; private set; } 101 | 102 | private IModelDocumentationProvider DocumentationProvider 103 | { 104 | get 105 | { 106 | return _documentationProvider.Value; 107 | } 108 | } 109 | 110 | public ModelDescription GetOrCreateModelDescription(Type modelType) 111 | { 112 | if (modelType == null) 113 | { 114 | throw new ArgumentNullException("modelType"); 115 | } 116 | 117 | Type underlyingType = Nullable.GetUnderlyingType(modelType); 118 | if (underlyingType != null) 119 | { 120 | modelType = underlyingType; 121 | } 122 | 123 | ModelDescription modelDescription; 124 | string modelName = ModelNameHelper.GetModelName(modelType); 125 | if (GeneratedModels.TryGetValue(modelName, out modelDescription)) 126 | { 127 | if (modelType != modelDescription.ModelType) 128 | { 129 | throw new InvalidOperationException( 130 | String.Format( 131 | CultureInfo.CurrentCulture, 132 | "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + 133 | "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", 134 | modelName, 135 | modelDescription.ModelType.FullName, 136 | modelType.FullName)); 137 | } 138 | 139 | return modelDescription; 140 | } 141 | 142 | if (DefaultTypeDocumentation.ContainsKey(modelType)) 143 | { 144 | return GenerateSimpleTypeModelDescription(modelType); 145 | } 146 | 147 | if (modelType.IsEnum) 148 | { 149 | return GenerateEnumTypeModelDescription(modelType); 150 | } 151 | 152 | if (modelType.IsGenericType) 153 | { 154 | Type[] genericArguments = modelType.GetGenericArguments(); 155 | 156 | if (genericArguments.Length == 1) 157 | { 158 | Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); 159 | if (enumerableType.IsAssignableFrom(modelType)) 160 | { 161 | return GenerateCollectionModelDescription(modelType, genericArguments[0]); 162 | } 163 | } 164 | if (genericArguments.Length == 2) 165 | { 166 | Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); 167 | if (dictionaryType.IsAssignableFrom(modelType)) 168 | { 169 | return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); 170 | } 171 | 172 | Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); 173 | if (keyValuePairType.IsAssignableFrom(modelType)) 174 | { 175 | return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); 176 | } 177 | } 178 | } 179 | 180 | if (modelType.IsArray) 181 | { 182 | Type elementType = modelType.GetElementType(); 183 | return GenerateCollectionModelDescription(modelType, elementType); 184 | } 185 | 186 | if (modelType == typeof(NameValueCollection)) 187 | { 188 | return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); 189 | } 190 | 191 | if (typeof(IDictionary).IsAssignableFrom(modelType)) 192 | { 193 | return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); 194 | } 195 | 196 | if (typeof(IEnumerable).IsAssignableFrom(modelType)) 197 | { 198 | return GenerateCollectionModelDescription(modelType, typeof(object)); 199 | } 200 | 201 | return GenerateComplexTypeModelDescription(modelType); 202 | } 203 | 204 | // Change this to provide different name for the member. 205 | private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) 206 | { 207 | JsonPropertyAttribute jsonProperty = member.GetCustomAttribute(); 208 | if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) 209 | { 210 | return jsonProperty.PropertyName; 211 | } 212 | 213 | if (hasDataContractAttribute) 214 | { 215 | DataMemberAttribute dataMember = member.GetCustomAttribute(); 216 | if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) 217 | { 218 | return dataMember.Name; 219 | } 220 | } 221 | 222 | return member.Name; 223 | } 224 | 225 | private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) 226 | { 227 | JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute(); 228 | XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute(); 229 | IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute(); 230 | NonSerializedAttribute nonSerialized = member.GetCustomAttribute(); 231 | ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute(); 232 | 233 | bool hasMemberAttribute = member.DeclaringType.IsEnum ? 234 | member.GetCustomAttribute() != null : 235 | member.GetCustomAttribute() != null; 236 | 237 | // Display member only if all the followings are true: 238 | // no JsonIgnoreAttribute 239 | // no XmlIgnoreAttribute 240 | // no IgnoreDataMemberAttribute 241 | // no NonSerializedAttribute 242 | // no ApiExplorerSettingsAttribute with IgnoreApi set to true 243 | // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute 244 | return jsonIgnore == null && 245 | xmlIgnore == null && 246 | ignoreDataMember == null && 247 | nonSerialized == null && 248 | (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && 249 | (!hasDataContractAttribute || hasMemberAttribute); 250 | } 251 | 252 | private string CreateDefaultDocumentation(Type type) 253 | { 254 | string documentation; 255 | if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) 256 | { 257 | return documentation; 258 | } 259 | if (DocumentationProvider != null) 260 | { 261 | documentation = DocumentationProvider.GetDocumentation(type); 262 | } 263 | 264 | return documentation; 265 | } 266 | 267 | private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) 268 | { 269 | List annotations = new List(); 270 | 271 | IEnumerable attributes = property.GetCustomAttributes(); 272 | foreach (Attribute attribute in attributes) 273 | { 274 | Func textGenerator; 275 | if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) 276 | { 277 | annotations.Add( 278 | new ParameterAnnotation 279 | { 280 | AnnotationAttribute = attribute, 281 | Documentation = textGenerator(attribute) 282 | }); 283 | } 284 | } 285 | 286 | // Rearrange the annotations 287 | annotations.Sort((x, y) => 288 | { 289 | // Special-case RequiredAttribute so that it shows up on top 290 | if (x.AnnotationAttribute is RequiredAttribute) 291 | { 292 | return -1; 293 | } 294 | if (y.AnnotationAttribute is RequiredAttribute) 295 | { 296 | return 1; 297 | } 298 | 299 | // Sort the rest based on alphabetic order of the documentation 300 | return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); 301 | }); 302 | 303 | foreach (ParameterAnnotation annotation in annotations) 304 | { 305 | propertyModel.Annotations.Add(annotation); 306 | } 307 | } 308 | 309 | private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) 310 | { 311 | ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); 312 | if (collectionModelDescription != null) 313 | { 314 | return new CollectionModelDescription 315 | { 316 | Name = ModelNameHelper.GetModelName(modelType), 317 | ModelType = modelType, 318 | ElementDescription = collectionModelDescription 319 | }; 320 | } 321 | 322 | return null; 323 | } 324 | 325 | private ModelDescription GenerateComplexTypeModelDescription(Type modelType) 326 | { 327 | ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription 328 | { 329 | Name = ModelNameHelper.GetModelName(modelType), 330 | ModelType = modelType, 331 | Documentation = CreateDefaultDocumentation(modelType) 332 | }; 333 | 334 | GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); 335 | bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; 336 | PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); 337 | foreach (PropertyInfo property in properties) 338 | { 339 | if (ShouldDisplayMember(property, hasDataContractAttribute)) 340 | { 341 | ParameterDescription propertyModel = new ParameterDescription 342 | { 343 | Name = GetMemberName(property, hasDataContractAttribute) 344 | }; 345 | 346 | if (DocumentationProvider != null) 347 | { 348 | propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); 349 | } 350 | 351 | GenerateAnnotations(property, propertyModel); 352 | complexModelDescription.Properties.Add(propertyModel); 353 | propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); 354 | } 355 | } 356 | 357 | FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); 358 | foreach (FieldInfo field in fields) 359 | { 360 | if (ShouldDisplayMember(field, hasDataContractAttribute)) 361 | { 362 | ParameterDescription propertyModel = new ParameterDescription 363 | { 364 | Name = GetMemberName(field, hasDataContractAttribute) 365 | }; 366 | 367 | if (DocumentationProvider != null) 368 | { 369 | propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); 370 | } 371 | 372 | complexModelDescription.Properties.Add(propertyModel); 373 | propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); 374 | } 375 | } 376 | 377 | return complexModelDescription; 378 | } 379 | 380 | private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) 381 | { 382 | ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); 383 | ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); 384 | 385 | return new DictionaryModelDescription 386 | { 387 | Name = ModelNameHelper.GetModelName(modelType), 388 | ModelType = modelType, 389 | KeyModelDescription = keyModelDescription, 390 | ValueModelDescription = valueModelDescription 391 | }; 392 | } 393 | 394 | private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) 395 | { 396 | EnumTypeModelDescription enumDescription = new EnumTypeModelDescription 397 | { 398 | Name = ModelNameHelper.GetModelName(modelType), 399 | ModelType = modelType, 400 | Documentation = CreateDefaultDocumentation(modelType) 401 | }; 402 | bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; 403 | foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) 404 | { 405 | if (ShouldDisplayMember(field, hasDataContractAttribute)) 406 | { 407 | EnumValueDescription enumValue = new EnumValueDescription 408 | { 409 | Name = field.Name, 410 | Value = field.GetRawConstantValue().ToString() 411 | }; 412 | if (DocumentationProvider != null) 413 | { 414 | enumValue.Documentation = DocumentationProvider.GetDocumentation(field); 415 | } 416 | enumDescription.Values.Add(enumValue); 417 | } 418 | } 419 | GeneratedModels.Add(enumDescription.Name, enumDescription); 420 | 421 | return enumDescription; 422 | } 423 | 424 | private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) 425 | { 426 | ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); 427 | ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); 428 | 429 | return new KeyValuePairModelDescription 430 | { 431 | Name = ModelNameHelper.GetModelName(modelType), 432 | ModelType = modelType, 433 | KeyModelDescription = keyModelDescription, 434 | ValueModelDescription = valueModelDescription 435 | }; 436 | } 437 | 438 | private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) 439 | { 440 | SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription 441 | { 442 | Name = ModelNameHelper.GetModelName(modelType), 443 | ModelType = modelType, 444 | Documentation = CreateDefaultDocumentation(modelType) 445 | }; 446 | GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); 447 | 448 | return simpleModelDescription; 449 | } 450 | } 451 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Use this attribute to change the name of the generated for a type. 7 | /// 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] 9 | public sealed class ModelNameAttribute : Attribute 10 | { 11 | public ModelNameAttribute(string name) 12 | { 13 | Name = name; 14 | } 15 | 16 | public string Name { get; private set; } 17 | } 18 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 7 | { 8 | internal static class ModelNameHelper 9 | { 10 | // Modify this to provide custom model name mapping. 11 | public static string GetModelName(Type type) 12 | { 13 | ModelNameAttribute modelNameAttribute = type.GetCustomAttribute(); 14 | if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) 15 | { 16 | return modelNameAttribute.Name; 17 | } 18 | 19 | string modelName = type.Name; 20 | if (type.IsGenericType) 21 | { 22 | // Format the generic type name to something like: GenericOfAgurment1AndArgument2 23 | Type genericType = type.GetGenericTypeDefinition(); 24 | Type[] genericArguments = type.GetGenericArguments(); 25 | string genericTypeName = genericType.Name; 26 | 27 | // Trim the generic parameter counts from the name 28 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 29 | string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); 30 | modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); 31 | } 32 | 33 | return modelName; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ParameterAnnotation 6 | { 7 | public Attribute AnnotationAttribute { get; set; } 8 | 9 | public string Documentation { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class ParameterDescription 7 | { 8 | public ParameterDescription() 9 | { 10 | Annotations = new Collection(); 11 | } 12 | 13 | public Collection Annotations { get; private set; } 14 | 15 | public string Documentation { get; set; } 16 | 17 | public string Name { get; set; } 18 | 19 | public ModelDescription TypeDescription { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class SimpleTypeModelDescription : ModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Models/HelpPageApiModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Net.Http.Headers; 4 | using System.Web.Http.Description; 5 | using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models 8 | { 9 | /// 10 | /// The model that represents an API displayed on the help page. 11 | /// 12 | public class HelpPageApiModel 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public HelpPageApiModel() 18 | { 19 | UriParameters = new Collection(); 20 | SampleRequests = new Dictionary(); 21 | SampleResponses = new Dictionary(); 22 | ErrorMessages = new Collection(); 23 | } 24 | 25 | /// 26 | /// Gets or sets the that describes the API. 27 | /// 28 | public ApiDescription ApiDescription { get; set; } 29 | 30 | /// 31 | /// Gets or sets the collection that describes the URI parameters for the API. 32 | /// 33 | public Collection UriParameters { get; private set; } 34 | 35 | /// 36 | /// Gets or sets the documentation for the request. 37 | /// 38 | public string RequestDocumentation { get; set; } 39 | 40 | /// 41 | /// Gets or sets the that describes the request body. 42 | /// 43 | public ModelDescription RequestModelDescription { get; set; } 44 | 45 | /// 46 | /// Gets the request body parameter descriptions. 47 | /// 48 | public IList RequestBodyParameters 49 | { 50 | get 51 | { 52 | return GetParameterDescriptions(RequestModelDescription); 53 | } 54 | } 55 | 56 | /// 57 | /// Gets or sets the that describes the resource. 58 | /// 59 | public ModelDescription ResourceDescription { get; set; } 60 | 61 | /// 62 | /// Gets the resource property descriptions. 63 | /// 64 | public IList ResourceProperties 65 | { 66 | get 67 | { 68 | return GetParameterDescriptions(ResourceDescription); 69 | } 70 | } 71 | 72 | /// 73 | /// Gets the sample requests associated with the API. 74 | /// 75 | public IDictionary SampleRequests { get; private set; } 76 | 77 | /// 78 | /// Gets the sample responses associated with the API. 79 | /// 80 | public IDictionary SampleResponses { get; private set; } 81 | 82 | /// 83 | /// Gets the error messages associated with this model. 84 | /// 85 | public Collection ErrorMessages { get; private set; } 86 | 87 | private static IList GetParameterDescriptions(ModelDescription modelDescription) 88 | { 89 | ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; 90 | if (complexTypeModelDescription != null) 91 | { 92 | return complexTypeModelDescription.Properties; 93 | } 94 | 95 | CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; 96 | if (collectionModelDescription != null) 97 | { 98 | complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; 99 | if (complexTypeModelDescription != null) 100 | { 101 | return complexTypeModelDescription.Properties; 102 | } 103 | } 104 | 105 | return null; 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Net.Http.Headers; 5 | 6 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 7 | { 8 | /// 9 | /// This is used to identify the place where the sample should be applied. 10 | /// 11 | public class HelpPageSampleKey 12 | { 13 | /// 14 | /// Creates a new based on media type. 15 | /// 16 | /// The media type. 17 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType) 18 | { 19 | if (mediaType == null) 20 | { 21 | throw new ArgumentNullException("mediaType"); 22 | } 23 | 24 | ActionName = String.Empty; 25 | ControllerName = String.Empty; 26 | MediaType = mediaType; 27 | ParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); 28 | } 29 | 30 | /// 31 | /// Creates a new based on media type and CLR type. 32 | /// 33 | /// The media type. 34 | /// The CLR type. 35 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) 36 | : this(mediaType) 37 | { 38 | if (type == null) 39 | { 40 | throw new ArgumentNullException("type"); 41 | } 42 | 43 | ParameterType = type; 44 | } 45 | 46 | /// 47 | /// Creates a new based on , controller name, action name and parameter names. 48 | /// 49 | /// The . 50 | /// Name of the controller. 51 | /// Name of the action. 52 | /// The parameter names. 53 | public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 54 | { 55 | if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) 56 | { 57 | throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); 58 | } 59 | if (controllerName == null) 60 | { 61 | throw new ArgumentNullException("controllerName"); 62 | } 63 | if (actionName == null) 64 | { 65 | throw new ArgumentNullException("actionName"); 66 | } 67 | if (parameterNames == null) 68 | { 69 | throw new ArgumentNullException("parameterNames"); 70 | } 71 | 72 | ControllerName = controllerName; 73 | ActionName = actionName; 74 | ParameterNames = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); 75 | SampleDirection = sampleDirection; 76 | } 77 | 78 | /// 79 | /// Creates a new based on media type, , controller name, action name and parameter names. 80 | /// 81 | /// The media type. 82 | /// The . 83 | /// Name of the controller. 84 | /// Name of the action. 85 | /// The parameter names. 86 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 87 | : this(sampleDirection, controllerName, actionName, parameterNames) 88 | { 89 | if (mediaType == null) 90 | { 91 | throw new ArgumentNullException("mediaType"); 92 | } 93 | 94 | MediaType = mediaType; 95 | } 96 | 97 | /// 98 | /// Gets the name of the controller. 99 | /// 100 | /// 101 | /// The name of the controller. 102 | /// 103 | public string ControllerName { get; private set; } 104 | 105 | /// 106 | /// Gets the name of the action. 107 | /// 108 | /// 109 | /// The name of the action. 110 | /// 111 | public string ActionName { get; private set; } 112 | 113 | /// 114 | /// Gets the media type. 115 | /// 116 | /// 117 | /// The media type. 118 | /// 119 | public MediaTypeHeaderValue MediaType { get; private set; } 120 | 121 | /// 122 | /// Gets the parameter names. 123 | /// 124 | public HashSet ParameterNames { get; private set; } 125 | 126 | public Type ParameterType { get; private set; } 127 | 128 | /// 129 | /// Gets the . 130 | /// 131 | public SampleDirection? SampleDirection { get; private set; } 132 | 133 | public override bool Equals(object obj) 134 | { 135 | HelpPageSampleKey otherKey = obj as HelpPageSampleKey; 136 | if (otherKey == null) 137 | { 138 | return false; 139 | } 140 | 141 | return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && 142 | String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && 143 | (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && 144 | ParameterType == otherKey.ParameterType && 145 | SampleDirection == otherKey.SampleDirection && 146 | ParameterNames.SetEquals(otherKey.ParameterNames); 147 | } 148 | 149 | public override int GetHashCode() 150 | { 151 | int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); 152 | if (MediaType != null) 153 | { 154 | hashCode ^= MediaType.GetHashCode(); 155 | } 156 | if (SampleDirection != null) 157 | { 158 | hashCode ^= SampleDirection.GetHashCode(); 159 | } 160 | if (ParameterType != null) 161 | { 162 | hashCode ^= ParameterType.GetHashCode(); 163 | } 164 | foreach (string parameterName in ParameterNames) 165 | { 166 | hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); 167 | } 168 | 169 | return hashCode; 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/SampleGeneration/ImageSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. 7 | /// 8 | public class ImageSample 9 | { 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | /// The URL of an image. 14 | public ImageSample(string src) 15 | { 16 | if (src == null) 17 | { 18 | throw new ArgumentNullException("src"); 19 | } 20 | Src = src; 21 | } 22 | 23 | public string Src { get; private set; } 24 | 25 | public override bool Equals(object obj) 26 | { 27 | ImageSample other = obj as ImageSample; 28 | return other != null && Src == other.Src; 29 | } 30 | 31 | public override int GetHashCode() 32 | { 33 | return Src.GetHashCode(); 34 | } 35 | 36 | public override string ToString() 37 | { 38 | return Src; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/SampleGeneration/InvalidSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. 7 | /// 8 | public class InvalidSample 9 | { 10 | public InvalidSample(string errorMessage) 11 | { 12 | if (errorMessage == null) 13 | { 14 | throw new ArgumentNullException("errorMessage"); 15 | } 16 | ErrorMessage = errorMessage; 17 | } 18 | 19 | public string ErrorMessage { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | InvalidSample other = obj as InvalidSample; 24 | return other != null && ErrorMessage == other.ErrorMessage; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return ErrorMessage.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return ErrorMessage; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/SampleGeneration/SampleDirection.cs: -------------------------------------------------------------------------------- 1 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 2 | { 3 | /// 4 | /// Indicates whether the sample is used for request or response 5 | /// 6 | public enum SampleDirection 7 | { 8 | Request = 0, 9 | Response 10 | } 11 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/SampleGeneration/TextSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. 7 | /// 8 | public class TextSample 9 | { 10 | public TextSample(string text) 11 | { 12 | if (text == null) 13 | { 14 | throw new ArgumentNullException("text"); 15 | } 16 | Text = text; 17 | } 18 | 19 | public string Text { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | TextSample other = obj as TextSample; 24 | return other != null && Text == other.Text; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return Text.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return Text; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/Api.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models 3 | @model HelpPageApiModel 4 | 5 | @{ 6 | var description = Model.ApiDescription; 7 | ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; 8 | } 9 | 10 | 11 |
12 | 19 |
20 | @Html.DisplayForModel() 21 |
22 |
23 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage 5 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models 6 | @model IGrouping 7 | 8 | @{ 9 | var controllerDocumentation = ViewBag.DocumentationProvider != null ? 10 | ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : 11 | null; 12 | } 13 | 14 |

@Model.Key.ControllerName

15 | @if (!String.IsNullOrEmpty(controllerDocumentation)) 16 | { 17 |

@controllerDocumentation

18 | } 19 | 20 | 21 | 22 | 23 | 24 | @foreach (var api in Model) 25 | { 26 | 27 | 28 | 38 | 39 | } 40 | 41 |
APIDescription
@api.HttpMethod.Method @api.RelativePath 29 | @if (api.Documentation != null) 30 | { 31 |

@api.Documentation

32 | } 33 | else 34 | { 35 |

No documentation available.

36 | } 37 |
-------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model CollectionModelDescription 3 | @if (Model.ElementDescription is ComplexTypeModelDescription) 4 | { 5 | @Html.DisplayFor(m => m.ElementDescription) 6 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model ComplexTypeModelDescription 3 | @Html.DisplayFor(m => m.Properties, "Parameters") -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model DictionaryModelDescription 3 | Dictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model EnumTypeModelDescription 3 | 4 |

Possible enumeration values:

5 | 6 | 7 | 8 | 9 | 10 | 11 | @foreach (EnumValueDescription value in Model.Values) 12 | { 13 | 14 | 15 | 18 | 21 | 22 | } 23 | 24 |
NameValueDescription
@value.Name 16 |

@value.Value

17 |
19 |

@value.Documentation

20 |
-------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Description 3 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models 4 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 5 | @model HelpPageApiModel 6 | 7 | @{ 8 | ApiDescription description = Model.ApiDescription; 9 | } 10 |

@description.HttpMethod.Method @description.RelativePath

11 |
12 |

@description.Documentation

13 | 14 |

Request Information

15 | 16 |

URI Parameters

17 | @Html.DisplayFor(m => m.UriParameters, "Parameters") 18 | 19 |

Body Parameters

20 | 21 |

@Model.RequestDocumentation

22 | 23 | @if (Model.RequestModelDescription != null) 24 | { 25 | @Html.DisplayFor(m => m.RequestModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.RequestModelDescription }) 26 | if (Model.RequestBodyParameters != null) 27 | { 28 | @Html.DisplayFor(m => m.RequestBodyParameters, "Parameters") 29 | } 30 | } 31 | else 32 | { 33 |

None.

34 | } 35 | 36 | @if (Model.SampleRequests.Count > 0) 37 | { 38 |

Request Formats

39 | @Html.DisplayFor(m => m.SampleRequests, "Samples") 40 | } 41 | 42 |

Response Information

43 | 44 |

Resource Description

45 | 46 |

@description.ResponseDescription.Documentation

47 | 48 | @if (Model.ResourceDescription != null) 49 | { 50 | @Html.DisplayFor(m => m.ResourceDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ResourceDescription }) 51 | if (Model.ResourceProperties != null) 52 | { 53 | @Html.DisplayFor(m => m.ResourceProperties, "Parameters") 54 | } 55 | } 56 | else 57 | { 58 |

None.

59 | } 60 | 61 | @if (Model.SampleResponses.Count > 0) 62 | { 63 |

Response Formats

64 | @Html.DisplayFor(m => m.SampleResponses, "Samples") 65 | } 66 | 67 |
-------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage 2 | @model ImageSample 3 | 4 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage 2 | @model InvalidSample 3 | 4 | @if (HttpContext.Current.IsDebuggingEnabled) 5 | { 6 |
7 |

@Model.ErrorMessage

8 |
9 | } 10 | else 11 | { 12 |

Sample not available.

13 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model KeyValuePairModelDescription 3 | Pair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model Type 3 | @{ 4 | ModelDescription modelDescription = ViewBag.modelDescription; 5 | if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription) 6 | { 7 | if (Model == typeof(Object)) 8 | { 9 | @:Object 10 | } 11 | else 12 | { 13 | @Html.ActionLink(modelDescription.Name, "ResourceModel", "Help", new { modelName = modelDescription.Name }, null) 14 | } 15 | } 16 | else if (modelDescription is CollectionModelDescription) 17 | { 18 | var collectionDescription = modelDescription as CollectionModelDescription; 19 | var elementDescription = collectionDescription.ElementDescription; 20 | @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, "ModelDescriptionLink", new { modelDescription = elementDescription }) 21 | } 22 | else 23 | { 24 | @Html.DisplayFor(m => modelDescription) 25 | } 26 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Collections.Generic 2 | @using System.Collections.ObjectModel 3 | @using System.Web.Http.Description 4 | @using System.Threading 5 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 6 | @model IList 7 | 8 | @if (Model.Count > 0) 9 | { 10 | 11 | 12 | 13 | 14 | 15 | @foreach (ParameterDescription parameter in Model) 16 | { 17 | ModelDescription modelDescription = parameter.TypeDescription; 18 | 19 | 20 | 23 | 26 | 39 | 40 | } 41 | 42 |
NameDescriptionTypeAdditional information
@parameter.Name 21 |

@parameter.Documentation

22 |
24 | @Html.DisplayFor(m => modelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = modelDescription }) 25 | 27 | @if (parameter.Annotations.Count > 0) 28 | { 29 | foreach (var annotation in parameter.Annotations) 30 | { 31 |

@annotation.Documentation

32 | } 33 | } 34 | else 35 | { 36 |

None.

37 | } 38 |
43 | } 44 | else 45 | { 46 |

None.

47 | } 48 | 49 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Net.Http.Headers 2 | @model Dictionary 3 | 4 | @{ 5 | // Group the samples into a single tab if they are the same. 6 | Dictionary samples = Model.GroupBy(pair => pair.Value).ToDictionary( 7 | pair => String.Join(", ", pair.Select(m => m.Key.ToString()).ToArray()), 8 | pair => pair.Key); 9 | var mediaTypes = samples.Keys; 10 | } 11 |
12 | @foreach (var mediaType in mediaTypes) 13 | { 14 |

@mediaType

15 |
16 | Sample: 17 | @{ 18 | var sample = samples[mediaType]; 19 | if (sample == null) 20 | { 21 |

Sample not available.

22 | } 23 | else 24 | { 25 | @Html.DisplayFor(s => sample); 26 | } 27 | } 28 |
29 | } 30 |
-------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 2 | @model SimpleTypeModelDescription 3 | @Model.Documentation -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml: -------------------------------------------------------------------------------- 1 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage 2 | @model TextSample 3 | 4 |
5 | @Model.Text
6 | 
-------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using System.Collections.ObjectModel 5 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.Models 6 | @model Collection 7 | 8 | @{ 9 | ViewBag.Title = "ASP.NET Web API Help Page"; 10 | 11 | // Group APIs by controller 12 | ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor); 13 | } 14 | 15 | 16 |
17 |
18 |
19 |

@ViewBag.Title

20 |
21 |
22 |
23 |
24 | 32 |
33 | @foreach (var group in apiGroups) 34 | { 35 | @Html.DisplayFor(m => group, "ApiGroup") 36 | } 37 |
38 |
39 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Help/ResourceModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions 3 | @model ModelDescription 4 | 5 | 6 |
7 | 14 |

@Model.Name

15 |

@Model.Documentation

16 |
17 | @Html.DisplayFor(m => Model) 18 |
19 |
20 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | @ViewBag.Title 7 | @RenderSection("scripts", required: false) 8 | 9 | 10 | @RenderBody() 11 | 12 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/Web.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 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | // Change the Layout path below to blend the look and feel of the help page with your existing web pages 3 | Layout = "~/Views/Shared/_Layout.cshtml"; 4 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Areas/HelpPage/XmlDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Web.Http.Controllers; 6 | using System.Web.Http.Description; 7 | using System.Xml.XPath; 8 | using WebAPI_NG_TokenbasedAuth.Areas.HelpPage.ModelDescriptions; 9 | 10 | namespace WebAPI_NG_TokenbasedAuth.Areas.HelpPage 11 | { 12 | /// 13 | /// A custom that reads the API documentation from an XML documentation file. 14 | /// 15 | public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider 16 | { 17 | private XPathNavigator _documentNavigator; 18 | private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; 19 | private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; 20 | private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; 21 | private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; 22 | private const string ParameterExpression = "param[@name='{0}']"; 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// The physical path to XML document. 28 | public XmlDocumentationProvider(string documentPath) 29 | { 30 | if (documentPath == null) 31 | { 32 | throw new ArgumentNullException("documentPath"); 33 | } 34 | XPathDocument xpath = new XPathDocument(documentPath); 35 | _documentNavigator = xpath.CreateNavigator(); 36 | } 37 | 38 | public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) 39 | { 40 | XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); 41 | return GetTagValue(typeNode, "summary"); 42 | } 43 | 44 | public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) 45 | { 46 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 47 | return GetTagValue(methodNode, "summary"); 48 | } 49 | 50 | public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) 51 | { 52 | ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; 53 | if (reflectedParameterDescriptor != null) 54 | { 55 | XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); 56 | if (methodNode != null) 57 | { 58 | string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; 59 | XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); 60 | if (parameterNode != null) 61 | { 62 | return parameterNode.Value.Trim(); 63 | } 64 | } 65 | } 66 | 67 | return null; 68 | } 69 | 70 | public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) 71 | { 72 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 73 | return GetTagValue(methodNode, "returns"); 74 | } 75 | 76 | public string GetDocumentation(MemberInfo member) 77 | { 78 | string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); 79 | string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; 80 | string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); 81 | XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); 82 | return GetTagValue(propertyNode, "summary"); 83 | } 84 | 85 | public string GetDocumentation(Type type) 86 | { 87 | XPathNavigator typeNode = GetTypeNode(type); 88 | return GetTagValue(typeNode, "summary"); 89 | } 90 | 91 | private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) 92 | { 93 | ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; 94 | if (reflectedActionDescriptor != null) 95 | { 96 | string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); 97 | return _documentNavigator.SelectSingleNode(selectExpression); 98 | } 99 | 100 | return null; 101 | } 102 | 103 | private static string GetMemberName(MethodInfo method) 104 | { 105 | string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); 106 | ParameterInfo[] parameters = method.GetParameters(); 107 | if (parameters.Length != 0) 108 | { 109 | string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); 110 | name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); 111 | } 112 | 113 | return name; 114 | } 115 | 116 | private static string GetTagValue(XPathNavigator parentNode, string tagName) 117 | { 118 | if (parentNode != null) 119 | { 120 | XPathNavigator node = parentNode.SelectSingleNode(tagName); 121 | if (node != null) 122 | { 123 | return node.Value.Trim(); 124 | } 125 | } 126 | 127 | return null; 128 | } 129 | 130 | private XPathNavigator GetTypeNode(Type type) 131 | { 132 | string controllerTypeName = GetTypeName(type); 133 | string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); 134 | return _documentNavigator.SelectSingleNode(selectExpression); 135 | } 136 | 137 | private static string GetTypeName(Type type) 138 | { 139 | string name = type.FullName; 140 | if (type.IsGenericType) 141 | { 142 | // Format the generic type name to something like: Generic{System.Int32,System.String} 143 | Type genericType = type.GetGenericTypeDefinition(); 144 | Type[] genericArguments = type.GetGenericArguments(); 145 | string genericTypeName = genericType.FullName; 146 | 147 | // Trim the generic parameter counts from the name 148 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 149 | string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); 150 | name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); 151 | } 152 | if (type.IsNested) 153 | { 154 | // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. 155 | name = name.Replace("+", "."); 156 | } 157 | 158 | return name; 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Set width on the form input elements since they're 100% wide by default */ 13 | input, 14 | select, 15 | textarea { 16 | max-width: 280px; 17 | } 18 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 System.Web.Http.ModelBinding; 10 | using Microsoft.AspNet.Identity; 11 | using Microsoft.AspNet.Identity.EntityFramework; 12 | using Microsoft.AspNet.Identity.Owin; 13 | using Microsoft.Owin.Security; 14 | using Microsoft.Owin.Security.Cookies; 15 | using Microsoft.Owin.Security.OAuth; 16 | using WebAPI_NG_TokenbasedAuth.Models; 17 | using WebAPI_NG_TokenbasedAuth.Providers; 18 | using WebAPI_NG_TokenbasedAuth.Results; 19 | 20 | namespace WebAPI_NG_TokenbasedAuth.Controllers 21 | { 22 | [Authorize] 23 | [RoutePrefix("api/Account")] 24 | public class AccountController : ApiController 25 | { 26 | private const string LocalLoginProvider = "Local"; 27 | private ApplicationUserManager _userManager; 28 | 29 | public AccountController() 30 | { 31 | } 32 | 33 | public AccountController(ApplicationUserManager userManager, 34 | ISecureDataFormat accessTokenFormat) 35 | { 36 | UserManager = userManager; 37 | AccessTokenFormat = accessTokenFormat; 38 | } 39 | 40 | public ApplicationUserManager UserManager 41 | { 42 | get 43 | { 44 | return _userManager ?? Request.GetOwinContext().GetUserManager(); 45 | } 46 | private set 47 | { 48 | _userManager = value; 49 | } 50 | } 51 | 52 | public ISecureDataFormat AccessTokenFormat { get; private set; } 53 | 54 | // GET api/Account/UserInfo 55 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 56 | [Route("UserInfo")] 57 | public UserInfoViewModel GetUserInfo() 58 | { 59 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 60 | 61 | return new UserInfoViewModel 62 | { 63 | Email = User.Identity.GetUserName(), 64 | HasRegistered = externalLogin == null, 65 | LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null 66 | }; 67 | } 68 | 69 | // POST api/Account/Logout 70 | [Route("Logout")] 71 | public IHttpActionResult Logout() 72 | { 73 | Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); 74 | return Ok(); 75 | } 76 | 77 | // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true 78 | [Route("ManageInfo")] 79 | public async Task GetManageInfo(string returnUrl, bool generateState = false) 80 | { 81 | IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); 82 | 83 | if (user == null) 84 | { 85 | return null; 86 | } 87 | 88 | List logins = new List(); 89 | 90 | foreach (IdentityUserLogin linkedAccount in user.Logins) 91 | { 92 | logins.Add(new UserLoginInfoViewModel 93 | { 94 | LoginProvider = linkedAccount.LoginProvider, 95 | ProviderKey = linkedAccount.ProviderKey 96 | }); 97 | } 98 | 99 | if (user.PasswordHash != null) 100 | { 101 | logins.Add(new UserLoginInfoViewModel 102 | { 103 | LoginProvider = LocalLoginProvider, 104 | ProviderKey = user.UserName, 105 | }); 106 | } 107 | 108 | return new ManageInfoViewModel 109 | { 110 | LocalLoginProvider = LocalLoginProvider, 111 | Email = user.UserName, 112 | Logins = logins, 113 | ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) 114 | }; 115 | } 116 | 117 | // POST api/Account/ChangePassword 118 | [Route("ChangePassword")] 119 | public async Task ChangePassword(ChangePasswordBindingModel model) 120 | { 121 | if (!ModelState.IsValid) 122 | { 123 | return BadRequest(ModelState); 124 | } 125 | 126 | IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, 127 | model.NewPassword); 128 | 129 | if (!result.Succeeded) 130 | { 131 | return GetErrorResult(result); 132 | } 133 | 134 | return Ok(); 135 | } 136 | 137 | // POST api/Account/SetPassword 138 | [Route("SetPassword")] 139 | public async Task SetPassword(SetPasswordBindingModel model) 140 | { 141 | if (!ModelState.IsValid) 142 | { 143 | return BadRequest(ModelState); 144 | } 145 | 146 | IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); 147 | 148 | if (!result.Succeeded) 149 | { 150 | return GetErrorResult(result); 151 | } 152 | 153 | return Ok(); 154 | } 155 | 156 | // POST api/Account/AddExternalLogin 157 | [Route("AddExternalLogin")] 158 | public async Task AddExternalLogin(AddExternalLoginBindingModel model) 159 | { 160 | if (!ModelState.IsValid) 161 | { 162 | return BadRequest(ModelState); 163 | } 164 | 165 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 166 | 167 | AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); 168 | 169 | if (ticket == null || ticket.Identity == null || (ticket.Properties != null 170 | && ticket.Properties.ExpiresUtc.HasValue 171 | && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) 172 | { 173 | return BadRequest("External login failure."); 174 | } 175 | 176 | ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); 177 | 178 | if (externalData == null) 179 | { 180 | return BadRequest("The external login is already associated with an account."); 181 | } 182 | 183 | IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), 184 | new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); 185 | 186 | if (!result.Succeeded) 187 | { 188 | return GetErrorResult(result); 189 | } 190 | 191 | return Ok(); 192 | } 193 | 194 | // POST api/Account/RemoveLogin 195 | [Route("RemoveLogin")] 196 | public async Task RemoveLogin(RemoveLoginBindingModel model) 197 | { 198 | if (!ModelState.IsValid) 199 | { 200 | return BadRequest(ModelState); 201 | } 202 | 203 | IdentityResult result; 204 | 205 | if (model.LoginProvider == LocalLoginProvider) 206 | { 207 | result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); 208 | } 209 | else 210 | { 211 | result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), 212 | new UserLoginInfo(model.LoginProvider, model.ProviderKey)); 213 | } 214 | 215 | if (!result.Succeeded) 216 | { 217 | return GetErrorResult(result); 218 | } 219 | 220 | return Ok(); 221 | } 222 | 223 | // GET api/Account/ExternalLogin 224 | [OverrideAuthentication] 225 | [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] 226 | [AllowAnonymous] 227 | [Route("ExternalLogin", Name = "ExternalLogin")] 228 | public async Task GetExternalLogin(string provider, string error = null) 229 | { 230 | if (error != null) 231 | { 232 | return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); 233 | } 234 | 235 | if (!User.Identity.IsAuthenticated) 236 | { 237 | return new ChallengeResult(provider, this); 238 | } 239 | 240 | ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); 241 | 242 | if (externalLogin == null) 243 | { 244 | return InternalServerError(); 245 | } 246 | 247 | if (externalLogin.LoginProvider != provider) 248 | { 249 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 250 | return new ChallengeResult(provider, this); 251 | } 252 | 253 | ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, 254 | externalLogin.ProviderKey)); 255 | 256 | bool hasRegistered = user != null; 257 | 258 | if (hasRegistered) 259 | { 260 | Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 261 | 262 | ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, 263 | OAuthDefaults.AuthenticationType); 264 | ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, 265 | CookieAuthenticationDefaults.AuthenticationType); 266 | 267 | AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 268 | Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); 269 | } 270 | else 271 | { 272 | IEnumerable claims = externalLogin.GetClaims(); 273 | ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); 274 | Authentication.SignIn(identity); 275 | } 276 | 277 | return Ok(); 278 | } 279 | 280 | // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true 281 | [AllowAnonymous] 282 | [Route("ExternalLogins")] 283 | public IEnumerable GetExternalLogins(string returnUrl, bool generateState = false) 284 | { 285 | IEnumerable descriptions = Authentication.GetExternalAuthenticationTypes(); 286 | List logins = new List(); 287 | 288 | string state; 289 | 290 | if (generateState) 291 | { 292 | const int strengthInBits = 256; 293 | state = RandomOAuthStateGenerator.Generate(strengthInBits); 294 | } 295 | else 296 | { 297 | state = null; 298 | } 299 | 300 | foreach (AuthenticationDescription description in descriptions) 301 | { 302 | ExternalLoginViewModel login = new ExternalLoginViewModel 303 | { 304 | Name = description.Caption, 305 | Url = Url.Route("ExternalLogin", new 306 | { 307 | provider = description.AuthenticationType, 308 | response_type = "token", 309 | client_id = Startup.PublicClientId, 310 | redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, 311 | state = state 312 | }), 313 | State = state 314 | }; 315 | logins.Add(login); 316 | } 317 | 318 | return logins; 319 | } 320 | 321 | // POST api/Account/Register 322 | [AllowAnonymous] 323 | [Route("Register")] 324 | public async Task Register(RegisterBindingModel model) 325 | { 326 | if (!ModelState.IsValid) 327 | { 328 | return BadRequest(ModelState); 329 | } 330 | 331 | var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; 332 | 333 | IdentityResult result = await UserManager.CreateAsync(user, model.Password); 334 | 335 | if (!result.Succeeded) 336 | { 337 | return GetErrorResult(result); 338 | } 339 | 340 | return Ok(); 341 | } 342 | 343 | // POST api/Account/RegisterExternal 344 | [OverrideAuthentication] 345 | [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] 346 | [Route("RegisterExternal")] 347 | public async Task RegisterExternal(RegisterExternalBindingModel model) 348 | { 349 | if (!ModelState.IsValid) 350 | { 351 | return BadRequest(ModelState); 352 | } 353 | 354 | var info = await Authentication.GetExternalLoginInfoAsync(); 355 | if (info == null) 356 | { 357 | return InternalServerError(); 358 | } 359 | 360 | var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; 361 | 362 | IdentityResult result = await UserManager.CreateAsync(user); 363 | if (!result.Succeeded) 364 | { 365 | return GetErrorResult(result); 366 | } 367 | 368 | result = await UserManager.AddLoginAsync(user.Id, info.Login); 369 | if (!result.Succeeded) 370 | { 371 | return GetErrorResult(result); 372 | } 373 | return Ok(); 374 | } 375 | 376 | protected override void Dispose(bool disposing) 377 | { 378 | if (disposing && _userManager != null) 379 | { 380 | _userManager.Dispose(); 381 | _userManager = null; 382 | } 383 | 384 | base.Dispose(disposing); 385 | } 386 | 387 | #region Helpers 388 | 389 | private IAuthenticationManager Authentication 390 | { 391 | get { return Request.GetOwinContext().Authentication; } 392 | } 393 | 394 | private IHttpActionResult GetErrorResult(IdentityResult result) 395 | { 396 | if (result == null) 397 | { 398 | return InternalServerError(); 399 | } 400 | 401 | if (!result.Succeeded) 402 | { 403 | if (result.Errors != null) 404 | { 405 | foreach (string error in result.Errors) 406 | { 407 | ModelState.AddModelError("", error); 408 | } 409 | } 410 | 411 | if (ModelState.IsValid) 412 | { 413 | // No ModelState errors are available to send, so just return an empty BadRequest. 414 | return BadRequest(); 415 | } 416 | 417 | return BadRequest(ModelState); 418 | } 419 | 420 | return null; 421 | } 422 | 423 | private class ExternalLoginData 424 | { 425 | public string LoginProvider { get; set; } 426 | public string ProviderKey { get; set; } 427 | public string UserName { get; set; } 428 | 429 | public IList GetClaims() 430 | { 431 | IList claims = new List(); 432 | claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); 433 | 434 | if (UserName != null) 435 | { 436 | claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); 437 | } 438 | 439 | return claims; 440 | } 441 | 442 | public static ExternalLoginData FromIdentity(ClaimsIdentity identity) 443 | { 444 | if (identity == null) 445 | { 446 | return null; 447 | } 448 | 449 | Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); 450 | 451 | if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) 452 | || String.IsNullOrEmpty(providerKeyClaim.Value)) 453 | { 454 | return null; 455 | } 456 | 457 | if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) 458 | { 459 | return null; 460 | } 461 | 462 | return new ExternalLoginData 463 | { 464 | LoginProvider = providerKeyClaim.Issuer, 465 | ProviderKey = providerKeyClaim.Value, 466 | UserName = identity.FindFirstValue(ClaimTypes.Name) 467 | }; 468 | } 469 | } 470 | 471 | private static class RandomOAuthStateGenerator 472 | { 473 | private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); 474 | 475 | public static string Generate(int strengthInBits) 476 | { 477 | const int bitsPerByte = 8; 478 | 479 | if (strengthInBits % bitsPerByte != 0) 480 | { 481 | throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); 482 | } 483 | 484 | int strengthInBytes = strengthInBits / bitsPerByte; 485 | 486 | byte[] data = new byte[strengthInBytes]; 487 | _random.GetBytes(data); 488 | return HttpServerUtility.UrlTokenEncode(data); 489 | } 490 | } 491 | 492 | #endregion 493 | } 494 | } 495 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Controllers/EmployeeAPIController.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.Web.Http; 7 | using WebAPI_NG_TokenbasedAuth.Models; 8 | 9 | namespace WebAPI_NG_TokenbasedAuth.Controllers 10 | { 11 | [Authorize] 12 | public class EmployeeAPIController : ApiController 13 | { 14 | public List Get() 15 | { 16 | return new EmployeeDatabase(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Controllers/EmployeeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Controllers 8 | { 9 | public class EmployeeController : Controller 10 | { 11 | // GET: Employee 12 | public ActionResult Index() 13 | { 14 | return View(); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Controllers 8 | { 9 | public class HomeController : Controller 10 | { 11 | public ActionResult Index() 12 | { 13 | ViewBag.Title = "Home Page"; 14 | 15 | return View(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Controllers/LoginController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Controllers 8 | { 9 | [AllowAnonymous] 10 | public class LoginController : Controller 11 | { 12 | // GET: Login 13 | public ActionResult SecurityInfo() 14 | { 15 | return View(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Controllers/ValuesController.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.Web.Http; 7 | 8 | namespace WebAPI_NG_TokenbasedAuth.Controllers 9 | { 10 | [Authorize] 11 | public class ValuesController : ApiController 12 | { 13 | // GET api/values 14 | public IEnumerable Get() 15 | { 16 | return new string[] { "value1", "value2" }; 17 | } 18 | 19 | // GET api/values/5 20 | public string Get(int id) 21 | { 22 | return "value"; 23 | } 24 | 25 | // POST api/values 26 | public void Post([FromBody]string value) 27 | { 28 | } 29 | 30 | // PUT api/values/5 31 | public void Put(int id, [FromBody]string value) 32 | { 33 | } 34 | 35 | // DELETE api/values/5 36 | public void Delete(int id) 37 | { 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="WebAPI_NG_TokenbasedAuth.WebApiApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Http; 6 | using System.Web.Mvc; 7 | using System.Web.Optimization; 8 | using System.Web.Routing; 9 | 10 | namespace WebAPI_NG_TokenbasedAuth 11 | { 12 | public class WebApiApplication : System.Web.HttpApplication 13 | { 14 | protected void Application_Start() 15 | { 16 | AreaRegistration.RegisterAllAreas(); 17 | GlobalConfiguration.Configure(WebApiConfig.Register); 18 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 19 | RouteConfig.RegisterRoutes(RouteTable.Routes); 20 | BundleConfig.RegisterBundles(BundleTable.Bundles); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Models/AccountBindingModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using Newtonsoft.Json; 4 | 5 | namespace WebAPI_NG_TokenbasedAuth.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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Models/AccountViewModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace WebAPI_NG_TokenbasedAuth.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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Models/EmployeeModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace WebAPI_NG_TokenbasedAuth.Models 4 | { 5 | public class Employee 6 | { 7 | public int EmpNo { get; set; } 8 | public string EmpName { get; set; } 9 | public int Salary { get; set; } 10 | public string DeptName { get; set; } 11 | } 12 | 13 | public class EmployeeDatabase : List 14 | { 15 | public EmployeeDatabase() 16 | { 17 | Add(new Employee() { EmpNo = 101, EmpName = "TS", Salary = 12000, DeptName = "IT" }); 18 | Add(new Employee() { EmpNo = 102, EmpName = "MS", Salary = 22000, DeptName = "System" }); 19 | Add(new Employee() { EmpNo = 103, EmpName = "LS", Salary = 21000, DeptName = "Sales" }); 20 | Add(new Employee() { EmpNo = 104, EmpName = "VB", Salary = 32000, DeptName = "HRD" }); 21 | Add(new Employee() { EmpNo = 105, EmpName = "PB", Salary = 42000, DeptName = "HRD" }); 22 | Add(new Employee() { EmpNo = 106, EmpName = "AB", Salary = 12000, DeptName = "Admin" }); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Models/IdentityModels.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNet.Identity; 4 | using Microsoft.AspNet.Identity.EntityFramework; 5 | using Microsoft.AspNet.Identity.Owin; 6 | 7 | namespace WebAPI_NG_TokenbasedAuth.Models 8 | { 9 | // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. 10 | public class ApplicationUser : IdentityUser 11 | { 12 | public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType) 13 | { 14 | // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 15 | var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 16 | // Add custom user claims here 17 | return userIdentity; 18 | } 19 | } 20 | 21 | public class ApplicationDbContext : IdentityDbContext 22 | { 23 | public ApplicationDbContext() 24 | : base("DefaultConnection", throwIfV1Schema: false) 25 | { 26 | } 27 | 28 | public static ApplicationDbContext Create() 29 | { 30 | return new ApplicationDbContext(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Project_Readme.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Your ASP.NET application 6 | 95 | 96 | 97 | 98 | 102 | 103 |
104 |
105 |

This application consists of:

106 |
    107 |
  • Help Page for documenting your Web APIs
  • 108 |
  • Theming using Bootstrap
  • 109 |
  • Authentication, if selected, shows how to register and sign in
  • 110 |
  • ASP.NET features managed using NuGet
  • 111 |
112 |
113 | 114 | 130 | 131 |
132 |

Deploy

133 | 138 |
139 | 140 |
141 |

Get help

142 | 146 |
147 |
148 | 149 | 150 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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("WebAPI_NG_TokenbasedAuth")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("WebAPI_NG_TokenbasedAuth")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 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("4351a4c6-ee8f-4063-8929-4062fc8fa58f")] 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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 WebAPI_NG_TokenbasedAuth.Models; 13 | 14 | namespace WebAPI_NG_TokenbasedAuth.Providers 15 | { 16 | public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 17 | { 18 | private readonly string _publicClientId; 19 | 20 | public ApplicationOAuthProvider(string publicClientId) 21 | { 22 | if (publicClientId == null) 23 | { 24 | throw new ArgumentNullException("publicClientId"); 25 | } 26 | 27 | _publicClientId = publicClientId; 28 | } 29 | 30 | public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 31 | { 32 | var userManager = context.OwinContext.GetUserManager(); 33 | 34 | ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 35 | 36 | if (user == null) 37 | { 38 | context.SetError("invalid_grant", "The user name or password is incorrect."); 39 | return; 40 | } 41 | 42 | ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 43 | OAuthDefaults.AuthenticationType); 44 | ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 45 | 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 | } -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 WebAPI_NG_TokenbasedAuth.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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/MyScripts/EmpService.js: -------------------------------------------------------------------------------- 1 | //1. 2 | app.service('empservice', function ($http) { 3 | this.get = function () { 4 | 5 | var accesstoken = sessionStorage.getItem('accessToken'); 6 | 7 | var authHeaders = {}; 8 | if (accesstoken) { 9 | authHeaders.Authorization = 'Bearer ' + accesstoken; 10 | } 11 | 12 | var response = $http({ 13 | url: "/api/EmployeeAPI", 14 | method: "GET", 15 | headers: authHeaders 16 | }); 17 | return response; 18 | }; 19 | }); 20 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/MyScripts/EmployeeController.js: -------------------------------------------------------------------------------- 1 | //1. 2 | app.controller('emplcontroller', function ($scope, empservice) { 3 | $scope.Employees = []; 4 | 5 | $scope.Message = ""; 6 | $scope.userName = sessionStorage.getItem('userName'); 7 | 8 | 9 | loadEmployees(); 10 | 11 | function loadEmployees() { 12 | 13 | 14 | var promise = empservice.get(); 15 | promise.then(function (resp) { 16 | $scope.Employees = resp.data; 17 | $scope.Message = "Call Completed Successfully"; 18 | }, function (err) { 19 | $scope.Message = "Error!!! " + err.status 20 | }); 21 | }; 22 | $scope.logout = function () { 23 | 24 | sessionStorage.removeItem('accessToken'); 25 | window.location.href = '/Login/SecurityInfo'; 26 | }; 27 | }); -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/MyScripts/LoginLogic.js: -------------------------------------------------------------------------------- 1 |  2 | 3 | //The Service Containing functions for Register User and 4 | //User Login 5 | app.service('loginservice', function ($http) { 6 | 7 | this.register = function (userInfo) { 8 | var resp = $http({ 9 | url: "/api/Account/Register", 10 | method: "POST", 11 | data: userInfo, 12 | }); 13 | return resp; 14 | }; 15 | 16 | this.login = function (userlogin) { 17 | 18 | var resp = $http({ 19 | url: "/TOKEN", 20 | method: "POST", 21 | data: $.param({ grant_type: 'password', username: userlogin.username, password: userlogin.password }), 22 | headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 23 | }); 24 | return resp; 25 | }; 26 | }); 27 | 28 | app.controller('logincontroller', function ($scope, loginservice) { 29 | 30 | //Scope Declaration 31 | $scope.responseData = ""; 32 | 33 | $scope.userName = ""; 34 | 35 | $scope.userRegistrationEmail = ""; 36 | $scope.userRegistrationPassword = ""; 37 | $scope.userRegistrationConfirmPassword = ""; 38 | 39 | $scope.userLoginEmail = ""; 40 | $scope.userLoginPassword = ""; 41 | 42 | $scope.accessToken = ""; 43 | $scope.refreshToken = ""; 44 | //Ends Here 45 | 46 | //Functionn to register user 47 | $scope.registerUser = function () { 48 | 49 | $scope.responseData = ""; 50 | 51 | //The User Registration Information 52 | var userRegistrationInfo = { 53 | Email: $scope.userRegistrationEmail, 54 | Password: $scope.userRegistrationPassword, 55 | ConfirmPassword: $scope.userRegistrationConfirmPassword 56 | }; 57 | 58 | var promiseregister = loginservice.register(userRegistrationInfo); 59 | 60 | promiseregister.then(function (resp) { 61 | $scope.responseData = "User is Successfully"; 62 | $scope.userRegistrationEmail=""; 63 | $scope.userRegistrationPassword=""; 64 | $scope.userRegistrationConfirmPassword=""; 65 | }, function (err) { 66 | $scope.responseData="Error " + err.status; 67 | }); 68 | }; 69 | 70 | 71 | $scope.redirect = function () { 72 | window.location.href = '/Employee/Index'; 73 | }; 74 | 75 | //Function to Login. This will generate Token 76 | $scope.login = function () { 77 | //This is the information to pass for token based authentication 78 | var userLogin = { 79 | grant_type: 'password', 80 | username: $scope.userLoginEmail, 81 | password: $scope.userLoginPassword 82 | }; 83 | 84 | var promiselogin = loginservice.login(userLogin); 85 | 86 | promiselogin.then(function (resp) { 87 | 88 | $scope.userName = resp.data.userName; 89 | //Store the token information in the SessionStorage 90 | //So that it can be accessed for other views 91 | sessionStorage.setItem('userName', resp.data.userName); 92 | sessionStorage.setItem('accessToken', resp.data.access_token); 93 | sessionStorage.setItem('refreshToken', resp.data.refresh_token); 94 | window.location.href = '/Employee/Index'; 95 | }, function (err) { 96 | 97 | $scope.responseData="Error " + err.status; 98 | }); 99 | 100 | }; 101 | }); 102 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/MyScripts/Module.js: -------------------------------------------------------------------------------- 1 | var app; 2 | 3 | app = angular.module('appmodule',[]); -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/Scripts/_references.js -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/jquery.validate.unobtrusive.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /* 16 | ** Unobtrusive validation support library for jQuery and jQuery Validate 17 | ** Copyright (C) Microsoft Corporation. All rights reserved. 18 | */ 19 | (function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?a.parseJSON(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("
  • ").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?a.parseJSON(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&b.empty()}}function n(){var b=a(this),c="__jquery_unobtrusive_validation_form_reset";if(b.data(c))return;b.data(c,true);try{b.data("validator").resetForm()}finally{b.removeData(c)}b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(b){var c=a(b),f=c.data(e),i=a.proxy(n,b),g=d.unobtrusive.options||{},h=function(e,d){var c=g[e];c&&a.isFunction(c)&&c.apply(b,d)};if(!f){f={options:{errorClass:g.errorClass||"input-validation-error",errorElement:g.errorElement||"span",errorPlacement:function(){m.apply(b,arguments);h("errorPlacement",arguments)},invalidHandler:function(){l.apply(b,arguments);h("invalidHandler",arguments)},messages:{},rules:{},success:function(){k.apply(b,arguments);h("success",arguments)}},attachValidation:function(){c.off("reset."+e,i).on("reset."+e,i).validate(this.options)},validate:function(){c.validate();return c.valid()}};c.data(e,f)}return f}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(c){var b=a(c),e=b.parents().addBack().filter("form").add(b.find("form")).has("[data-val=true]");b.find("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});e.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input").filter("[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){var d=a(b.form).find(":input").filter("[name='"+f(c)+"']");return d.is(":checkbox")?d.filter(":checked").val()||d.filter(":hidden").val()||"":d.is(":radio")?d.filter(":checked").val()||"":d.val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery); -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/respond.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 16 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 17 | window.matchMedia = window.matchMedia || (function(doc, undefined){ 18 | 19 | var bool, 20 | docElem = doc.documentElement, 21 | refNode = docElem.firstElementChild || docElem.firstChild, 22 | // fakeBody required for 23 | fakeBody = doc.createElement('body'), 24 | div = doc.createElement('div'); 25 | 26 | div.id = 'mq-test-1'; 27 | div.style.cssText = "position:absolute;top:-100em"; 28 | fakeBody.style.background = "none"; 29 | fakeBody.appendChild(div); 30 | 31 | return function(q){ 32 | 33 | div.innerHTML = '­'; 34 | 35 | docElem.insertBefore(fakeBody, refNode); 36 | bool = div.offsetWidth == 42; 37 | docElem.removeChild(fakeBody); 38 | 39 | return { matches: bool, media: q }; 40 | }; 41 | 42 | })(document); 43 | 44 | 45 | 46 | 47 | /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 48 | (function( win ){ 49 | //exposed namespace 50 | win.respond = {}; 51 | 52 | //define update even in native-mq-supporting browsers, to avoid errors 53 | respond.update = function(){}; 54 | 55 | //expose media query support flag for external use 56 | respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches; 57 | 58 | //if media queries are supported, exit here 59 | if( respond.mediaQueriesSupported ){ return; } 60 | 61 | //define vars 62 | var doc = win.document, 63 | docElem = doc.documentElement, 64 | mediastyles = [], 65 | rules = [], 66 | appendedEls = [], 67 | parsedSheets = {}, 68 | resizeThrottle = 30, 69 | head = doc.getElementsByTagName( "head" )[0] || docElem, 70 | base = doc.getElementsByTagName( "base" )[0], 71 | links = head.getElementsByTagName( "link" ), 72 | requestQueue = [], 73 | 74 | //loop stylesheets, send text content to translate 75 | ripCSS = function(){ 76 | var sheets = links, 77 | sl = sheets.length, 78 | i = 0, 79 | //vars for loop: 80 | sheet, href, media, isCSS; 81 | 82 | for( ; i < sl; i++ ){ 83 | sheet = sheets[ i ], 84 | href = sheet.href, 85 | media = sheet.media, 86 | isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; 87 | 88 | //only links plz and prevent re-parsing 89 | if( !!href && isCSS && !parsedSheets[ href ] ){ 90 | // selectivizr exposes css through the rawCssText expando 91 | if (sheet.styleSheet && sheet.styleSheet.rawCssText) { 92 | translate( sheet.styleSheet.rawCssText, href, media ); 93 | parsedSheets[ href ] = true; 94 | } else { 95 | if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) 96 | || href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){ 97 | requestQueue.push( { 98 | href: href, 99 | media: media 100 | } ); 101 | } 102 | } 103 | } 104 | } 105 | makeRequests(); 106 | }, 107 | 108 | //recurse through request queue, get css text 109 | makeRequests = function(){ 110 | if( requestQueue.length ){ 111 | var thisRequest = requestQueue.shift(); 112 | 113 | ajax( thisRequest.href, function( styles ){ 114 | translate( styles, thisRequest.href, thisRequest.media ); 115 | parsedSheets[ thisRequest.href ] = true; 116 | makeRequests(); 117 | } ); 118 | } 119 | }, 120 | 121 | //find media blocks in css text, convert to style blocks 122 | translate = function( styles, href, media ){ 123 | var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ), 124 | ql = qs && qs.length || 0, 125 | //try to get CSS path 126 | href = href.substring( 0, href.lastIndexOf( "/" )), 127 | repUrls = function( css ){ 128 | return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" ); 129 | }, 130 | useMedia = !ql && media, 131 | //vars used in loop 132 | i = 0, 133 | j, fullq, thisq, eachq, eql; 134 | 135 | //if path exists, tack on trailing slash 136 | if( href.length ){ href += "/"; } 137 | 138 | //if no internal queries exist, but media attr does, use that 139 | //note: this currently lacks support for situations where a media attr is specified on a link AND 140 | //its associated stylesheet has internal CSS media queries. 141 | //In those cases, the media attribute will currently be ignored. 142 | if( useMedia ){ 143 | ql = 1; 144 | } 145 | 146 | 147 | for( ; i < ql; i++ ){ 148 | j = 0; 149 | 150 | //media attr 151 | if( useMedia ){ 152 | fullq = media; 153 | rules.push( repUrls( styles ) ); 154 | } 155 | //parse for styles 156 | else{ 157 | fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1; 158 | rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); 159 | } 160 | 161 | eachq = fullq.split( "," ); 162 | eql = eachq.length; 163 | 164 | for( ; j < eql; j++ ){ 165 | thisq = eachq[ j ]; 166 | mediastyles.push( { 167 | media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all", 168 | rules : rules.length - 1, 169 | hasquery: thisq.indexOf("(") > -1, 170 | minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), 171 | maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) 172 | } ); 173 | } 174 | } 175 | 176 | applyMedia(); 177 | }, 178 | 179 | lastCall, 180 | 181 | resizeDefer, 182 | 183 | // returns the value of 1em in pixels 184 | getEmValue = function() { 185 | var ret, 186 | div = doc.createElement('div'), 187 | body = doc.body, 188 | fakeUsed = false; 189 | 190 | div.style.cssText = "position:absolute;font-size:1em;width:1em"; 191 | 192 | if( !body ){ 193 | body = fakeUsed = doc.createElement( "body" ); 194 | body.style.background = "none"; 195 | } 196 | 197 | body.appendChild( div ); 198 | 199 | docElem.insertBefore( body, docElem.firstChild ); 200 | 201 | ret = div.offsetWidth; 202 | 203 | if( fakeUsed ){ 204 | docElem.removeChild( body ); 205 | } 206 | else { 207 | body.removeChild( div ); 208 | } 209 | 210 | //also update eminpx before returning 211 | ret = eminpx = parseFloat(ret); 212 | 213 | return ret; 214 | }, 215 | 216 | //cached container for 1em value, populated the first time it's needed 217 | eminpx, 218 | 219 | //enable/disable styles 220 | applyMedia = function( fromResize ){ 221 | var name = "clientWidth", 222 | docElemProp = docElem[ name ], 223 | currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, 224 | styleBlocks = {}, 225 | lastLink = links[ links.length-1 ], 226 | now = (new Date()).getTime(); 227 | 228 | //throttle resize calls 229 | if( fromResize && lastCall && now - lastCall < resizeThrottle ){ 230 | clearTimeout( resizeDefer ); 231 | resizeDefer = setTimeout( applyMedia, resizeThrottle ); 232 | return; 233 | } 234 | else { 235 | lastCall = now; 236 | } 237 | 238 | for( var i in mediastyles ){ 239 | var thisstyle = mediastyles[ i ], 240 | min = thisstyle.minw, 241 | max = thisstyle.maxw, 242 | minnull = min === null, 243 | maxnull = max === null, 244 | em = "em"; 245 | 246 | if( !!min ){ 247 | min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 248 | } 249 | if( !!max ){ 250 | max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 251 | } 252 | 253 | // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true 254 | if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ 255 | if( !styleBlocks[ thisstyle.media ] ){ 256 | styleBlocks[ thisstyle.media ] = []; 257 | } 258 | styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); 259 | } 260 | } 261 | 262 | //remove any existing respond style element(s) 263 | for( var i in appendedEls ){ 264 | if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){ 265 | head.removeChild( appendedEls[ i ] ); 266 | } 267 | } 268 | 269 | //inject active styles, grouped by media type 270 | for( var i in styleBlocks ){ 271 | var ss = doc.createElement( "style" ), 272 | css = styleBlocks[ i ].join( "\n" ); 273 | 274 | ss.type = "text/css"; 275 | ss.media = i; 276 | 277 | //originally, ss was appended to a documentFragment and sheets were appended in bulk. 278 | //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! 279 | head.insertBefore( ss, lastLink.nextSibling ); 280 | 281 | if ( ss.styleSheet ){ 282 | ss.styleSheet.cssText = css; 283 | } 284 | else { 285 | ss.appendChild( doc.createTextNode( css ) ); 286 | } 287 | 288 | //push to appendedEls to track for later removal 289 | appendedEls.push( ss ); 290 | } 291 | }, 292 | //tweaked Ajax functions from Quirksmode 293 | ajax = function( url, callback ) { 294 | var req = xmlHttp(); 295 | if (!req){ 296 | return; 297 | } 298 | req.open( "GET", url, true ); 299 | req.onreadystatechange = function () { 300 | if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){ 301 | return; 302 | } 303 | callback( req.responseText ); 304 | } 305 | if ( req.readyState == 4 ){ 306 | return; 307 | } 308 | req.send( null ); 309 | }, 310 | //define ajax obj 311 | xmlHttp = (function() { 312 | var xmlhttpmethod = false; 313 | try { 314 | xmlhttpmethod = new XMLHttpRequest(); 315 | } 316 | catch( e ){ 317 | xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" ); 318 | } 319 | return function(){ 320 | return xmlhttpmethod; 321 | }; 322 | })(); 323 | 324 | //translate CSS 325 | ripCSS(); 326 | 327 | //expose update for re-running respond later on 328 | respond.update = ripCSS; 329 | 330 | //adjust on resize 331 | function callMedia(){ 332 | applyMedia( true ); 333 | } 334 | if( win.addEventListener ){ 335 | win.addEventListener( "resize", callMedia, false ); 336 | } 337 | else if( win.attachEvent ){ 338 | win.attachEvent( "onresize", callMedia ); 339 | } 340 | })(this); 341 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Scripts/respond.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 16 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 17 | window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='­';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document); 18 | 19 | /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 20 | (function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this); -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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(WebAPI_NG_TokenbasedAuth.Startup))] 8 | 9 | namespace WebAPI_NG_TokenbasedAuth 10 | { 11 | public partial class Startup 12 | { 13 | public void Configuration(IAppBuilder app) 14 | { 15 | ConfigureAuth(app); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Employee/Index.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |

    Employee Information

    7 | 8 |

    9 | {{userName}} 10 | 11 |

    12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 27 | 30 | 33 | 36 | 37 | 38 |
    EmpNoEmpNameSalaryDeptName
    25 | {{Emp.EmpNo}} 26 | 28 | {{Emp.EmpName}} 29 | 31 | {{Emp.Salary}} 32 | 34 | {{Emp.DeptName}} 35 |
    39 |
    40 | {{Message}} 41 |
    42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | 
    2 |

    ASP.NET

    3 |

    ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.

    4 |

    Learn more »

    5 |
    6 |
    7 |
    8 |

    Getting started

    9 |

    ASP.NET Web API is a framework that makes it easy to build HTTP services that reach 10 | a broad range of clients, including browsers and mobile devices. ASP.NET Web API 11 | is an ideal platform for building RESTful applications on the .NET Framework.

    12 |

    Learn more »

    13 |
    14 |
    15 |

    Get more libraries

    16 |

    NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

    17 |

    Learn more »

    18 |
    19 |
    20 |

    Web Hosting

    21 |

    You can easily find a web hosting company that offers the right mix of features and price for your applications.

    22 |

    Learn more »

    23 |
    24 |
    25 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Login/Index.cshtml: -------------------------------------------------------------------------------- 1 |  2 | @{ 3 | ViewBag.Title = "Index"; 4 | } 5 | 6 |

    Index

    7 | 8 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Login/SecurityInfo.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |

    The Security Information View

    7 | 8 | 9 | 42 | 43 | 44 | 74 | 75 |
    10 | 11 | 12 | 13 | 17 | 18 | 19 | 20 | 24 | 25 | 26 | 27 | 31 | 32 | 33 | 34 | 39 | 40 |
    Email: 14 | 16 |
    Password: 21 | 23 |
    Confirm Password: 28 | 30 |
    35 | 38 |
    41 |
    45 | 46 | 47 | 48 | 52 | 53 | 54 | 55 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 71 | 72 |
    Email: 49 | 51 |
    Password: 56 | 59 |
    68 | 70 |
    73 |
    76 | 77 |
    78 | 79 |
    80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Error 6 | 7 | 8 |
    9 |

    Error.

    10 |

    An error occurred while processing your request.

    11 |
    12 | 13 | 14 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewBag.Title 7 | @Styles.Render("~/Content/css") 8 | @Scripts.Render("~/bundles/modernizr") 9 | 10 | 11 | 29 |
    30 | @RenderBody() 31 |
    32 |
    33 |

    © @DateTime.Now.Year - My ASP.NET Application

    34 |
    35 |
    36 | 37 | @Scripts.Render("~/bundles/jquery") 38 | @Scripts.Render("~/bundles/bootstrap") 39 | @RenderSection("scripts", required: false) 40 | 41 | 42 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/Web.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 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/WebAPI_NG_TokenbasedAuth.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 600 5 | True 6 | False 7 | False 8 | 9 | False 10 | 600 11 | ProjectFiles 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 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/favicon.ico -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.csproj.FileListAbsolute.txt: -------------------------------------------------------------------------------- 1 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\csc.exe 2 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.Build.Tasks.CodeAnalysis.dll 3 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.CodeAnalysis.CSharp.dll 4 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.CodeAnalysis.dll 5 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.CodeAnalysis.VisualBasic.dll 6 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.CSharp.Core.targets 7 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\Microsoft.VisualBasic.Core.targets 8 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\System.Collections.Immutable.dll 9 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\System.Reflection.Metadata.dll 10 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\vbc.exe 11 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\VBCSCompiler.exe 12 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\roslyn\VBCSCompiler.exe.config 13 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\WebAPI_NG_TokenbasedAuth.dll.config 14 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\WebAPI_NG_TokenbasedAuth.dll 15 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\WebAPI_NG_TokenbasedAuth.pdb 16 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Antlr3.Runtime.dll 17 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\EntityFramework.dll 18 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\EntityFramework.SqlServer.dll 19 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.Core.dll 20 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.EntityFramework.dll 21 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.Owin.dll 22 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll 23 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.dll 24 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Host.SystemWeb.dll 25 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Cookies.dll 26 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.dll 27 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Facebook.dll 28 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Google.dll 29 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.MicrosoftAccount.dll 30 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.OAuth.dll 31 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Twitter.dll 32 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Web.Infrastructure.dll 33 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Newtonsoft.Json.dll 34 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Owin.dll 35 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Net.Http.Formatting.dll 36 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Helpers.dll 37 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.dll 38 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.Owin.dll 39 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.WebHost.dll 40 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Mvc.dll 41 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Optimization.dll 42 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Razor.dll 43 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.Deployment.dll 44 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.dll 45 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.Razor.dll 46 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\WebGrease.dll 47 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.xml 48 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Newtonsoft.Json.xml 49 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Net.Http.Formatting.xml 50 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Helpers.xml 51 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.xml 52 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.WebHost.xml 53 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Mvc.xml 54 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Optimization.xml 55 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Razor.xml 56 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.xml 57 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.Deployment.xml 58 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.WebPages.Razor.xml 59 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Antlr3.Runtime.pdb 60 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\EntityFramework.xml 61 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\EntityFramework.SqlServer.xml 62 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.Core.xml 63 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.Owin.xml 64 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.AspNet.Identity.EntityFramework.xml 65 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.xml 66 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Host.SystemWeb.xml 67 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.xml 68 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Facebook.xml 69 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Cookies.xml 70 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.OAuth.xml 71 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Google.xml 72 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.Twitter.xml 73 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\Microsoft.Owin.Security.MicrosoftAccount.xml 74 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\bin\System.Web.Http.Owin.xml 75 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\obj\Debug\WebAPI_NG_TokenbasedAuth.csprojResolveAssemblyReference.cache 76 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\obj\Debug\WebAPI_NG_TokenbasedAuth.dll 77 | E:\Mahesh_New\Articles\Oct15\WebAPI_NG_TokenbasedAuth\WebAPI_NG_TokenbasedAuth\obj\Debug\WebAPI_NG_TokenbasedAuth.pdb 78 | -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.csprojResolveAssemblyReference.cache: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.csprojResolveAssemblyReference.cache -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.dll -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dotnetcurry/Secure-ASP.NET-WebAPI-using-Tokens/c3760e9f614d78e75ce3d0c807d7a82829a0ef5d/WebAPI_NG_TokenbasedAuth/obj/Debug/WebAPI_NG_TokenbasedAuth.pdb -------------------------------------------------------------------------------- /WebAPI_NG_TokenbasedAuth/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | --------------------------------------------------------------------------------