Simple Webapi user login and access permissions, webapi User Login

Source: Internet
Author: User

Simple Webapi user login and access permissions, webapi User Login

Summarize the design of webapi user logon permission control in the previous project.

Purpose: The front-end can determine the user's logon status and access permissions based on the interface status code.

 

1. Add a configuration in webconfig to enable or disable permission control.

 <appSettings>    <add key="WebApiAuthFlag" value="true" />
</appSettings>

 

2. first understand the ActionFilterAttribute class, which can be intercepted before and after the action method is executed.

 

//// Abstract: // represents the base class of all operation filter features. [AttributeUsage (AttributeTargets. class | AttributeTargets. method, Inherited = true, AllowMultiple = true)] public abstract class ActionFilterAttribute: FilterAttribute, IActionFilter, IFilter {// abstract: // initialize System. web. http. filters. A new instance of the ActionFilterAttribute class. Protected ActionFilterAttribute (); // Abstract: // It occurs after the operation method is called. //// Parameter: // actionExecutedContext: // context of the operation execution. Public virtual void OnActionExecuted (HttpActionExecutedContext actionExecutedContext); public virtual Task OnActionExecutedAsync (HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken); // Summary: // occurs before the operation method is called. //// Parameter: // actionContext: // operation context. Public virtual void OnActionExecuting (HttpActionContext actionContext); public virtual Task OnActionExecutingAsync (HttpActionContext actionContext, CancellationToken cancellationToken );}

 

 

3. after understanding the role of the above class, we can create a class under the Filter folder (not necessarily under the Filter folder, can be any location) and inherit from the class above, override the OnActionExecuting method. In this case, this class is a filter.

Usage:

1. Global Filtering: register in the FilterConfig class.

2. partial filtering: add the Filter Name tag above a class or method to implement filtering.

Public class BasicAuthenticationAttribute: actionFilterAttribute {// <summary> /// check whether the user has the permission to perform the Action. /// </summary> /// <param name = "actionContext"> </param> public override void OnActionExecuting (HttpActionContext actionContext) {bool isRquired = false; try {// obtain the permission switch isRquired = WebConfigurationManager added in webconfig. appSettings ["WebApiAuthFlag"]. toString (). toBool ();} catch (Exception ex) {// throw an Exception} // if enabled... if (isRquired) {bool isLogin = false; // User Logon verification // code ..... // code ..... // code ..... // isLogin = true or false; if (isLogin) {// if you have logged on, skip base Verification. onActionExecuting (actionContext);} else {// if the request Header does not contain ticket, determine whether the request is an anonymous call of var attr = actionContext. actionDescriptor. getCustomAttributes <AllowAnonymousAttribute> (). ofType <AllowAnonymousAttribute> (); bool isAnonymous = attr. any (a => a is AllowAnonymousAttribute); // if it is an anonymous user, it continues to be executed. if it is a non-Anonymous user, it throws "unauthorized access" Information (throw 401) if (isAnonymous) base. onActionExecuting (actionContext); else actionContext. response = new HttpResponseMessage (HttpStatusCode. unauthorized );}}}}

After the above, we can start to write our own api class.

 

4. Create an api class and add a label above the class, that is, the name of the filter we just created above.

Using System; using System. collections. generic; using System. linq; using System. net; using System. web. http; using Test. filters; // introduce the namespace Test in which the filter is located. api {// Add a filter tag to verify all methods in the current class. [BasicAuthenticationAttribute] public class MemberController: ApiController {// before executing this method, the public int GetMemberId () {return 0 ;}// if the AllowAnonymous label is added to the method separately, the authentication is skipped, directly execute [AllowAnonymous] public string GetMemberName () {return "Bob ";}}}

 

5. All right. Let's take a look at the results.

 

GetMemberId is returned if you are not logged on to the system. 401 is returned.

 

Get GetMemberId In the logged-on status, and 200 is returned.

 

GetMemberName is obtained without logon, and 200 is returned.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.