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

  • 相关阅读:
    redhat 6.4下PXE+Kickstart无人值守安装操作系统
    ubuntu14.04安装好Hadoo之后接着安装hbase和介绍常用命令
    避坑之Hadoop安装伪分布式(Hadoop3.2.0/Ubuntu14.04 64位)
    kindeditor文件上传设置文件说明为上传文件名(JSP版)
    sqlmap 扫描注入漏洞
    局域网内访问不同网段的主机(转记)
    cmd创建用户开启3389命令
    用python来更改windows开机密码
    代码安全之上传文件
    web渗透(转)
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/2908817.html
Copyright © 2011-2022 走看看