Taurus. MVC 2.2.3.4: WebAPI implements permission control authentication (and function enhancement instructions), taurus. mvcwebapi
Preface:
Two days ago, when I was back in my hometown, preparing to go back to Guangzhou, I had another 365 days of fighting for IT companies,
Some netizens asked: how to implement authentication and permission control in Taurus. MVC is a small example.
I accidentally replied: I will write another article when I return to Guangzhou ......
Then, I will fill in the article today 〜〜〜〜
Taurus. MVC Nuget updated:
Before writing the text, it took some time to upgrade the Nuget Package and synchronize it with the source code version.
Generally, the source code version is a minor version earlier than the Nuget package:
Currently, upgrade Taurus. MVC to V2.2.3.4 (CYQ. Data is synchronized to V5.7.8.3)
Latest Version updates:
V2.2.3.1 () 1: added the CheckFormat method [Support for null or regular expression verification] V2.2.3.3 () 1: added support for method parameters (compatible with conventional webapi usage) 2: CYQ. data is also upgraded to V5.7.7.4V2.2.3.4 (2017-07-05,2017-10-22) 1: enhanced cross-origin Support 2: Corrected Query <T> (aaa, defaultValue) the default value order. 3: Adjust the execution sequence of EndInvode events and BenginInvode events. 4: CYQ. Data is upgraded to V5.7.8.3 at the same time.
Taurus. MVC enhancement: compatible with conventional WebAPI parameter writing
For example, for the following requests:
itlinks.cn/user?uid=666 itlinks.cn/user/uid/666
General parameters:
public void Get() { int uid = Query<int>("uid"); }
Compatibility Statement:
public void Get(int uid) { }
Compatibility parameters can also be complex, such:
public void GetData(List<AB> unList,string a,int? b,AB ab) { Write("your data A:" + unList[0].A+" your data B:" + unList[0].B, true); }
The Json value of the corresponding Post may be as follows (double quotation marks are saved when the Post is played by hand ):
{ uiList:[{a:1,b:1} , {a:2,b:2}] ,a:1 ,b:2 ,ab:{a:3,b:3}}
Example of IT connection: WebAPI solution:
First look: IT connection back-end WebApi solution:
To create a solution, follow these steps:
1: Create an empty Web application.
That is, the interface is not required for ITLinks. API and WebAPI. This application is used to store various controllers.
2: Use the Nuget package management to introduce Taurus. MVC in the project reference.
Nuget package management automatically adds the following configurations to Web. Config.
The value of key = "Taurus. Controllers" must be changed to the name of the project stored in the Controller (the name is generally the same as the name of the generated dll ).
After Taurus. MVC is referenced, it only contains two dll, Taurus. Core and CYQ. Data.
In the IT connection solution, the source code project is used for the two dll files (which is convenient for the author to debug or expand the functions ).
3: create various controllers (CREATE request Rules) in the project ).
Taking the blacklist function in IT connection as an example, the Controller should inherit from Taurus. Core. Controller:
(Pay attention to the constructor here and pass this to the constructor of the logic class)
Namespace ITLinks. API {public class BlacklistController: Taurus. core. controller {BlacklistLogic blacklist; public BlacklistController () {blacklist = new BlacklistLogic (this );} /// <summary> /// obtain the blacklist /// </summary> [Token] public void GetList () {string result = blacklist. getList (); Write (result);} [Token] public void Set () {string result = blacklist. set (); Write (result );}}}
Because the routing type in Web. Config is set to 1, that is, the routing mode is:
/Controller name/method name/Parameter
The following two path requests are created:
/blacklist/getlist/blacklist/set
Theoretically, you can Write business code in a method and call the Write method to output a string in json format.
However, in actual projects, clear planning is required:
In IT Connection Projects, controllers are planned to define simple settings such as routes and permissions (excluding specific business code ). Separates the Business Code from ITLinks. the Logic project handles: business Logic class inherited from: Taurus. core. logicBase (Taurus can be reused after inheritance. core. common Methods in Controller, such as Query <T> (xxx) to obtain parameters)
For example, the source code of the blacklist logic in the IT connection blacklist list is as follows:
(Pay attention to the constructor to define the constructor method that inherits the parameters of the controller received by the parent class)
Business logic of IT connection:
Part 1: Independent to solution ITLinks. CommonLogic. Used for function reuse (reuse the same code in the management background of ASP. NET Aries and the WebApi here) Part: independent to the solution ITlinks. Aop. Used for third-party message processing.
I will not elaborate on these ~~~ Drifting directly!
OK. Next, we will focus on permission security authentication:
Taurus. MVC WebAPI permission Security Authentication
Before writing this article, I scanned and read the previous article about Taurus. MVC, and found that there were only five articles in total, of which:
Taurus. MVC 2.0 open-source release: WebAPI development tutorial. Step 5: The process of permission control is not detailed enough.
This article describes the logic of the backend WebAPI for connecting IT to the App in detail:
First, controllers that inherit from Taurus. Core. Controller have the following override methods:
public class TestController : Taurus.Core.Controller { public override bool CheckToken() { } public override bool BeforeInvoke(string methodName) { } public override void EndInvoke(string methodName) { } }
And three permission-related features [Token], [HttpGet], and [HttpPost]:
[Token] public class TestController : Taurus.Core.Controller { [HttpGet] public void Get() { } [HttpPost] public void Post() { } }
If the feature is placed on the class, it takes effect for all methods!
The Calling sequence is as follows:
1: Call CheckToken (if the method identifies the [Token] attribute )【If false is returned, the following operations are aborted. manual intervention is allowed.] 2: check Get or Post (if the method identifies the [HttpGet] or [HttpPost] attribute )【If false is returned, the following operations are aborted and automatically controlled by the system.] 3: Call the BeforeInvoke method 【If false is returned, the following operations are aborted. manual intervention is allowed.]4: Call our defined methods, such as Get or Post methods.5: Call the EndInvoke method.
Next, let's take the IT connection request as an example to describe the process:
1: when a user opens an IT connection App for the first time, the user obtains the version update and configuration information of the App:
At this time, no permission is required. Everything is defined normally, such:
Public class SysController: Controller {SysLogic sysLogic = null; public SysController () {sysLogic = new SysLogic (this );} /// <summary> /// obtain configuration information /// </summary> public void GetConfig () {string msg = sysLogic. getConfig (); Write (msg) ;}/// <summary> // App version upgrade /// </summary> public void Update () {string msg = sysLogic. checkAppVersion (); Write (msg );}}
2: log on to or register an App:
Login and registration do not require permission verification, and the method remains as usual.
public class UserController : Controller { UserLogic user; public UserController() { user = new UserLogic(this); } public void Register() { string result = user.Register(); Write(result); } public void Login() { string result = user.Login(); Write(result); } }
However, after login or registration is successful, you need to create a Token and return it to the App client for archiving:
How to Create a Token: strings the user's basic fixed and unimportant information, and then adds the password. For example: (User ID + registration time + User Name + valid date) = "encrypted into: abfabcbcdxxabfabccdc
For specific code, refer to the GetAuthToken method in UserAuth. cs in the ASP. NET Aries framework.
3: when the user enters the main interface or opens the App again:
Because the user has archived the Token on the client during registration or login, the Token can be included in all subsequent requests.
For example, you need permissions to obtain complete information or submit user feedback:
Public class FeedbackController: Controller {FeedbackLogic feedbackLogic = null; public FeedbackController () {feedbackLogic = new FeedbackLogic (this);} public override bool CheckToken () {string userid = UserAuth. userID; // decrypt the Token from the user to obtain the data bool result =! String. IsNullOrEmpty (userid) & UserAuth. UserID. Length = 36 & UserAuth. RegTime. Length = 8; if (! Result) {Write (LangConst. EC_10000, false); // return Token Verification Failed} return result ;} /// <summary> // user feedback suggestion /// </summary> /// <returns> </returns> [Token] public void Set () {string result = feedbackLogic. set (); Write (result );}}
For the Set method, basic identity authentication is required, and the [Token] feature is added;
At the same time, you need to write code in the CheckToken method to check whether the Token brought by the user is legal:
1: From the request data orRequest HeaderObtain (Token string) 2: decrypt, verify the format and whether the Token expires. 3: Return true or false Based on the decryption result.
For more information about the code, see how the UserID attribute in UserAuth. cs in the ASP. NET Aries framework is reversed.
In this way, basic permission authentication is completed.
Taurus. MVC WebAPI special defacontroller Controller
Given that the code used to check Token validity is the same, there may be a lot of business controllers, so there must be a unified place:
Taurus. MVC defines three global methods, which are located in DefaultController. Of course, this controller file does not exist by default and needs to be created by yourself:
Public class DefaultController: Controller {public static bool CheckToken (IController controller, string methodName) {// write the code that verifies the Token validity in this global place, which takes effect for all controllers.
String userid = UserAuth. UserID;
Bool result =! String. IsNullOrEmpty (userid) & UserAuth. UserID. Length = 36 & UserAuth. RegTime. Length = 8;
If (! Result)
{
Controller. Write (LangConst. EC_10000, false );
}
Return result;
} public static bool BeforeInvoke(IController controller, string methodName) { } public static void EndInvoke(IController controller, string methodName) { } }
Priority of the defacontroller controller global method:
The priority of the three static methods is lower than the instance method with the same name as the Controller itself. That is, if a Controller has rewritten the CheckToken instance method, the global CheckToken will not be called, the other two methods are the same.
DefaultController is a special controller of Taurus. MVC, which is special in:
1: If the queried controller does not exist, it will be located in DefaultController. If defacontroller does not exist, an exception is thrown. 2: If the method cannot be found in defacontroller Controller, the Default method will be called (Taurus. Core. Controller has the Default method, which can be overwritten ).
3: The three unified methods are arranged here by fate.
Summary:
You have the value!
Next, we have to switch the thread back to continue writing the IT connection Startup Series and the Sagit. Framework Development Framework series for IOS!