zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    log4j2配置ThresholdFilter,让info文件记录error日志
    Thrift常见异常及原因分析(<i>UPDATING...</i>)
    fastjson序列化出现StackOverflowError
    mysql执行update语句受影响行数是0
    远程Gitlab新建的分支在IDEA里不显示
    rabbitmq延迟队列demo
    利用延迟消息队列取代定时任务
    利用spring实现服务启动就自动执行某些操作的2种方式
    从Joda-Time反观Java语言利弊
    Linux Shell test判断
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/2908817.html
Copyright © 2011-2022 走看看