WebApi custom Filter instance

The function to be implemented is that when a user request is received, the headers need to contain the token, and the value of the token is equal to 123456 to pass the validation, and the interface can be called, otherwise it prompts 401 (identity authentication failed).

 

Step 1: Customize a filter to implement the interface IAuthorizationFilter

    public class MyAuthorFilter : IAuthorizationFilter
    {
        public bool AllowMultiple => throw new NotImplementedException();

        public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            IEnumerable<string> tokens;
            if (!actionContext.Request.Headers.TryGetValues("token", out tokens))
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }

            string token = tokens.First();
            if (token == "123456")
            {
                return await continuation();
            }
            else
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
        }
    }

Step 2: Register the newly added filter in the WebApiConfig.cs configuration file

//注册全局Filter
config.Filters.Add(new MyAuthorFilter());

 

The front-end code is as follows:

Refresh the front-end page at this time, you can see that the background service has been entered, the code in MyAuthorFilter is executed first, and the code in the controller is executed when the validation passes. The identity authentication function is realized.

 The program execution process is as follows:

 

The above is the case where the program has passed the verification. Let's look at the case if the value in the token is not 123456:

If the value of the token is abc, the program will return an exception of 401, and the method in the controller will not be executed. 

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/109214091