2011-05-01 79 views
8

我有一个MVC3应用程序,并且我的控制器操作使用[Authorize]属性进行保护。到目前为止,这么好,表单认证非常棒。现在我想将JSON API添加到我的应用程序中,以便非浏览器客户端可以访问某些操作。保护返回JSON的ASP.NET MVC控制器操作

我很难搞清楚'正确'的设计。

1)每个用户都有秘密的API密钥。

2)用户ID 5呼叫http://myapp.com/foocontroller/baraction/5?param1=value1&param2=value2&secure_hash=someValue。这里,secure_hash简单地是param1的SHA1哈希和param2的值,并且附加了用户的秘密API密钥。012)这将是一个AuthorizeAttribute的实现,它将检查请求是否以JSON形式进入。如果是,它将检查散列并查看它是否匹配。否则,如果请求是HTML,那么我调用现有的授权。

我完全不知道这是否可行。在查询字符串中传递安全哈希是正常的,还是应该将它作为HTTP头传递?使用HTTP基本身份验证而不是使用秘密API密钥创建的哈希更好吗?

任何使用ASP.NET MVC制作Web API的人的建议都会受到欢迎!

回答

11

我在请求主体中传递了秘密API密钥以及用户名和密码。一旦授权,就会生成一个令牌,并且客户端必须将其传递给授权标头。这将在每个请求的基础控制器中进行检查。

  1. 客户端调用myapp.com/authorize返回auth令牌。
  2. 客户端本地存储auth令牌。
  3. 客户端调用myapp.com/anycontroller,并在授权标头中使用authtoken。

AuthorizeController来自控制器继承。 Anycontroller继承自执行授权代码的自定义基础控制器。

我的示例需要以下的路径,其引导POST请求的任何控制器的命名后的ActionResult。我正在手动输入这个信息,以便尽可能简化它,以便为您提供总体思路。不要指望剪切和粘贴,并有它的工作:)

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

您的身份验证控制器可以使用这个

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); 

    } 
} 

你的其他控制器从基本控制器

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; 
      } 
     } 
+0

杰森,我想了解更多细节。我很新的MVC(RoR的背景),所以我就如何授权属性工作模糊。谢谢! – 2011-05-01 22:55:38

+0

谢谢杰森!你是如何“传之秘API密钥与请求主体的用户名和密码一起”?你只是添加自定义的HTTP头到请求或者你使用Http-Authorize? – 2011-05-01 23:20:09

+0

非常好,谢谢你的详细回复! – 2011-05-02 04:17:16

相关问题