• A simple key based AuthorizeAttribute


    n this example, we'll be setting up a custom authorization scheme based on a key which will be validated using a very simple algorithm. This isn't secure for any number of reasons, but with some minor modifications (e.g. expiring a key once it is used) it would be sufficient for things like simple beta program for a pre-release website.

    We'll accept a parameter called X-Key and validate that it's a number that passes a simple check.

    To start with, we'll create a new class called KeyAuthorizeAttribute that inherits from AuthorizeAttribute:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public class KeyAuthorizeAttribute : AuthorizeAttribute 
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string key = httpContext.Request["X-Key"];
            return ApiValidatorService.IsValid(key);
        }
    }
     
    public static class ApiValidatorService
    {
        public static bool IsValid(string key)
        {
            int keyvalue;
     
            if (int.TryParse(key, out keyvalue))
            {
                return keyvalue % 2137 == 7;
            }
            return false;
        }
    }

    This AuthorizeCore method checks a value (via header, querystring, form post, etc.) and calls into a service to validate it. In this case, validation is a simple static method that runs our validation algorithm. In your case, you'd probably want to check against a list of pre-issued keys in a database, call out to an external service, etc. AuthorizeCore returns a boolean value - pass or fail.

    We can then slap that [KeyAuthorize] attribute on any action or controller in the site, or register it globally (as shown in my previous post).

    This request would be allowed: http://localhost:8515/?X-Key=26381272 (because 26381272 mod 2137 equals 7)

    This request would be denied: http://localhost:8515/?X-Key=12345

  • 相关阅读:
    在redhat上搭建redmine
    工具第二天 cocoaPods 私有库的创建
    回归 从注释开始 appledoc
    Chrome浏览器插件开发-关于案例
    Chrome浏览器插件开发-淘宝自动登录
    IOS开发-本地持久化存储sqlite应用
    IOS开发-表单控件的应用
    如何安全可靠的处理后台任务
    Cache应用/任务Mutex,用于高并发任务处理经过多个项目使用
    报表的缓存基本存储和读写
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/2908817.html
Copyright © 2020-2023  润新知