如何使用 Web API 来对 MVC 应用程序进行身份验证
3个回答
2016-03-21 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517190
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
Web API有两种方式进行身份验证:在宿主程序中的身份验证和使用 HTTP Message Handlers进行身份验证。
如果你的Web API运行在IIS中,那么身份验证程序就是HTTP Modules,可以使用内置的asp.net身份验证模块进行身份验证,也可以自己写一个身份验证模块完成自定义身份验证。
当在宿主程序中进行身份验证时,宿主程序会创建一个principal对象,这个对象的类实现了IPrincipal接口,用来代表当前代码运行的安全上下文。宿主通过设置Thread.CurrentPrincipal 将主体附加到当前进程。principal包含一个关联用户信息的Identity 对象,如果用户验证通过,Identity.IsAuthenticated 属性返回true;对于匿名请求,IsAuthenticated 返回false。关于更多的principals信息,参见Role-Based Security。
如果你的Web API运行在IIS中,那么身份验证程序就是HTTP Modules,可以使用内置的asp.net身份验证模块进行身份验证,也可以自己写一个身份验证模块完成自定义身份验证。
当在宿主程序中进行身份验证时,宿主程序会创建一个principal对象,这个对象的类实现了IPrincipal接口,用来代表当前代码运行的安全上下文。宿主通过设置Thread.CurrentPrincipal 将主体附加到当前进程。principal包含一个关联用户信息的Identity 对象,如果用户验证通过,Identity.IsAuthenticated 属性返回true;对于匿名请求,IsAuthenticated 返回false。关于更多的principals信息,参见Role-Based Security。
展开全部
1 控制器基类ApiControllerBase
[csharp] view plaincopy
///
/// Controller的基类,用于实现适合业务场景的基础功能
///
///
[BasicAuthentication]
public abstract class ApiControllerBase : ApiController
{
}
2 权限属性BaseAuthenticationAttribute
[csharp] view plaincopy
///
/// 基本验证Attribtue,用以Action的权限处理
///
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
///
/// 检查用户是否有该Action执行的操作权限
///
///
public override void OnActionExecuting(HttpActionContext actionContext)
{
//检验用户ticket信息,用户ticket信息来自调用发起方
if (actionContext.Request.Headers.Authorization != null)
{
//解密用户ticket,并校验用户名密码是否匹配
var encryptTicket = actionContext.Request.Headers.Authorization.Parameter;
if (ValidateUserTicket(encryptTicket))
base.OnActionExecuting(actionContext);
else
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
//检查web.config配置是否要求权限校验
bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
if (isRquired)
{
//如果请求Header不包含ticket,则判断是否是匿名调用
var attr = actionContext.ActionDescriptor.GetCustomAttributes().OfType();
bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
//是匿名用户,则继续执行;非匿名用户,抛出“未授权访问”信息
if (isAnonymous)
base.OnActionExecuting(actionContext);
else
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
base.OnActionExecuting(actionContext);
}
}
}
///
/// 校验用户ticket信息
///
///
///
private bool ValidateUserTicket(string encryptTicket)
{
var userTicket = FormsAuthentication.Decrypt(encryptTicket);
var userTicketData = userTicket.UserData;
string userName = userTicketData.Substring(0, userTicketData.IndexOf(":"));
string password = userTicketData.Substring(userTicketData.IndexOf(":") + 1);
//检查用户名、密码是否正确,验证是合法用户
//var isQuilified = CheckUser(userName, password);
return true;
}
}
3 api服务Controller实例
[csharp] view plaincopy
public class ProductController : ApiControllerBase
{
[HttpGet]
public object Find(string id)
{
return ProductServiceInstance.Find(2);
}
// GET api/product/5
[HttpGet]
[AllowAnonymous]
public Product Get(string id)
{
var headers = Request.Headers;
var p = ProductServiceInstance.GetById(long.Parse(id));
if (p == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
Content = new StringContent("id3 not found"), ReasonPhrase = "product id not exist." });
}
return p;
}
}
4. 其它配置说明
1)、 Mvc前端Web.Config 配置
[html] view plaincopy
<</SPAN>system.web>
<</SPAN>compilation debug="true" targetFramework="4.5">
<</SPAN>assemblies>
<</SPAN>add assembly="System.Web.Http.Data.Helpers, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</</SPAN>assemblies>
</</SPAN>compilation>
<</SPAN>httpRuntime targetFramework="4.5" />
<</SPAN>authentication mode="Forms">
<</SPAN>forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index" protection="All" timeout="90" name=".AuthCookie"></</SPAN>forms>
</</SPAN>authentication>
<</SPAN>machineKey validationKey="3FFA12388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
</</SPAN>system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
2)、WebApi服务端Web.Config配置
[html] view plaincopy
<</SPAN>system.web>
<</SPAN>machineKey validationKey="3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
</</SPAN>system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
[csharp] view plaincopy
///
/// Controller的基类,用于实现适合业务场景的基础功能
///
///
[BasicAuthentication]
public abstract class ApiControllerBase : ApiController
{
}
2 权限属性BaseAuthenticationAttribute
[csharp] view plaincopy
///
/// 基本验证Attribtue,用以Action的权限处理
///
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
///
/// 检查用户是否有该Action执行的操作权限
///
///
public override void OnActionExecuting(HttpActionContext actionContext)
{
//检验用户ticket信息,用户ticket信息来自调用发起方
if (actionContext.Request.Headers.Authorization != null)
{
//解密用户ticket,并校验用户名密码是否匹配
var encryptTicket = actionContext.Request.Headers.Authorization.Parameter;
if (ValidateUserTicket(encryptTicket))
base.OnActionExecuting(actionContext);
else
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
//检查web.config配置是否要求权限校验
bool isRquired = (WebConfigurationManager.AppSettings["WebApiAuthenticatedFlag"].ToString() == "true");
if (isRquired)
{
//如果请求Header不包含ticket,则判断是否是匿名调用
var attr = actionContext.ActionDescriptor.GetCustomAttributes().OfType();
bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
//是匿名用户,则继续执行;非匿名用户,抛出“未授权访问”信息
if (isAnonymous)
base.OnActionExecuting(actionContext);
else
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
base.OnActionExecuting(actionContext);
}
}
}
///
/// 校验用户ticket信息
///
///
///
private bool ValidateUserTicket(string encryptTicket)
{
var userTicket = FormsAuthentication.Decrypt(encryptTicket);
var userTicketData = userTicket.UserData;
string userName = userTicketData.Substring(0, userTicketData.IndexOf(":"));
string password = userTicketData.Substring(userTicketData.IndexOf(":") + 1);
//检查用户名、密码是否正确,验证是合法用户
//var isQuilified = CheckUser(userName, password);
return true;
}
}
3 api服务Controller实例
[csharp] view plaincopy
public class ProductController : ApiControllerBase
{
[HttpGet]
public object Find(string id)
{
return ProductServiceInstance.Find(2);
}
// GET api/product/5
[HttpGet]
[AllowAnonymous]
public Product Get(string id)
{
var headers = Request.Headers;
var p = ProductServiceInstance.GetById(long.Parse(id));
if (p == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
Content = new StringContent("id3 not found"), ReasonPhrase = "product id not exist." });
}
return p;
}
}
4. 其它配置说明
1)、 Mvc前端Web.Config 配置
[html] view plaincopy
<</SPAN>system.web>
<</SPAN>compilation debug="true" targetFramework="4.5">
<</SPAN>assemblies>
<</SPAN>add assembly="System.Web.Http.Data.Helpers, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</</SPAN>assemblies>
</</SPAN>compilation>
<</SPAN>httpRuntime targetFramework="4.5" />
<</SPAN>authentication mode="Forms">
<</SPAN>forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index" protection="All" timeout="90" name=".AuthCookie"></</SPAN>forms>
</</SPAN>authentication>
<</SPAN>machineKey validationKey="3FFA12388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
</</SPAN>system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
2)、WebApi服务端Web.Config配置
[html] view plaincopy
<</SPAN>system.web>
<</SPAN>machineKey validationKey="3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE306219691434908D193A17C1FC8DCE51B71A4AE54920" decryptionKey="ECB6A3AF9ABBF3F16E80685ED68DC74B0B13CCEE538EBBA97D0B893139683B3B" validation="SHA1" decryption="AES" />
</</SPAN>system.web>
machineKey节点配置,是应用于对用户ticket数据加密和解密。
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Yii框架 Yii是一个基于组件、用于开发大型 Web 应用的 高性能 PHP 框架。Yii 几乎拥有了 所有的特性 ,包括 MVC、DAO/ActiveRecord、I18N/L10N、caching、基于 JQuery 的 AJAX 支持、用户认证和基于角色的访问控制、脚手架、输入验证、部件
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询