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.
89 lines
2.3 KiB
89 lines
2.3 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Web;
|
|
using System.Web.Http;
|
|
using System.Web.Http.Controllers;
|
|
using JWT;
|
|
using WebApplication1;
|
|
using ICSSoft.Frame.Data.Entity;
|
|
using System.Net.Http;
|
|
using Newtonsoft.Json;
|
|
using System.Web.Http.Filters;
|
|
|
|
namespace WebApplication1.Attributes
|
|
{
|
|
public class ApiAuthorize : AuthorizeAttribute
|
|
{
|
|
|
|
public override void OnAuthorization(HttpActionContext actionContext)
|
|
{
|
|
|
|
|
|
var authorization = actionContext.Request.Headers.Authorization;
|
|
if ((authorization != null) && (authorization.Parameter != null))
|
|
{
|
|
//校验Token是否合法
|
|
try
|
|
{
|
|
if (JwtHelper.Validate(authorization.Parameter))
|
|
{
|
|
base.IsAuthorized(actionContext);
|
|
}
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
HttpContext.Current.Items.Add("error", ex.Message);
|
|
|
|
HandleUnauthorizedRequest(actionContext);
|
|
}
|
|
}
|
|
//接口需要权限认证,但无Token,返回拒绝响应此请求
|
|
else
|
|
{
|
|
var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
|
|
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
|
|
if (isAnonymous) base.OnAuthorization(actionContext);
|
|
|
|
else
|
|
{
|
|
HttpContext.Current.Items.Add("error", "请传入tocken值!");
|
|
HandleUnauthorizedRequest(actionContext);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
|
|
{
|
|
base.HandleUnauthorizedRequest(actionContext);
|
|
actionContext.Response.StatusCode = System.Net.HttpStatusCode.Forbidden;
|
|
var result = new Result()
|
|
{
|
|
code = "400",
|
|
msg = HttpContext.Current.Items["error"].ToString()
|
|
|
|
};
|
|
|
|
actionContext.Response.Content = new StringContent(JsonConvert.SerializeObject(result));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|