This sample shows how to perform local login in ASP.NET Web API.
If you want to recreate this app from scratch, here are the steps that I followed.
-
Create a new ASP.NET Web Application project. In the New Project dialog, select the Web API template.
-
If the dialog does not list Individual User Accounts under Authentication, click Change Authentication. Then select Individual User Accounts.
-
Add Knockout.js to the project, using NuGet. From the Tools menu, select NuGet Package Manager > Package Manager Console. In the console window, type the following command.
Install-Package knockoutjs
This adds the Knockout.js files to your Scripts folder.
-
In App_Start/BundleConfig.cs, add a new script bundle.
bundles.Add(new ScriptBundle("~/bundles/app").Include( "~/Scripts/knockout-{version}.js", "~/Scripts/app.js"));
-
Add the app.js file to Scripts folder. The code in app.js defines a view model for Knockout.js. The view model data-binds to the HTML form controls in the app.
-
Update Views/Home/Index.cshtml with the app UI. This file defines the MVC view for the home page.
-
Enforce SSL.
-
Add the
RequireHttpsAttribute
filter to the MVC pipeline.public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); // New code: filters.Add(new RequireHttpsAttribute()); }
-
Add a custom
RequireHttpsAttribute
filter to the Web API pipeline. (See Working with SSL in Web API.)config.Filters.Add(new LocalAccountsApp.Filters.RequireHttpsAttribute());
-
Remove
AllowInsecureHttp
fromOAuthOptions
.OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14) //AllowInsecureHttp = true };
-
I replaced the
ValuesController
class with the following code, just to make the Web API responses more interesting.[Authorize] public class ValuesController : ApiController { // GET api/values public string Get() { var userName = this.RequestContext.Principal.Identity.Name; return String.Format("Hello, {0}.", userName); } }
This code adds the user name to the response, which shows the request has a valid principal.