asp.net - 保护返回 JSON 的 ASP.NET MVC Controller 操作

标签 asp.net json authentication asp.net-mvc-3

我有一个 MVC3 应用程序,并且我的 Controller 操作使用 [Authorize] 属性进行保护。到目前为止,一切都很好,forms auth 效果很好。现在我想向我的应用程序添加一个 JSON API,以便非浏览器客户端可以访问某些操作。

我无法找出“正确”的设计。

1)每个用户都有 secret 的API key 。

2) 用户 ID 5 次调用 http://myapp.com/foocontroller/baraction/5?param1=value1&param2=value2&secure_hash=someValue 。这里,secure_hash 只是 param1 和 param2 值的 SHA1 哈希值,并附加了用户的 secret API key

2)/foocontroller/baraction 将用 [CustomAuthorize] 装饰。这将是 AuthorizeAttribute 的实现,它将检查请求是否以 JSON 形式传入。如果是,它将检查哈希值并查看是否匹配。否则,如果请求是 HTML,那么我会调用现有授权。

我完全不确定这是否有效。在查询字符串中传递安全哈希是否正常,还是应该将其作为 HTTP header 传递?使用 HTTP 基本身份验证而不是使用 secret API key 生成的哈希是否更好?

欢迎使用 ASP.NET MVC 制作 Web API 的任何人提供提示!

最佳答案

我在请求正文中传递 secret API key 以及用户名和密码。一旦授权,就会生成一个 token ,客户端必须在授权 header 中传递该 token 。每个请求都会在基本 Controller 中进行检查。

  1. 客户端调用 myapp.com/authorize 并返回身份验证 token 。
  2. 客户端在本地存储身份验证 token 。
  3. 客户端调用 myapp.com/anycontroller,并在授权 header 中使用 authtoken。

AuthorizeController 继承自 Controller 。 Anycontroller 继承自执行授权代码的自定义基本 Controller 。

我的示例需要以下路由,将 POST 请求定向到任何 Controller 中名为 post 的 ActionResult。我手写此内容是为了尽可能简化它,以便为您提供总体思路。不要指望剪切和粘贴就能让它工作:)

routes.MapRoute(
    "post-object",
    "{controller}",
    new { controller = "Home", action = "post" {,
    new { httpMethod = new HttpMethodConstraint("POST")}
);

您的身份验证 Controller 可以使用它

public class AuthorizationController : Controller
{
    public ActionResult Post()
    {
        string authBody;
        var request = ControllerContext.HttpContext.Request;
        var response = ControllerContext.HttpContext.Response;

        using(var reader = new StreamReader(request.InputStream))
            authBody = reader.ReadToEnd();

        // authorize based on credentials passed in request body
        var authToken = {result of your auth method}

        response.Write(authToken);

    }
}

您的其他 Controller 继承自基本 Controller

public class BaseController : Controller
{
    protected override void Execute(RequestContext requestContext)
    {
        var request = requestContext.HttpContext.Request;
        var response = requestContext.HttpContext.Response;

        var authToken = Request.Headers["Authorization"];

        // use token to authorize in your own method
        var authorized = AmIAuthorized();

        if(authorized = false) { 
            response.StatusCode = 401; 
            response.Write("Invalid token");
            return;            
        }

        response.StatusCode = 200; // OK

        base.Execute(requestContext);  // allow inheriting controller to continue

    }
}

调用API的示例代码

 public static void ExecutePostRequest(string contentType)
        {
            request = (HttpWebRequest)WebRequest.Create(Uri + Querystring);
            request.Method = "POST";
            request.ContentType = contentType;  // application/json usually
            request.Headers["Authorization"] = token;

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                writer.Write(postRequestData);

            // GetResponse reaises an exception on http status code 400
            // We can pull response out of the exception and continue on our way            
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            finally
            {
                using (StreamReader reader =
                    new StreamReader(response.GetResponseStream()))
                    responseText = reader.ReadToEnd();
                httpcontext = HttpContext.Current;
            }
        }

关于asp.net - 保护返回 JSON 的 ASP.NET MVC Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5851900/

相关文章:

c# - PageRequestManagerServerErrorException 对象引用未设置... ASP.net AJAX

java - 为多态类型层次结构 Jackson 编写自定义解串器

javascript - PHP Web 服务器和 Node Js 之间的安全通信/身份验证

php - Laravel - 在登录时销毁现有 session

php - Auth::check() 不持久 Laravel 5.2

Asp.net mvc 在部分网站上运行

ASP.NET Identity 外部身份验证提供程序自定义图标

ASP.NET 数据注释 : How to validate a List of string?

java - 从 JSON 中读取不带小数点的浮点或 double 值

python - 当 json_normalize 无法迭代列以展平时如何修复它?