You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.8 KiB
42 lines
1.8 KiB
using System;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Web.Http;
|
|
using System.Web.Http.Controllers;
|
|
using System.Web.Http.Filters;
|
|
|
|
namespace WcfControlMonitorWebLib
|
|
{
|
|
/// <summary>
|
|
/// 标识一个 Controller 下的 Action 被访问时,需要身份认证。
|
|
/// (标识有 AnonymousAttribute 的 Action 将忽略)
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
|
|
internal sealed class AuthorizationAttribute : ActionFilterAttribute
|
|
{
|
|
public override void OnActionExecuting(HttpActionContext actionContext)
|
|
{
|
|
base.OnActionExecuting(actionContext);
|
|
if (actionContext.ActionDescriptor.GetCustomAttributes<AnonymousAttribute>().Count == 0)
|
|
{
|
|
HttpRequestMessage request = actionContext.Request;
|
|
var token = request.Token();
|
|
// 没登录过
|
|
if (string.IsNullOrEmpty(token) || !WebSession.Store.ContainsKey(token))
|
|
{
|
|
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
|
|
}
|
|
// 过期了
|
|
if (WebParameter.SESSION_TIMEOUT > 0 && DateTime.Now.Subtract(Convert.ToDateTime(WebSession.Store[token].Timestamp)).TotalMinutes > WebParameter.SESSION_TIMEOUT)
|
|
{
|
|
WebSession.Store.Remove(token);
|
|
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
|
|
}
|
|
// 合法,更新时间戳
|
|
WebSession.Store[token].Timestamp = DateTime.Now;
|
|
// 取用户名,可以在 Action 中使用
|
|
(actionContext.ControllerContext.Controller as ControllerBase).Identity = WebSession.Store[token].Value;
|
|
}
|
|
}
|
|
}
|
|
}
|