Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the ASP.NET MVC authorization filter

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use ASP.NET MVC authorization filter". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use ASP.NET MVC authorization filter" can help you solve the problem.

Filter

The emergence of Filter allows us to better control the URL requested by the browser in the ASP.NET MVC program, not every request will respond to the content, only those users with specific permissions can respond to the specific content. The filter theoretically has the following functions:

Determine whether to log in or not or user permissions.

Decision output cache.

Hotlink protection.

Against spiders.

Localization and internationalization settings.

Implement dynamic Action (often used to do rights management system).

1. Mode of use

The first method is to use the Authorize feature directly on top of Controller or Action without setting any properties of the property. Look at the screenshot below:

As you can see from the screenshot above, the first Action method named Index is unfiltered and any request with any identity can be passed. Just type: http://localhost:**/Admin/Index in the URL address bar of the browser to get the corresponding view response. The results are as follows:

The second Action method named Welcome uses the Authorize feature, indicating that this is a request that processes only those authenticated URL, and the page request effect is as follows:

At this point, you can see that the error indicates that only authenticated users can access the resources required by the request.

This kind of error page is very unfriendly, usually jump to the login page to allow the user to log in, so make the following modifications to the program.

1.1. Add login page

Create a new Account controller and two new Action methods as follows:

Using MVCAuthorizeFilterDemo.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Security;namespace MVCAuthorizeFilterDemo.Controllers {public class AccountController: Controller {/ / GET: Account public ActionResult Index () {return View () } / display login view / public ActionResult LogOn () {LogOnViewModel model = new LogOnViewModel (); return View (model) } / process the user clicks the login to submit the postback form / [HttpPost] public ActionResult LogOn (LogOnViewModel model) {/ / as long as the user name and password entered are the same as the if (model.UserName.Trim ( ) = = model.Password.Trim ()) {/ / determine whether the cookie FormsAuthentication.SetAuthCookie (model.UserName) that remembers my if (model.RememberMe) {/ / 2880 minute validity period is checked True) } else {/ / session cookie FormsAuthentication.SetAuthCookie (model.UserName, false);} / / Jump to the Welcome method return RedirectToAction of the Account controller ("Welcome", "Admin") } else {return View (model);}

LogOnViewModel is a user login entity class, which is defined as follows:

Using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Web;namespace MVCAuthorizeFilterDemo.Models {/ user login entity class / / public class LogOnViewModel {/ user name / [DisplayName ("user name")] public string UserName {get; set } / password / [DisplayName (password)] public string Password {get; set;} / remember me / [DisplayName (remember me)] public bool RememberMe {get; set;}

The LogOn view page code is as follows:

@ model MVCAuthorizeFilterDemo.Models.LogOnViewModel@ {Layout = null } LogOn @ using (Html.BeginForm ()) {@ Html.AntiForgeryToken () login @ Html.ValidationSummary (true) @ Html.LabelFor (model = > model.UserName) New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.UserName) @ Html.ValidationMessageFor (model = > model.UserName) @ Html.LabelFor (model = > model.Password) New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.Password) @ Html.ValidationMessageFor (model = > model.Password) @ Html.LabelFor (model = > model.RememberMe) New {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.RememberMe) @ Html.ValidationMessageFor (model = > model.RememberMe)} 1.2, Modify the configuration file

In the above case, an error page will be displayed if the permission authentication is not passed. In this case, you need to jump to the login page to allow the user to log in, so configure the login page in the configuration file. If you do not pass the authentication, you will jump to the login page configured in the configuration file. The configuration file code is as follows:

1.3, testing

After the modification, type "http://localhost:39175/Admin/Index" in the address bar of URL, and the results are as follows:

When accessing the Welcome method, enter: http://localhost:39175/Admin/Welcome, and the page is displayed as follows:

You can see from the above figure that although you visited the Action of Welcome, it did not return the corresponding view directly, but was taken to the login page. This is because the Action of Welcome uses the Authorize feature and denies access to all unlogged-in users.

Since the above denies the access of unauthenticated users, log in and pass the authentication. If you look at the code in the LogOn above, you can log in as long as you enter the same user name and password, and enter "admin". The page displays as follows:

The screenshot shows that it has been verified and the corresponding Action of Welcome has been obtained. Press F12 to open the console and you will find that there is an additional Cookie named ".ASPXAUTH", which is the default name and can be modified in the configuration file. If remember me is checked when logging in, then the expiration time of this Cookie is the 2880 minutes defined in the configuration file.

2. Mode of use 2

The second use of permission filters is based on user authorization and role-based authorization.

Based on role authorization, you assign values to the Roles attribute of the Authorize feature, and multiple roles can be separated by commas. Based on user authorization, you assign a value to the Users attribute of the Authorize feature, and you can use commas to separate multiple users. If the verification fails, it can also be configured through web.config.

Continue to modify based on the above case, allowing only two users with login names "a" and "b" to access the Welcome method. The modified code is as follows:

Using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MVCAuthorizeFilterDemo.Controllers {public class AdminController: Controller {/ / GET: Admin public ActionResult Index () {return View () } / usage 1: directly use the Authorize feature without adding any attributes / Authorize] / / public ActionResult Welcome () / / {/ / return View () / /} / usage 2: use the Authorize feature and add the Users attribute. Only an and b login users can access / [Authorize (Users = "AME b")] public ActionResult Welcome () {return View ();}

Visit http://localhost:39175/Admin/Welcome again, and then log in with admin, and you will find that the page will not jump to the page corresponding to the Welcome method, but the login page will be displayed. If you log in to an or b, the page corresponding to Welcome will be displayed, which means that the Users property you set works.

In the above case, assigning a value to the Users attribute of the Authorize feature controls who can access it, which is operationally convenient to control access to Action. However, if the project is very large and the corresponding roles and permissions of the user change greatly, it is obviously not appropriate to modify the code to re-label the Action each time. How should it be solved at this time? This allows you to use the custom filter provided by MVC.

That's all for "how to use ASP.NET MVC Authorization filter". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report