In this artilce I will talk about authorization in ASP.NET MVC 4 WebAPI using Authorize attribute.
Let's write code:
Step 1: Download code from Hello WebAPI or follow the steps provided in the article.
Step 2: Browse DemoWebAPI.html and click on Update/Save Customer or any button and you will get the response.
Step 2: Open CustomerController.cs under Controller folder and place [Authorize] attribute on top of CustomerController class.
[Authorize] public class CustomerController : ApiController {
Step 3: Browse DemoWebAPI.html again and turn on IE debugger tool and go to NetWork tab. Now click on Update/Save Customer button or any button. You will get HTTP 401 which means authorization required.

Let's fix this by writing some code.
Step 4: Create a class with name AccountModel.cs under Models folder and place below code in it.
public class LoginModel { public string UserName { get; set; } public string Password { get; set; } public bool RememberMe { get; set; } }
Step 5: Create AccountController.cs class under Controllers folder and place below code in it.
[Authorize] public class AccountController : Controller { [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); }
[AllowAnonymous] [HttpPost] public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); } }
If membership provider is not configure you need to configure it. Visit Walkthrough: Managing Web Site Users with Roles
Once we finish the entire coding and for testing purpose (if membership provider is not set up) put a breakpoint on the bold line above mentioned and step through it which will set the cookie.
Step 6: Add _LoginPartial.html in the /Views/Shared folder and put below code.
@if (Request.IsAuthenticated) { <p> Hello, @Html.ActionLink(User.Identity.Name, "ChangePassword", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Change password" })! @Html.ActionLink("Log off", "LogOff", "Account") </p> } else { <ul> <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> </ul> }
Step 7: Open _Layout.cshtml in /Views/Shared folder and place below code.
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - My ASP.NET MVC Application</title> <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/themes/base/css", "~/Content/css") @Scripts.Render("~/bundles/modernizr") </head>
<body> <header> <div class="content-wrapper"> <div class="float-right"> <section id="login"> @Html.Partial("_LoginPartial") </section> </div> </div> </header> <div id="body"> @RenderSection("featured", required: false) <section class="content-wrapper main-content clear-fix"> @RenderBody() </section> </div> @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false) </body> </html>
Step 8: Create a folder Account under Views and add Login.cshtml file. Place below code in the Login.cshtml file.
@model WebAPI_Authorization.Models.LoginModel
@{ ViewBag.Title = "Log in"; }
< hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>Use this form to enter your user name and password.</h2> </hgroup>
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.ValidationSummary(true, "Log in was unsuccessful. Please correct the errors and try again.") <fieldset> <legend>Log in Form</legend> <ol> <li> @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName) </li> <li> @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password) </li> </ol> <input type="submit" value="Log in" /> </fieldset> }
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Step 9: Open Web.config under the project not which is under View folder. Search for authentication element. Replace authentication element with below code. Authentication if present will be inside Systen.web.
< authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880"/> </authentication>
Step 10: Now run the application, you will get screen like below and click on LogIn.

Step 11: Enter valid ASP.NET membership user name and password.

Step 12: Open IE devloper toolbar, go to network tab, click on Start Capturing Button and now click on LogIn button. You will get /Account/Login url like below.

Now click on Go to detailed view. Notice Response and Set-Cookie row. It means you are validated and cookie has been set.
Step 13: Now browse on DemoWebAPI.html, and click on any of the button and you will get the desired result.

Step 14: We can handle 401 user not authorized like below code. Open DemoWebAPI.html and bold section in UpdateORSaveCustomer method.
function UpdateORSaveCustomer() { $.ajax({ url: "/api/customer/", type: 'POST', data: null, contentType: 'application/json; charset=utf-8', cache: false, statusCode: { 200: function (data) { alert('success save'); }, 401: function () { alert('Not Authorized'); } } }); }
This ends the article of authorization in WebAPI.
|