这是CustomAuthorizeAttribute;
public class CustomAuthorize : AuthorizeAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if ((actionContext.Request.Headers.GetValues("Host").FirstOrDefault().Contains("localhost:15742"))) { IEnumerable<string> access_token; if (actionContext.Request.Headers.TryGetValues("Authorization",out access_token)) { var user = GetUserByToken(access_token); if (user!=null && !user.TokenIsExpired) { HttpContext.Current.Response.AddHeader("WWW-Authenticate","Custom " + access_token.FirstOrDefault()); return; } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); HttpContext.Current.Response.AddHeader("WWW-Authenticate","Custom"); return; } } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } else { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden); } } }
这是前端使用
<script type="text/javascript"> $(function () { var access_token = $.cookie('access_token'); if (access_token == undefined) { $.cookie('access_token','test-token'); } $.ajax({ url: '/api/account',headers: { access_token: access_token },success: function (data) { document.write(data.name + " " + data.lastname); } }); }); </script>
顺便说一句,我为我的英语感到抱歉.我希望你理解我的问题,我在等你的建议.
解决方法
首先检查是多余的,因为HTTP请求只是TCP连接上的一串文本,因此任何人都可以使用TCP客户端连接到您的服务器并发送他想要的任何标头.
actionContext.Request.Headers.GetValues( “主机”)FirstOrDefault()包含.( “本地主机:15742”))
Authorization filters run before the controller action. If the request is not authorized,the filter returns an error response,and the action is not invoked.
属性的唯一方法是不设置响应是用户!= null&& !user.TokenIsExpired所以这个属性可以完成工作,可以认为是安全的.
这个头可以删除HttpContext.Current.Response.AddHeader(“WWW-Authenticate”,“Custom”);
另外,为什么你会在成功的情况下再次发送身份验证令牌? HttpContext.Current.Response.AddHeader(“WWW-Authenticate”,“Custom”access_token.FirstOrDefault());
只需减少IF-s嵌套级别,以便代码更易于阅读:
public override void OnAuthorization(HttpActionContext actionContext) { IEnumerable<string> access_token; if (!actionContext.Request.Headers.TryGetValues("Authorization",out access_token)) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return; } var user = GetUserByToken(access_token); if (user == null || user.TokenIsExpired) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return; } // OK return; }
许多ASP.NET代码似乎过度设计(有时是:)包括OWIN.但它有一个目的 – 声明一种标准的方式来做各种各样的事情,例如auth.
想象一下,每个人都会开始构建他们的自定义attrbiutes,然后就不可能只安装Google nuget包并做类似的事情
public void ConfigureAuth(IAppBuilder app) { app.UseGoogleAuthentication( clientId: "000-000.apps.googleusercontent.com",clientSecret: "00000000000"); }