public override async Task OnActionExecuting(ActionExecutingContext context) { try { var req = context.HttpContext.Request; string token = req.GetToken(); if (token.IsNullOrEmpty()) { context.Result = Error("缺少token", _errorCode, AppId); return; } if (!JWTHelper.CheckToken(token, JwtKey) && !IsQuickDebug) { context.Result = Error("token校验失败!", _errorCode, AppId); return; } var payload = JWTHelper.GetPayload <JWTPayload>(token); if (payload.Expire < DateTime.Now) { context.Result = Error("token过期!", _errorCode, AppId); return; } if (AppId != payload.AppId && !IsQuickDebug) { context.Result = Error("token访问了错误的的应用", _errorCode, AppId); return; } } catch (Exception ex) { context.Result = Error(ex.Message, _errorCode, AppId); } await Task.CompletedTask; }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext context) { try { if (context.ContainsFilter <NoCheckJWTAttribute>() || GlobalSwitch.RunMode == RunMode.LocalTest) { return; } var req = context.HttpContext.Request; string token = req.GetToken(); if (!JWTHelper.CheckToken(token, JWTHelper.JWTSecret)) { context.Result = Error("token校验失败!", _errorCode); return; } var payload = JWTHelper.GetPayload <JWTPayload>(token); if (payload.Expire < DateTime.Now) { context.Result = Error("token过期!", _errorCode); return; } } catch (Exception ex) { context.Result = Error(ex.Message, _errorCode); } }
private static void TestJWT() { var user = new LoginInfo(); user.NickName = "NickName"; user.FamilyName = "FamilyName"; var token = JWTHelper.CreateToken(user, "127.0.0.1"); Console.WriteLine(token); Thread.Sleep(9000); var ret = JWTHelper.CheckToken <LoginInfo>(token, "127.0.0.1"); Console.WriteLine(ret.Msg); }
/// <summary> /// 验权 /// </summary> /// <param name="context"></param> public override void OnActionExecuting(ActionExecutingContext context) { //允许匿名 if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } //验证结果 ResultInfo <TokenInfo> ret = null; //获取token var token = ((HttpRequestHeaders)context.HttpContext.Request.Headers).HeaderAuthorization.FirstOrDefault(); //token传入0时,判断是否允许此IP匿名访问 if (token == "0") { //获取客户端IP var ip = context.HttpContext.GetClientIp(); //是否允许匿名访问IP ret = ComHelper.AllowAnonymous(ip); } else { //JWT验证 ret = JWTHelper.CheckToken <TokenInfo>(token, context.HttpContext.GetClientIp()); } //验证不通过 if (ret.IsOK == false) { LogHelper.Info($"访问接口[{context.HttpContext.Request.Path}]被拒绝({ret.Msg})"); context.Result = new UnauthorizedResult(); return; } //给控制器赋值token信息 var baseCtl = context.Controller as BaseController; if (baseCtl != null) { baseCtl.LoginInfo = ret.Info; } }
public bool Authorize([NotNull] DashboardContext context) { var req = context.GetHttpContext().Request; string token = req.Query["token"].ToString(); if (token.IsNullOrEmpty()) { // 获取cookie token = req.Cookies["Authorization"]; } else { //设置cookie context.GetHttpContext().Response.Cookies.Append("Authorization", token); } try { if (token.IsNullOrEmpty()) { return(false); } if (!JWTHelper.CheckToken(token, _jwtKey)) { return(false); } var payload = JWTHelper.GetPayload <JWTPayload>(token); if (payload.Expire < DateTime.Now) { return(false); } } catch (Exception) { return(false); } return(true); }
public override async Task OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoCheckJWTAttribute>()) { return; } try { var req = context.HttpContext.Request; string token = req.GetToken(); if (token.IsNullOrEmpty()) { context.Result = Error("缺少token", _errorCode); return; } if (!JWTHelper.CheckToken(token, JwtKey)) { context.Result = Error("token校验失败!", _errorCode); return; } var payload = JWTHelper.GetPayload <JWTPayload>(token); if (payload.Expire < DateTime.Now) { context.Result = Error("token过期!", _errorCode); return; } } catch (Exception ex) { context.Result = Error(ex.Message, _errorCode); } await Task.CompletedTask; }
/// <summary>在调用操作方法之前发生。</summary> /// <param name="actionContext">操作上下文。</param> public override void OnActionExecuting(HttpActionContext actionContext) { string isInterfaceSignature = ConfigHelper.GetValue("IsInterfaceSignature"); if (isInterfaceSignature.ToLower() != "true") { return; } BaseJsonResult <string> resultMsg = null; //授权码,最终签名字符串,时间戳,随机数字符串 string accessToken = string.Empty, signature = string.Empty, timestamp = string.Empty, nonce = string.Empty; //操作上下文请求信息 HttpRequestMessage request = actionContext.Request; //请求方法 string method = request.Method.Method; #region 接受客户端预请求 //接受客户端预请求 if (actionContext.Request.Method == HttpMethod.Options) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Accepted); return; } #endregion 接受客户端预请求 #region 忽略不需要授权的方法 //忽略不需要授权的方法 var attributes = actionContext.ActionDescriptor.GetCustomAttributes <IgnoreTokenAttribute>(); if (attributes.Count > 0 && attributes[0].Ignore) { return; } #endregion 忽略不需要授权的方法 _logHelper.Debug("*************************授权开始*************************\r\n"); _logHelper.Debug("鉴权地址:" + actionContext.Request.RequestUri + "\r\n"); #region 获取请求头信息 //授权Token if (request.Headers.Contains("access_token")) { accessToken = HttpUtility.UrlDecode(request.Headers.GetValues("access_token").FirstOrDefault()); _logHelper.Debug("access_token:" + accessToken + "\r\n"); } //签名字符串 if (request.Headers.Contains("signature")) { signature = HttpUtility.UrlDecode(request.Headers.GetValues("signature").FirstOrDefault()); _logHelper.Debug("signature:" + signature + "\r\n"); } //时间戳 if (request.Headers.Contains("timestamp")) { timestamp = HttpUtility.UrlDecode(request.Headers.GetValues("timestamp").FirstOrDefault()); _logHelper.Debug("timestamp:" + timestamp + "\r\n"); } //随机字符串 if (request.Headers.Contains("nonce_str")) { nonce = HttpUtility.UrlDecode(request.Headers.GetValues("nonce_str").FirstOrDefault()); _logHelper.Debug("nonce_str:" + nonce + "\r\n"); } #endregion 获取请求头信息 #region 判断请求头是否包含以下参数 //判断请求头是否包含以下参数 if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce)) { resultMsg = new BaseJsonResult <string> { Status = GlobalErrorCodes.AuthParameterError, Message = GlobalErrorCodes.AuthParameterError.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(请求头参数不完整)*************************\r\n"); return; } #endregion 判断请求头是否包含以下参数 #region 校验参数是否被篡改 ////校验参数是否被篡改 //Dictionary<string, object> actionArguments = null; //switch (method) //{ // case "POST": // actionArguments = actionContext.ActionArguments; // KeyValuePair<string, object> keyValuePair = actionArguments.FirstOrDefault(); // actionArguments = keyValuePair.Value.Object2Dictionary(); // break; // case "GET": // actionArguments = actionContext.ActionArguments; // break; //} //bool isSucc = this.CheckSignature(signature, actionArguments); //if (!isSucc) //{ // resultMsg = new BaseJsonResult<string> // { // Status = (int)JsonObjectStatus.ParameterManipulation, // Message = JsonObjectStatus.ParameterManipulation.GetEnumDescription() // }; // actionContext.Response = resultMsg.TryToHttpResponseMessage(); // _logHelper.Debug("*************************授权结束(请求参数被篡改或指纹有误)*************************\r\n"); // return; //} #endregion 校验参数是否被篡改 #region 校验Token是否有效 //校验Token是否有效 bool isCheckSucc = JWTHelper.CheckToken(accessToken, out JWTPlayloadInfo jwtPlayloadInfo); if (!isCheckSucc) { _logHelper.Debug("校验Token是否有效:TOKEN失效\r\n"); resultMsg = new BaseJsonResult <string> { Status = GlobalErrorCodes.TokenInvalid, Message = GlobalErrorCodes.TokenInvalid.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(TOKEN失效)*************************\r\n"); return; } else { //校验当前用户是否能够操作某些特定方法(比如更新用户信息) if (!attributes[0].Ignore) { string userId = jwtPlayloadInfo.aud; //访客用户不能访问未忽略的接口 if (!string.IsNullOrEmpty(userId) && userId.Equals(JWTPlayloadInfo.DefaultAud)) { resultMsg = new BaseJsonResult <string> { Status = GlobalErrorCodes.NoPermission, Message = GlobalErrorCodes.NoPermission.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(无权执行此操作)*************************\r\n"); return; } //TODO 验证正式用户或者试用用户是否有权操作当前方法 } } #endregion 校验Token是否有效 #region 验证签名字符串是否有效 SortedDictionary <string, object> dict = new SortedDictionary <string, object> { { "access_token", accessToken }, { "timestamp", timestamp }, { "nonce_str", nonce }, }; bool isSucc = this.CheckSignature(signature, dict); if (isSucc) { base.OnActionExecuting(actionContext); } else { resultMsg = new BaseJsonResult <string> { Status = GlobalErrorCodes.SignError, Message = GlobalErrorCodes.SignError.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(签名有误)*************************\r\n"); return; } #endregion _logHelper.Debug("*************************授权结束*************************\r\n"); }
/// <summary>在调用操作方法之前发生。</summary> /// <param name="actionContext">操作上下文。</param> public override void OnActionExecuting(HttpActionContext actionContext) { string isInterfaceSignature = ConfigHelper.GetValue("IsInterfaceSignature"); if (isInterfaceSignature.ToLower() == "false") { return; } BaseJsonResult <string> resultMsg = null; //授权码,指纹,时间戳,8位随机数 string accessToken = string.Empty, signature = string.Empty, timestamp = string.Empty, nonce = string.Empty; //操作上下文请求信息 HttpRequestMessage request = actionContext.Request; //请求方法 string method = request.Method.Method; #region 接受客户端预请求 //接受客户端预请求 if (actionContext.Request.Method == HttpMethod.Options) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Accepted); return; } #endregion #region 忽略不需要授权的方法 //忽略不需要授权的方法 var attributes = actionContext.ActionDescriptor.GetCustomAttributes <IgnoreTokenAttribute>(); if (attributes.Count == 0 || (attributes.Count > 0 && attributes[0].Ignore)) { return; } #endregion _logHelper.Debug("*************************授权开始*************************\r\n"); _logHelper.Debug("鉴权地址:" + actionContext.Request.RequestUri + "\r\n"); #region 获取请求头信息 //授权Token if (request.Headers.Contains("Authorization")) { accessToken = HttpUtility.UrlDecode(request.Headers.GetValues("Authorization").FirstOrDefault()); _logHelper.Debug("Authorization:" + accessToken + "\r\n"); } ////指纹 //if (request.Headers.Contains("Signature")) //{ // signature = HttpUtility.UrlDecode(request.Headers.GetValues("Signature").FirstOrDefault()); // _logHelper.Debug("Signature:" + signature + "\r\n"); //} #endregion #region 判断请求头是否包含以下参数 //判断请求头是否包含以下参数 if (string.IsNullOrEmpty(accessToken)) { resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.ParameterError, Message = JsonObjectStatus.ParameterError.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(请求头参数不完整)*************************\r\n"); return; } #endregion #region 校验参数是否被篡改 ////校验参数是否被篡改 //Dictionary<string, object> actionArguments = null; //switch (method) //{ // case "POST": // actionArguments = actionContext.ActionArguments; // KeyValuePair<string, object> keyValuePair = actionArguments.FirstOrDefault(); // actionArguments = keyValuePair.Value.Object2Dictionary(); // break; // case "GET": // actionArguments = actionContext.ActionArguments; // break; //} //bool isSucc = this.CheckSignature(signature, actionArguments); //if (!isSucc) //{ // resultMsg = new BaseJsonResult<string> // { // Status = (int)JsonObjectStatus.ParameterManipulation, // Message = JsonObjectStatus.ParameterManipulation.GetEnumDescription() // }; // actionContext.Response = resultMsg.TryToHttpResponseMessage(); // _logHelper.Debug("*************************授权结束(请求参数被篡改或指纹有误)*************************\r\n"); // return; //} #endregion #region 校验Token是否有效 //校验Token是否有效 JWTPlayloadInfo playload = JWTHelper.CheckToken(accessToken); if (playload == null) { _logHelper.Debug("校验Token是否有效:TOKEN失效\r\n"); resultMsg = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.TokenInvalid, Message = JsonObjectStatus.TokenInvalid.GetEnumDescription() }; actionContext.Response = resultMsg.TryToHttpResponseMessage(); _logHelper.Debug("*************************授权结束(TOKEN失效)*************************\r\n"); return; } else { //TODO 等系统开放了登陆,取消此段代码注释 //校验当前用户是否能够操作某些特定方法(比如更新用户信息) //if (!attributes[0].Ignore) //{ // if (!string.IsNullOrEmpty(playload.aud) && playload.aud.Equals("guest")) // { // resultMsg = new BaseJsonResult<string> // { // Status = (int)JsonObjectStatus.Unauthorized, // Message = JsonObjectStatus.Unauthorized.GetEnumDescription() // }; // actionContext.Response = resultMsg.TryToHttpResponseMessage(); // return; // } //} } #endregion _logHelper.Debug("*************************授权结束*************************\r\n"); //base.OnActionExecuting(actionContext); }