//// this is Castle.Core.Logging.ILogger, not log4net.Core.ILogger //public ILogger Logger { get; set; } /// <summary> /// Executes the authorization filter. /// </summary> /// <param name="actionContext">The action context.</param> /// <param name="cancellationToken">The cancellation token associated with the filter.</param> /// <param name="continuation">The continuation.</param> /// <returns> /// The authorization filter to synchronize. /// </returns> public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { HttpRequestMessage request = actionContext.Request; try { if (IsAjaxRequest(request)) { ValidateRequestHeader(request); } else { AntiForgery.Validate(); } } catch (Exception) { //LogManager.GetCurrentClassLogger().Warn("Anti-XSRF Validation Failed", ex); actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, RequestMessage = actionContext.ControllerContext.Request }; return FromResult(actionContext.Response); } return continuation(); }
public override void OnActionExecuting(HttpActionContext actionContext) { if (!String.Equals(actionContext.Request.RequestUri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) { Content = new StringContent("HTTPS Required") }; return; } }
/// <summary> /// 根据Reques上下文信息格式化返回值 /// </summary> /// <param name="httpContext"></param> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <param name="httpMethodContext"></param> public void ProcessResponse(HttpContext httpContext, HttpActionContext context) { //0 业务逻辑检查, 检查方法的返回值是否合法 //1 生成结果的二进制字节流 //2 检查返回值是否需要压缩 //3 检查返回值是否需要签名 //4 写入结果到ResponseStream中 context.ResponseWrapper = new HttpActionResponse(); httpContext.Response.Clear(); object o = context.Result; string acceptType = GetAcceptType(httpContext.Request); //获取返回结果的二进制数据 byte[] ResultBinary = GetResultBinary(o, acceptType); //bool IsCompressed = IsNeedCompress(httpContext.Request, 0, acceptType, ResultBinary); //需要进行压缩 //if (IsCompressed) // ResultBinary = CompressHelper.Compress(ResultBinary, RestConfigInfo.Data.CompressLevel); //string SignatureType = GetSignatureType(httpContext.Request, acceptType); //byte[] SingnedBinary = null; //签名 //switch (SignatureType) //{ // case "1": // SingnedBinary = ComputeStaticSHA1(prefix, suffix, ResultBinary); // break; // case "2": // //注意:实现动态sig时要注意对于可缓存接口使用该方式可能导致问题,应约束使得可缓存接口无法使用sig验证 // SingnedBinary = ComputeDynamicSHA1(ResultBinary); // break; // default: // break; //} //写入Response context.ResponseWrapper.ContentEncoding = Encoding.UTF8; context.ResponseWrapper.ContentType = acceptType; context.ResponseWrapper.BinaryWrite(ResultBinary); //context.HttpContext.Response.BinaryWrite(ResultBinary); //context.HttpContext.Response.Flush(); }
public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ActionArguments.Any(p => p.Value == null)) { actionContext.ModelState.AddModelError(string.Empty, Messages.RequestCannotBeEmpty); } if (!actionContext.ModelState.IsValid) { var error = actionContext .ModelState .Values .SelectMany(v => v.Errors.Select(er => er.ErrorMessage)) .First(); actionContext.Response = actionContext.Request.CreateResponse(new ResultObject(false, error)); } }
public void SetContext(HttpActionContext actionContext) { _context = actionContext; _modelState = _context.ModelState; }
private static void HandleUnathorized(HttpActionContext actionContext) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); actionContext.Response.Headers.Add("WWW-Authenticate", "Basic Scheme='Data' location = 'http://localhost:"); }
private static bool CSRFCheckIsIgnoredOnTargetMethod(HttpActionContext actionContext) { return (actionContext.ActionDescriptor.GetCustomAttributes <IgnoreCSRFProtectionAttribute>().Any() || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <IgnoreCSRFProtectionAttribute>().Any()); }
/// <summary> /// Passes or fails authentication, based on whether you provide a valid application key in the http headers of the request. /// </summary> /// <param name="actionContext">Action filter context.</param> public void OnAuthorization(HttpActionContext actionContext) { try { if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any()) { return; } var credentials = ProcessAuthorizationToken(actionContext.Request, Entries); if (credentials != null && credentials.Count == Entries) { var authenticationToken = actionContext.Request.Headers.FirstOrDefault(x => x.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase)).Value.First(); var body = actionContext.Request.Content.ReadAsStringAsync().Result; if (actionContext.Request.Method != HttpMethod.Get && !string.IsNullOrWhiteSpace(body) && !actionContext.Request.Content.IsMimeMultipartContent()) //NOT (If GET request or request without any body or body having image/audio/video content) { try { RequestBase req = null; if (Helper.IsJson(body)) { req = JsonConvert.DeserializeObject <RequestBase>(body); } else { var doc = XDocument.Load(new StringReader(body)); var xElements = doc.Descendants().Elements() as IList <XElement> ?? doc.Descendants().Elements().ToList(); var userIdData = xElements.FirstOrDefault(x => x.Name == "UserId"); var deviceIdData = xElements.FirstOrDefault(x => x.Name == "DeviceId"); if (userIdData != null && deviceIdData != null) { req = new RequestBase { UserId = Convert.ToInt32(userIdData.Value), DeviceId = deviceIdData.Value }; } } if (req != null && (!req.UserId.ToString(CultureInfo.InvariantCulture).Equals(credentials[(int)SystemSessionEntity.UserId]) || !req.DeviceId.Equals(credentials[(int)SystemSessionEntity.DeviceId]))) { actionContext.Response = actionContext.Request.SystemResponse <string>(SystemDbStatus.Unauthorized); return; } } catch (Exception ex) { actionContext.Response = actionContext.Request.SystemResponse(SystemDbStatus.GeneralError, ex.Message, false, SystemResponseMessage.NonInheritingRequestBase); return; } } if (MemoryCache.GetValue(authenticationToken) != null && SaveToSession(actionContext, credentials)) { return; } var dvcTyp = credentials[(int)SystemSessionEntity.DeviceTypeId]; var userExists = _service.IsAuthenticated(Convert.ToInt32(credentials[(int)SystemSessionEntity.UserId]), credentials[(int)SystemSessionEntity.UserName], credentials[(int)SystemSessionEntity.LoginToken], credentials[(int)SystemSessionEntity.DeviceId], dvcTyp, dvcTyp.Equals("W", StringComparison.OrdinalIgnoreCase) ? System.Web.HttpContext.Current.Request.UserHostAddress : null); if (userExists) { SaveToSession(actionContext, credentials); MemoryCache.Add(authenticationToken, credentials[(int)SystemSessionEntity.UserId], DateTime.Now.AddMinutes(SystemConstants.CacheExpiryTimeInMinutes)); return; } } actionContext.Response = actionContext.Request.SystemResponse <string>(SystemDbStatus.Unauthorized); } catch (Exception ex) { actionContext.Response = actionContext.Request.SystemResponse <string>(SystemDbStatus.GeneralError, null, false, ex.Message); } }
/// <summary> /// /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { ServiceContainer.Resolve <IInitRequestScopeContext>().BeginRequest(actionContext.Request); if (!actionContext.HasMarkerAttribute <NonTracingAttribute>()) { var request = actionContext.Request; IRequestModel <Header> reqModel = null; Header reqHeader = null; if (actionContext.ActionArguments.Count > 0) { foreach (var dic in actionContext.ActionArguments) { //if (dic.Value is RequestModel) //{ // reqModel = dic.Value as RequestModel; // break; //} reqModel = dic.Value as IRequestModel <Header>; if (reqModel != null) { break; } } } if (reqModel == null && actionContext.Request.Content != null && string.Equals(actionContext.Request.Method.Method, "post", StringComparison.CurrentCultureIgnoreCase)) { try { reqModel = actionContext.Request.Content.ReadAsAsync <RequestModel>().Result; } catch { } if (reqModel != null) { actionContext.ActionArguments.Add(Guid.NewGuid().ToString("N"), reqModel); } } if (reqModel != null && reqModel.Header != null) { reqHeader = reqModel.Header; if (string.IsNullOrWhiteSpace(reqHeader.TraceID)) { reqHeader.TraceID = Generate.GenerateId();// Util.GetUniqueCode32(); } if (string.IsNullOrWhiteSpace(reqHeader.RpcID)) { reqHeader.RpcID = "0"; } //HttpContentData.SetTrackID(reqHeader.TraceID); //HttpContentData.SubRpcID = reqHeader.RpcID + ".0"; //var header = HttpContentData.CloneRequestHeader(reqModel.Header); //header.RpcID = header.RpcID + ".0"; } else { reqHeader = TracingContextData.GetDefaultRequestHeader(); //HttpContentData.SetTrackID(reqHeader.TraceID); } TracingContextData.SetSubRpcID(reqHeader.RpcID + ".0"); TracingContextData.SetRequestHeader(reqHeader); //HttpContentData.RequestHeader = reqHeader; //Not To Log if (!actionContext.HasMarkerAttribute <NotToLogAttribute>()) { TraceLogs trace = new TraceLogs(); trace.ContextType = ContextType.Server.ToString(); trace.StartTime = DateTime.Now; trace.MachineAddr = Util.TracingContextHelper.GetServerAddress(); trace.TraceId = reqHeader.TraceID; trace.RpcId = reqHeader.RpcID; trace.Protocol = string.Format("{0}/{1}", actionContext.Request.RequestUri.Scheme, actionContext.Request.Version); trace.Environment = this.environment ?? EnvironmentConfig.Environment; trace.SystemID = this.systemID ?? EnvironmentConfig.SystemID; trace.SystemName = this.systemName ?? EnvironmentConfig.SystemName; //InvokeID trace.InvokeID = request.RequestUri.AbsolutePath; IEnumerable <string> folder; if (actionContext.Request.Headers.TryGetValues(Config.ResponseHeaderFolderKey, out folder)) { trace.ServerHost = actionContext.Request.RequestUri.Host + folder.FirstOrDefault(); } else { trace.ServerHost = actionContext.Request.RequestUri.Host; } //SearchKey var searchKey = reqModel as ISearchKey; if (searchKey != null) { trace.SearchKey = searchKey.GetSearchKey(); } TraceExtensionOnActionExecuting(actionContext, trace); //srs.InvokeID = string.Format("{0}_{1}", actionContext.ControllerContext.ControllerDescriptor.ControllerName.ToLower(), actionContext.ActionDescriptor.ActionName.ToLower()); //if (actionContext.ActionArguments != null && actionContext.ActionArguments.Count > 0) //{ // srs.Extension.Add(Config.ParamsKey, actionContext.ActionArguments); //} //ServerRS Log Data TODO Util.TracingContextHelper.SetContextItem(Config.ServerRSKey, trace); } } base.OnActionExecuting(actionContext); }
public override void OnActionExecuting(HttpActionContext actionContext) { Assert.Equal(_model, actionContext.Request.GetModel()); }
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext == null) { throw Error.ArgumentNull("actionContext"); } HttpRequestMessage request = actionContext.Request; if (request == null) { throw Error.Argument("actionContext", SRResources.ActionContextMustHaveRequest); } SetValue(actionContext, request.ODataProperties().Path); return(TaskHelpers.Completed()); }
private static bool IsExternalApiRequest(HttpActionContext actionContext) { var authenticationContext = GetService <IAuthenticationContext>(actionContext); return(authenticationContext.Method == AuthenticationMethod.KitosToken); }
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(DataTableRequest)) { return(false); } var model = (DataTableRequest)bindingContext.Model ?? new DataTableRequest(); model.Draw = Convert.ToInt32(GetValue(bindingContext, "draw")); model.Start = Convert.ToInt32(GetValue(bindingContext, "start")); model.Length = Convert.ToInt32(GetValue(bindingContext, "length")); // Search model.Search = new DataTableSearch { Value = GetValue(bindingContext, "search.value"), Regex = Convert.ToBoolean(GetValue(bindingContext, "search.regex")) }; // Order var o = 0; var order = new List <DataTableOrder>(); while (GetValue(bindingContext, "order[" + o + "].column") != null) { order.Add(new DataTableOrder { Column = GetValue(bindingContext, "columns[" + GetValue(bindingContext, "order[" + o + "].column") + "].name"), Dir = GetValue(bindingContext, "order[" + o + "].dir") }); o++; } model.Order = order.ToArray(); // Columns var c = 0; var columns = new List <DataTableColumn>(); while (GetValue(bindingContext, "columns[" + c + "].data") != null) { columns.Add(new DataTableColumn { Data = GetValue(bindingContext, "columns[" + c + "].data"), Name = GetValue(bindingContext, "columns[" + c + "].name"), Orderable = Convert.ToBoolean(GetValue(bindingContext, "columns[" + c + "].orderable")), Searchable = Convert.ToBoolean(GetValue(bindingContext, "columns[" + c + "].searchable")), Search = new DataTableSearch { Value = GetValue(bindingContext, "columns[" + c + "][search].value"), Regex = Convert.ToBoolean(GetValue(bindingContext, "columns[" + c + "].search.regex")) } }); c++; } model.Columns = columns.ToArray(); bindingContext.Model = model; return(true); }
public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation) { var attrs = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true); if (attrs.Count == 1) { return(await continuation()); } attrs = actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true); if (attrs.Count == 1) { return(await continuation()); } var headers = actionContext.Request.Headers; var cNameSpace = actionContext.ControllerContext.ControllerDescriptor.ControllerType.Namespace; var match = version.Match(cNameSpace); if (match.Success && float.TryParse(match.Groups[1].Value, out var v) && v > 2) { if (!headers.TryGetValues("JWT", out var jwt)) { return(Content(HttpStatusCode.Unauthorized, "JWT为空")); } try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); var secret = WebHelper.AppSetting(); var data = decoder.DecodeToObject <Payload>(jwt.FirstOrDefault(), secret, true); return(await continuation()); } catch (TokenExpiredException) { return(Content(HttpStatusCode.Unauthorized, "Token 已过期")); } catch (SignatureVerificationException) { return(Content(HttpStatusCode.Unauthorized, "签名错误!")); } } if (!headers.TryGetValues("AppKey", out var appKeys)) { return(Content(HttpStatusCode.Unauthorized, "AppKey为空")); } if (!headers.TryGetValues("Sign", out var signs)) { return(Content(HttpStatusCode.Unauthorized, "Sign为空")); } string appkey = appKeys.FirstOrDefault(); string sign = signs.FirstOrDefault(); var appInfo = await _appInfoService.GetByAppKeyAsync(appkey); if (appInfo == null) { return(Content(HttpStatusCode.Unauthorized, "AppKey错误")); } var paramArr = actionContext.Request .GetQueryNameValuePairs() .OrderBy(kv => kv.Key) .Select(kv => kv.Key + "=" + kv.Value) .ToArray(); string sign2 = MD5Helper.ToMD5(string.Join("&", paramArr) + appInfo.AppSecret); if (!sign.Equals(sign2, StringComparison.InvariantCultureIgnoreCase)) { return(Content(HttpStatusCode.Unauthorized, "签名错误")); } return(await continuation()); }
private static void setErrorResponse(HttpActionContext actionContext, string message) { var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, message); actionContext.Response = response; }
private static bool SkipAuthorization(HttpActionContext actionContext) { return(actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any()); }
protected override bool IsAuthorized(HttpActionContext actionContext) { int HMAC_Valid_inMinutes = 10; /** * Pen Your Prayer Authorization Specification * Encoding before send. * Authorization for Registered User * * Authorization: hmac_logintype="email"; * hmac_username="******"; * hmac_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D"; * hmac_timestamp="Sun, 01 Nov 2015 15:31:08 GMT"; * hmac_nonce="4572616e48616d6d65724c61686176" random int value * * hashing order method + LoginType + UserName + tdate + nonce + query + content; */ if (System.Configuration.ConfigurationManager.AppSettings["DebugMode"] != null && System.Configuration.ConfigurationManager.AppSettings["DebugMode"].ToUpper() == "TRUE") { using (DBDataContext db = new DBDataContext()) { List <usp_GetUserInformationResult> d = db.usp_GetUserInformation("GooglePlus", "117887045378788685328").ToList(); PenYourPrayerIdentity identity = new PenYourPrayerIdentity(d.ElementAt(0).ID, d.ElementAt(0).LoginType, d.ElementAt(0).UserName) { DisplayName = d.ElementAt(0).DisplayName, ProfilePictureURL = d.ElementAt(0).ProfilePictureURL, MobilePlatform = d.ElementAt(0).MobilePlatform, PushNotificationID = d.ElementAt(0).PushNotificationID, City = d.ElementAt(0).City, Region = d.ElementAt(0).Region, Country = d.ElementAt(0).Country }; IPrincipal principal = new GenericPrincipal(identity, null); actionContext.RequestContext.Principal = principal; return(true); } return(false); } else if (actionContext.Request.Headers.Authorization != null) { try { string method = actionContext.Request.Method.ToString().ToUpper(); string LoginType = ""; string UserName = ""; string tdate = ""; DateTime tDateTime = new DateTime(0); string receivedHash = ""; string nonce = ""; string encodedAuthorizationHeader = actionContext.Request.Headers.Authorization.ToString(); string[] AuthorizationHeaders = HttpUtility.UrlDecode(encodedAuthorizationHeader).Split(';'); foreach (string s in AuthorizationHeaders) { string[] t = new string[2]; t[0] = s.Substring(0, s.IndexOf("=")).Trim(); t[1] = s.Substring(s.IndexOf("=") + 1).Trim(); if (t[0].ToUpper() == "HMAC_LOGINTYPE") { LoginType = t[1].Substring(1, t[1].Length - 2).ToUpper(); } else if (t[0].ToUpper() == "HMAC_USERNAME") { UserName = t[1].Substring(1, t[1].Length - 2).ToUpper(); } else if (t[0].ToUpper() == "HMAC_SIGNATURE") { receivedHash = t[1].Substring(1, t[1].Length - 2); } else if (t[0].ToUpper() == "HMAC_NONCE") { nonce = t[1].Substring(1, t[1].Length - 2); } else if (t[0].ToUpper() == "HMAC_TIMESTAMP") { tdate = t[1].Substring(1, t[1].Length - 2); } } // string query = ""; if (actionContext.Request.RequestUri.Query.Length > 0) { query = HttpUtility.UrlDecode(HttpUtility.UrlDecode(actionContext.Request.RequestUri.Query.Substring(1))); } //string content = content = actionContext.Request.Content.ReadAsStringAsync().Result; byte[] contentBytes = actionContext.Request.Content.ReadAsByteArrayAsync().Result; string contentMD5 = ""; if (method != "GET") { contentMD5 = md5CheckSum(contentBytes).ToUpper(); } //DBDataContext dda = new DBDataContext(); //dda.usp_AddLog(DateTime.Now.ToString() + " content md5: " + contentMD5); //dda.Connection.Close(); //if (content.StartsWith("\"")) // content = content.Substring(1); //if(content.EndsWith("\"")) // content = content.Substring(0, content.Length-1); if (method == null || nonce == null || receivedHash == null || LoginType == null || UserName == null || tdate == null || LoginType.Length == 0 || UserName.Length == 0 || tdate.Length == 0 || receivedHash.Length == 0 || nonce.Length == 0 || method.Length == 0) { return(false); } else { //check time difference not more than 5sec DateTime d = DateTime.UtcNow; tDateTime = DateTime.ParseExact(tdate, "r", CultureInfo.InvariantCulture); long timeDifference = (long)((d - tDateTime).TotalSeconds); if (timeDifference > (HMAC_Valid_inMinutes * 60) || timeDifference < (-HMAC_Valid_inMinutes * 60)) { return(false); } } PenYourPrayerIdentity identity; string HMACHashKey = ""; if (LoginType != "ANONYMOUS") { using (DBDataContext db = new DBDataContext()) { string result = ""; db.usp_AddNonce(LoginType, UserName, DateTime.ParseExact(tdate, "r", CultureInfo.InvariantCulture), (int?)int.Parse(nonce), ref result); if (result.ToUpper() == "EXISTS") { return(false); } List <usp_GetUserInformationResult> d = db.usp_GetUserInformation(LoginType, UserName).ToList(); if (d.Count() == 0) { return(false); } else if (d.Count() == 1) { identity = new PenYourPrayerIdentity(d.ElementAt(0).ID, d.ElementAt(0).LoginType, d.ElementAt(0).UserName) { DisplayName = d.ElementAt(0).DisplayName, ProfilePictureURL = d.ElementAt(0).ProfilePictureURL, MobilePlatform = d.ElementAt(0).MobilePlatform, PushNotificationID = d.ElementAt(0).PushNotificationID, City = d.ElementAt(0).City, Region = d.ElementAt(0).Region, Country = d.ElementAt(0).Country }; HMACHashKey = d.ElementAt(0).HMACHashKey; } else { return(false); } } if (LoginType.ToUpper() != identity.LoginType.ToUpper() || UserName.ToUpper() != identity.UserName.ToUpper()) { return(false); } } else { using (DBDataContext db = new DBDataContext()){ string result = ""; db.usp_AddNonce(LoginType, UserName, DateTime.ParseExact(tdate, "r", CultureInfo.InvariantCulture), (int?)int.Parse(nonce), ref result); if (result.ToUpper() == "EXISTS") { return(false); } } identity = new PenYourPrayerIdentity(0, "", ""); HMACHashKey = QuickReference.AnonymousHMACKey; } byte[] key = Encoding.ASCII.GetBytes(HMACHashKey); string contentToHash = method + LoginType + UserName + tdate + nonce + md5CheckSum(query).ToUpper() + contentMD5; if (Encode(contentToHash, key) != receivedHash) { return(false); } IPrincipal principal = new GenericPrincipal(identity, null); actionContext.RequestContext.Principal = principal; return(true); } catch (Exception e) { return(false); } } return(false); }
public abstract IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext);
private bool HandleWindowsAuthentication(HttpActionContext actionContext) { var mgmtConfig = _configurationService.GetManagementServerConfiguration(); var windowsPrincipal = (WindowsPrincipal)actionContext.RequestContext.Principal; UserRoleEnum?roleToAssign = null; if (windowsPrincipal.IsInRole(_domainDetails.AdminDomainGroup)) { roleToAssign = UserRoleEnum.Admin; } else if (windowsPrincipal.IsInRole(_domainDetails.AnalystDomainGroup)) { roleToAssign = UserRoleEnum.Analyst; } if (roleToAssign == null) { Logger.Instance.Warn(string.Format("Blocked connection attempt by Windows account {0} not in Admin or Analyst group.", windowsPrincipal.Identity.Name), LoggerConsts.AccountLogInError); return(false); } var profile = _userProfileAccessor.GetUserProfile(windowsPrincipal.Identity.GetUserName()); if (profile == null) { if (!mgmtConfig.AutoCreateUsers) { Logger.Instance.Warn(string.Format("Windows account {0} is authorized but does not have profile.", windowsPrincipal.Identity.Name), LoggerConsts.AccountLogInError); return(false); } var userDetails = UserAndDomainHelper.GetUserPrincipal(windowsPrincipal.Identity.GetUserName(), GetActiveDirectoryCredentials()); var user = new UserProfile { FirstName = userDetails.GivenName, LastName = userDetails.Surname, UserName = windowsPrincipal.Identity.Name, Email = userDetails.EmailAddress, Role = roleToAssign.Value, UserType = UserType.Windows, ImageBase64 = null }; _userProfileAccessor.AddOrUpdateUserProfile(user); } else { if (profile.Role != roleToAssign.Value) { profile.Role = roleToAssign.Value; _userProfileAccessor.AddOrUpdateUserProfile(profile); } if (profile.IsDisabled) { Logger.Instance.Debug(string.Format("Blocked login attempt by disabled user {0}", profile.UserName), LoggerConsts.AccountLogInError); return(false); } } return(true); }
public override void OnAuthorization(HttpActionContext actionContext) { // validar se foi informado no cabeçalho da mensagem o parâmetro de autenticação. if (actionContext.Request.Headers.Authorization == null) { // responde para o cliente como não autorizado var dnsHost = actionContext.Request.RequestUri.DnsSafeHost; actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost)); return; } else { //obtém o parâmetro (token de autenticação) string tokenAutenticacao = actionContext.Request.Headers.Authorization.Parameter; // decodifica o parâmetro, pois ele deve vir codificado em base 64 string decodedTokenAutenticacao = Encoding.Default.GetString(Convert.FromBase64String(tokenAutenticacao)); // obtém o login e senha (usuario:senha) string[] userNameAndPassword = decodedTokenAutenticacao.Split(':'); // validar as credenciais obtidas com as cadastradas no sistema Usuario usuario = null; if (ValidarUsuario(userNameAndPassword[0], userNameAndPassword[1], out usuario)) { string[] papeis = usuario.Permissoes.Select(papel => papel.Nome).ToArray(); var identidade = new GenericIdentity(usuario.Email); var genericUser = new GenericPrincipal(identidade, papeis); // confere o perfil da action com os do usuário if (string.IsNullOrEmpty(Roles)) { // atribui o usuário informado no contexto da requisição atual Thread.CurrentPrincipal = genericUser; if (HttpContext.Current != null) { HttpContext.Current.User = genericUser; } return; } else { var currentRoles = Roles.Split(','); foreach (var currentRole in currentRoles) { if (genericUser.IsInRole(currentRole)) { // atribui o usuário informado no contexto da requisição atual Thread.CurrentPrincipal = genericUser; if (HttpContext.Current != null) { HttpContext.Current.User = genericUser; } return; } } } } } actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { mensagens = new string[] { "Usuário ou senha inválidos." } }); }
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext) { base.HandleUnauthorizedRequest(filterContext); }
/// <summary> /// 执行action时验证token /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { try { #region 请求记录 var builder = new StringBuilder(); builder.AppendLine(String.Format("ApiName:{0}", actionContext.ActionDescriptor.ActionName)); builder.AppendLine(String.Format("IP:{0}", XNY.Helper.String.ValueHelper.GetClientIP())); #region 获取请求Ip this.AccessIp = XNY.Helper.String.ValueHelper.GetClientIP(); #endregion #endregion #region 获取access_token if (actionContext.Request.Method == HttpMethod.Get) { string query = actionContext.Request.RequestUri.Query; this.AccessToken = HttpUtility.ParseQueryString(query).Get("access_token"); } else { this.AccessToken = HttpContext.Current.Request.Form["access_token"]; builder.AppendLine(String.Format("[POST]FormData:{0}", HttpContext.Current.Request.Form.ToString())); } #endregion LogHelper.Info(builder.ToString()); } catch (Exception ex) { var error = String.Format("actionContext:{0} Access {1} ", actionContext.Request.Method, ex.Message); } if (!string.IsNullOrWhiteSpace(AccessIp)) { IAccessTokenValidator accessTokenValidator = new AccessTokenValidator(ModuleName); var validIp = accessTokenValidator.ValidateIp(AccessIp); if (validIp.code > 0) { var response = new HttpResponseMessage { Content = new StringContent("This ip is not valid"), StatusCode = HttpStatusCode.Unauthorized }; var exception = new HttpResponseException(response); throw new HttpResponseException(response); } } // we first check for valid token if (!String.IsNullOrWhiteSpace(AccessToken)) { IAccessTokenValidator accessTokenValidator = new AccessTokenValidator(ModuleName); var validToken = accessTokenValidator.ValidateToken(AccessToken, (this.Scope ?? "").Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)); if (validToken.code > 0) { var response = new HttpResponseMessage { Content = new StringContent("This token is not valid, please refresh token or obtain valid token!"), StatusCode = HttpStatusCode.Unauthorized }; var exception = new HttpResponseException(response); throw new HttpResponseException(response); } } else { var response = new HttpResponseMessage { Content = new StringContent("You must supply valid token to access method!"), StatusCode = HttpStatusCode.Unauthorized }; var exception = new HttpResponseException(response); throw exception; } base.OnActionExecuting(actionContext); }
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { throw new NotImplementedException(); }
// Note the different signature to what you have in your question. public override void OnActionExecuting(HttpActionContext actionContext) { // }
public override void OnActionExecuting(HttpActionContext actionContext) { if (Current.UmbracoContext.Security.CurrentUser == null) { //not logged in throw new HttpResponseException(System.Net.HttpStatusCode.Unauthorized); } int nodeId; if (_nodeId.HasValue == false) { var parts = _paramName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (actionContext.ActionArguments[parts[0]] == null) { throw new InvalidOperationException("No argument found for the current action with the name: " + _paramName); } if (parts.Length == 1) { var argument = actionContext.ActionArguments[parts[0]].ToString(); // if the argument is an int, it will parse and can be assigned to nodeId // if might be a udi, so check that next // otherwise treat it as a guid - unlikely we ever get here if (int.TryParse(argument, out int parsedId)) { nodeId = parsedId; } else if (UdiParser.TryParse(argument, true, out Udi udi)) { // TODO: inject? we can't because this is an attribute but we could provide ctors and empty ctors that pass in the required services nodeId = Current.Services.EntityService.GetId(udi).Result; } else { Guid.TryParse(argument, out Guid key); // TODO: inject? we can't because this is an attribute but we could provide ctors and empty ctors that pass in the required services nodeId = Current.Services.EntityService.GetId(key, UmbracoObjectTypes.Document).Result; } } else { //now we need to see if we can get the property of whatever object it is var pType = actionContext.ActionArguments[parts[0]].GetType(); var prop = pType.GetProperty(parts[1]); if (prop == null) { throw new InvalidOperationException("No argument found for the current action with the name: " + _paramName); } nodeId = (int)prop.GetValue(actionContext.ActionArguments[parts[0]]); } } else { nodeId = _nodeId.Value; } var permissionResult = ContentPermissionsHelper.CheckPermissions(nodeId, Current.UmbracoContext.Security.CurrentUser, Current.Services.UserService, Current.Services.ContentService, Current.Services.EntityService, out var contentItem, _permissionToCheck.HasValue ? new[] { _permissionToCheck.Value } : null); if (permissionResult == ContentPermissionsHelper.ContentAccess.NotFound) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (permissionResult == ContentPermissionsHelper.ContentAccess.Denied) { throw new HttpResponseException(actionContext.Request.CreateUserNoAccessResponse()); } if (contentItem != null) { //store the content item in request cache so it can be resolved in the controller without re-looking it up actionContext.Request.Properties[typeof(IContent).ToString()] = contentItem; } base.OnActionExecuting(actionContext); }
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); base.HandleUnauthorizedRequest(actionContext); }
public override void OnAuthorization(HttpActionContext actionContext) { base.OnAuthorization(actionContext); }
/// <summary> /// 从当前Http(请求)上下文获取用户信息 /// </summary> /// <param name="ctx"></param> /// <returns></returns> protected abstract TUserId GetUserId(HttpActionContext ctx);
public override void OnActionExecuting(HttpActionContext actionContext) { OnActionExecutingInternal(actionContext); base.OnActionExecuting(actionContext); }
public void Test_AuditApiActionFilter_InsertOnEnd() { // Mock out the context to run the action filter. var request = new Mock <HttpRequestBase>(); //var request = new HttpRequest(null, "http://200.10.10.20:1010/api/values", null); request.Setup(c => c.ContentType).Returns("application/json"); var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("{ Id: 'test' }"); writer.Flush(); stream.Position = 0; request.Setup(c => c.InputStream).Returns(stream); request.Setup(c => c.ContentLength).Returns(123); var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new HttpControllerContext() { ControllerDescriptor = new HttpControllerDescriptor() { ControllerName = "values" }, Request = new HttpRequestMessage() }; controllerContext.Request.Headers.Add("test-header", "header-value"); var actionDescriptor = new Mock <HttpActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); var args = new Dictionary <string, object>() { { "test1", "value1" } }; var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEvent(It.IsAny <AuditEvent>())).Returns(Guid.NewGuid()); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnEnd; var filter = new AuditApiAttribute() { IncludeHeaders = true, IncludeModelState = true, IncludeResponseBody = true, IncludeRequestBody = true, EventTypeName = "TestEvent" }; var actionContext = new HttpActionContext() { ActionDescriptor = actionDescriptor.Object, ControllerContext = controllerContext, }; var actionExecutingContext = new HttpActionContext(controllerContext, actionDescriptor.Object); actionExecutingContext.ActionArguments.Add("test1", "value1"); var self = new TestClass() { Id = 1 }; actionExecutingContext.ActionArguments.Add("SelfReferencing", self); Console.WriteLine(JsonConvert.SerializeObject(self, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); actionExecutingContext.Request.Properties.Add("MS_HttpContext", httpContext.Object); filter.OnActionExecuting(actionExecutingContext); var scopeFromController = AuditApiAttribute.GetCurrentScope(controllerContext.Request); var actionFromController = scopeFromController.Event.GetWebApiAuditAction(); var actionExecutedContext = new HttpActionExecutedContext(actionContext, null); actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage() { StatusCode = HttpStatusCode.OK }; filter.OnActionExecuted(actionExecutedContext); var action = itemsDict["__private_AuditApiAction__"] as AuditApiAction; var scope = itemsDict["__private_AuditApiScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Never); Assert.AreEqual(action, actionFromController); Assert.AreEqual(scope, scopeFromController); dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); Assert.AreEqual("header-value", action.Headers["test-header"]); Assert.AreEqual("get", action.ActionName); Assert.AreEqual("value1", action.ActionParameters["test1"]); Assert.AreEqual(123, ((dynamic)action.RequestBody).Length); Assert.AreEqual("application/json", ((dynamic)action.RequestBody).Type); }
public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { return(base.BindModelForType(actionContext, bindingContext, typeof(long))); }
public void Test_AuditApiActionFilter_InsertOnStartReplaceOnEnd() { // Mock out the context to run the action filter. var request = new Mock <HttpRequestBase>(); //var request = new HttpRequest(null, "http://200.10.10.20:1010/api/values", null); request.Setup(c => c.ContentType).Returns("application/json"); var httpResponse = new Mock <HttpResponseBase>(); httpResponse.Setup(c => c.StatusCode).Returns(200); var itemsDict = new Dictionary <object, object>(); var httpContext = new Mock <HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Items).Returns(() => itemsDict); httpContext.SetupGet(c => c.Response).Returns(() => httpResponse.Object); var controllerContext = new HttpControllerContext() { ControllerDescriptor = new HttpControllerDescriptor() { ControllerName = "values" }, Request = new HttpRequestMessage() }; controllerContext.Request.Headers.Add("test-header", "header-value"); var actionDescriptor = new Mock <HttpActionDescriptor>(); actionDescriptor.Setup(c => c.ActionName).Returns("get"); var args = new Dictionary <string, object>() { { "test1", "value1" } }; var dataProvider = new Mock <AuditDataProvider>(); dataProvider.Setup(x => x.InsertEvent(It.IsAny <AuditEvent>())).Returns(Guid.NewGuid()); Audit.Core.Configuration.DataProvider = dataProvider.Object; Audit.Core.Configuration.CreationPolicy = EventCreationPolicy.InsertOnStartReplaceOnEnd; var filter = new AuditApiAttribute() { IncludeHeaders = true, IncludeModelState = true, IncludeResponseBody = true, EventTypeName = "TestEvent" }; var actionContext = new HttpActionContext() { ActionDescriptor = actionDescriptor.Object, ControllerContext = controllerContext, }; var actionExecutingContext = new HttpActionContext(controllerContext, actionDescriptor.Object); actionExecutingContext.ActionArguments.Add("test1", "value1"); actionExecutingContext.Request.Properties.Add("MS_HttpContext", httpContext.Object); filter.OnActionExecuting(actionExecutingContext); var scopeFromController = AuditApiAttribute.GetCurrentScope(controllerContext.Request); var actionFromController = scopeFromController.Event.GetWebApiAuditAction(); var actionExecutedContext = new HttpActionExecutedContext(actionContext, null); actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage() { StatusCode = HttpStatusCode.OK }; filter.OnActionExecuted(actionExecutedContext); var action = itemsDict["__private_AuditApiAction__"] as AuditApiAction; var scope = itemsDict["__private_AuditApiScope__"] as AuditScope; //Assert dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); dataProvider.Verify(p => p.ReplaceEvent(It.IsAny <object>(), It.IsAny <AuditEvent>()), Times.Once); Assert.AreEqual(action, actionFromController); Assert.AreEqual(scope, scopeFromController); dataProvider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Once); Assert.AreEqual("header-value", action.Headers["test-header"]); Assert.AreEqual("get", action.ActionName); Assert.AreEqual("value1", action.ActionParameters["test1"]); }
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { bindingContext.Model = new BinderPrecedenceModel { Precedence = BinderPrecedence.Model }; return true; }
public void SetOAuthErrorResponse(HttpActionContext actionContext, ResponseBaseModel content) { actionContext.Response = new HttpResponseMessage(); actionContext.Response.Content = new StringContent(JsonConvert.SerializeObject(content)); actionContext.Response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); }
public virtual void Response(HttpActionContext context) { if (context != null && context.IsCached == false && !string.IsNullOrEmpty(context.CacheKey) ) { context.IsCached = true; cacheManager.Add( context.CacheKey, context, null, DateTime.Now.AddSeconds(this.DefaultExpireSeconds), TimeSpan.Zero, CacheItemPriority.Default, null); } IHttpAction httpAction = NextAction as IHttpAction; if (httpAction != null) httpAction.Response(context); }
public Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { var actionAttrs = actionContext.ActionDescriptor.GetCustomAttributes <CustomAuthorizeAttribute>(); if (actionAttrs.Count > 0) { var responseBaseModel = new ResponseBaseModel(); ClaimsPrincipal principal = actionContext.RequestContext.Principal as ClaimsPrincipal; if (principal != null && principal.Identity.IsAuthenticated) { //认证成功 if (actionAttrs.Any(s => null != s.Roles && s.Roles.Count() > 0)) { //需要验证权限的情况 List <Role> needRoles = actionAttrs .Select(s => s.Roles.Select(m => new Role() { roleType = s.RoleType, roleCode = m }).ToList()) .Aggregate((result, next) => { result.AddRange(next.Where(s => !result.Exists(m => m.roleType.Equals(s.roleType) && m.roleCode.Equals(s.roleCode)))); return(result); }); //当前用户具有的权限 //var oAuthRoles = principal.Claims.Where(s => s.Type.Equals(ClaimTypes.Role)).Select(s => s.Value).ToList(); //List<Role> localRoles = identityService.TransformOAuthRoleToLocalRole(oAuthRoles); var userMail = ((ClaimsIdentity)principal.Identity).FindFirst(ClaimTypes.Email).Value; var userRepoModel = this.userRepository.GetUser(userMail); List <Role> localRoles = userRepoModel.roleList; var reqParams = actionContext.ActionArguments.Values.FirstOrDefault() as RequestBaseModel; if (needRoles.Count(s => s.roleType.Equals(RoleType.Team)).Equals(needRoles.Count()) && (null == reqParams || reqParams.teamID == 0)) { //为了可读性,因此不采用!needRoles.Exists(s=>!s.roleType.Equals(RoleType.Team)) //全部是团队的角色 responseBaseModel.SetResponse(ResStatusCode.FrontInputValidateError, "团队ID不能为空"); SetOAuthErrorResponse(actionContext, responseBaseModel); } else if (needRoles.Count(s => s.roleType.Equals(RoleType.Project)).Equals(needRoles.Count()) && (null == reqParams || reqParams.projectID == 0)) { //全部是项目的角色 responseBaseModel.SetResponse(ResStatusCode.FrontInputValidateError, "项目ID不能为空"); SetOAuthErrorResponse(actionContext, responseBaseModel); } else if (null == reqParams || (reqParams.teamID == 0 && reqParams.projectID == 0)) { //混合项目和团队的角色(一般不可能发生) responseBaseModel.SetResponse(ResStatusCode.FrontInputValidateError, "团队ID和项目ID不能同时为空"); SetOAuthErrorResponse(actionContext, responseBaseModel); } else if (!CheckAuthorize(localRoles, needRoles, reqParams)) { //无角色匹配 responseBaseModel.SetResponse(ResStatusCode.UnAuthorize, "未授权用户"); SetOAuthErrorResponse(actionContext, responseBaseModel); } } } else { //认证失败 responseBaseModel.SetResponse(ResStatusCode.UnAuthenticate, "未认证用户"); SetOAuthErrorResponse(actionContext, responseBaseModel); } #region 废弃代码 //var response = new HttpResponseMessage(); //var responseContent = new ResponseBaseModel(); //var resMsg = new List<string>(); //var reqParams = (RequestBaseModel)actionContext.ActionArguments.Values.FirstOrDefault(); //reqParams = reqParams == null ? new RequestBaseModel() : reqParams; //if (string.IsNullOrEmpty(reqParams.createUser)) //{ // resMsg.Add("创建人未填"); //} //if (string.IsNullOrEmpty(reqParams.createUserName)) //{ // resMsg.Add("创建人姓名未填"); //} //if (reqParams.createTime < 0) //{ // resMsg.Add("创建时间未填"); //} //if (string.IsNullOrEmpty(reqParams.token)) //{ // resMsg.Add("token未填"); //} //if (resMsg.Count > 0) //{ // responseContent.SetResponse(ResStatusCode.UnAuthenticate, String.Join(",", resMsg)); // response.Content = new StringContent(JsonConvert.SerializeObject(responseContent)); // actionContext.Response = response; // actionContext.Response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //} #endregion } return(Task.FromResult(0)); }
public override void OnActionExecuting(HttpActionContext actionContext) { OnActionExecuting(HttpMethod, HttpContext.Current, () => base.OnActionExecuting(actionContext)); }
/// <summary> /// 格式化输出 /// </summary> /// <param name="context"></param> public override void Response(HttpContext httpContext, HttpActionContext context) { new BasicHttpMethodResponse().ProcessResponse(httpContext, context); }