• 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

  • 相关阅读:
    [Flex] Flex 控件&类 的自定义事件添加
    [java]原始类型和其包装类
    [java]解析网络上的xml文件
    [android]用adb操作android模拟器
    [java]优先队列
    [Q&A]为什么在ospf邻居之间确定主从关系?
    [js]jQuery插件开发总结
    [Q&A] 为什么把js脚本放到html页面的底部?
    理解一个简单的网页请求过程
    [js]如何更快的得到图片的高度和宽度
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/2908817.html
Copyright © 2020-2023  润新知