标签:ade 应该 方式 userdata from header path 调用 http请求
1.WebConfig中:
<httpProtocol></httpProtocol>中加
<customHeaders>
<!--<add name="Access-Control-Allow-Origin" value="http://oa.test.facehm.com" />-->
<add name="Access-Control-Allow-Origin" value="http://192.168.0.202:9528" />
<add name="Access-Control-Max-Age" value="30" />
<add name="Access-Control-Allow-Methods" value="POST" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
</customHeaders>
<handlers></handlers>中加 <add name="OPTIONS" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" />
2.新建类
/// <summary>
/// 自定义此特性用于接口的身份验证
/// </summary>
public class RequestAuthorizeAttribute : AuthorizeAttribute
{
Context context = new Context();
//重写基类的验证方式,加入我们自定义的Ticket验证
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
//从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
var authorization = actionContext.Request.Headers.Authorization;
if (authorization != null)
{
//解密用户ticket,并校验用户名密码是否匹配
var encryptTicket = authorization.Scheme;
if (ValidateTicket(encryptTicket))
{
base.IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
//如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
else
{
var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
if (isAnonymous) base.OnAuthorization(actionContext);
else HandleUnauthorizedRequest(actionContext);
}
}
//校验用户名密码(正式环境中应该是数据库校验)
private bool ValidateTicket(string encryptTicket)
{
//解密Ticket
var strTicket = FormsAuthentication.Decrypt(encryptTicket).UserData;
//从Ticket里面获取用户名和密码
string strUser = strTicket;
var query = context.Users.SingleOrDefault(s => s.U_Account == strUser);
if (query != null)
{
return true;
}
else
{
return false;
}
}
}
3.每个接口请求参数前加[FromBody],接口上面加[RequestAuthorize],调用上面的那个类
标签:ade 应该 方式 userdata from header path 调用 http请求
原文地址:https://www.cnblogs.com/tfeblog/p/10620238.html