項(xiàng)目中有一個留言消息接口,接收其他系統(tǒng)的留言和展示留言,參考了網(wǎng)上的一些API驗(yàn)證方法,發(fā)現(xiàn)使用通用權(quán)限管理系統(tǒng)提供的驗(yàn)證方法最完美。
下面將實(shí)現(xiàn)的完整思路共享
1、WebApiConfig全局處理
/// <summary> /// WebApiConfig /// 路由基礎(chǔ)配置。 /// /// /// 修改記錄 /// /// 2016.11.01 版本:2.0 宋彪 對日期格式進(jìn)行統(tǒng)一處理。 /// 2016.10.30 版本:2.0 宋彪 解決json序列化時的循環(huán)引用問題。 /// 2016.10.28 版本:2.0 宋彪 回傳響應(yīng)格式 $format 支持。 /// 2016.09.01 版本:1.0 宋彪 創(chuàng)建。 /// /// 版本:1.0 /// /// <author> /// <name>宋彪</name> /// <date>2016.09.01</date> /// </author> /// </summary> public static class WebApiConfig { /// <summary> /// 注冊全局配置服務(wù) /// </summary> /// <param name="config"></param> public static void Register(HttpConfiguration config) { // Web API configuration and services //強(qiáng)制https訪問 //config.Filters.Add(new ForceHttpsAttribute()); // 統(tǒng)一回傳格式 config.Filters.Add(new ApiResultAttribute()); // 發(fā)生異常時處理 config.Filters.Add(new ApiErrorHandleAttribute()); // ToKen身份驗(yàn)證過濾器 更方便 不需要在這里了 具有改標(biāo)簽的就會自動檢查 //config.Filters.Add(new ApiAuthFilterAttribute()); // 解決json序列化時的循環(huán)引用問題 config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //對日期格式進(jìn)行統(tǒng)一處理 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" } ); // Web API routes 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); // 干掉XML序列化器 //config.Formatters.Remove(config.Formatters.XmlFormatter); //在請求的Url加上 ?$format=xml,便可以指定響應(yīng)格式 config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); } }2、身份驗(yàn)證過濾器
using DotNet.Business; using DotNet.Utilities; using DotNet.Tracking.API.Common; /// <summary> /// ApiAuthFilterAttribute /// 身份驗(yàn)證過濾器,具有ApiAuthFilterAttribute標(biāo)簽屬性的方法會自動檢查 /// /// /// 修改紀(jì)錄 /// /// 2016-10-11 版本:1.0 SongBiao 創(chuàng)建文件。 /// /// <author> /// <name>SongBiao</name> /// <date>2016-10-11</date> /// </author> /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class ApiAuthFilterAttribute : AuthorizationFilterAttribute { /// <summary> /// 未授權(quán)時的提示信息 /// </summary> private const string UnauthorizedMessage = "請求未授權(quán),拒絕訪問。"; /// <summary> /// 權(quán)限進(jìn)入 /// </summary> /// <param name="actionContext"></param> public override void OnAuthorization(HttpActionContext actionContext) { base.OnAuthorization(actionContext); // 允許匿名訪問 if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0) { return; } string systemCode = APIOperateContext.Current.SystemCode; string permissionCode = APIOperateContext.Current.PermissionCode; string appKey = APIOperateContext.Current.AppKey; string appSecret = APIOperateContext.Current.AppSecret; if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret)) { //未驗(yàn)證(登錄)的用戶, 而且是非匿名訪問,則轉(zhuǎn)向登錄頁面 //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); //actionContext.Response.Content = new StringContent("<p>Unauthorized</p>", Encoding.UTF8, "text/html"); var response = actionContext.Response= actionContext.Response?? new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Unauthorized; BaseResult result = new BaseResult { Status = false, StatusMessage = UnauthorizedMessage }; response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json"); } else { // 檢查 AppKey 和 AppSecret BaseResult result = BaseServicesLicenseManager.CheckService(appKey, appSecret, false, 0, 0, systemCode, permissionCode); if (!result.Status) { var response = actionContext.Response = actionContext.Response?? new HttpResponseMessage(); response.Content = new StringContent(result.ToJson(), Encoding.UTF8, "application/json"); } } } }
新聞熱點(diǎn)
疑難解答
圖片精選