public SyndicationItem CreateItem(IncomingWebRequestContext request, Stream stream) { return handlers .Where(x => x.CanCreateItem(request)) .FirstOrDefault() .CreateItem(request, stream); }
private static IRequest CreateNancyRequestFromIncomingRequest(IncomingWebRequestContext req) { var ruri = req.UriTemplateMatch.BaseUri.MakeRelativeUri(req.UriTemplateMatch.RequestUri); return new Request( req.Method, "/"+ruri.ToString()); }
private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody) { var address = ((RemoteEndpointMessageProperty) OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]); var relativeUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri).MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri)); var expectedRequestLength = GetExpectedRequestLength(webRequest.Headers.ToDictionary()); var nancyUrl = new Url { BasePath = webRequest.UriTemplateMatch.BaseUri.AbsolutePath, Scheme = webRequest.UriTemplateMatch.RequestUri.Scheme, HostName = webRequest.UriTemplateMatch.BaseUri.Host, Port = webRequest.UriTemplateMatch.RequestUri.IsDefaultPort ? null : (int?)webRequest.UriTemplateMatch.RequestUri.Port, Path = string.Concat("/", relativeUri), Query = webRequest.UriTemplateMatch.RequestUri.Query }; return new Request( webRequest.Method, nancyUrl, RequestStream.FromStream(requestBody, expectedRequestLength, false), webRequest.Headers.ToDictionary(), address.Address); }
/** * Check authz before performing action. * * @param action desired action * @throws NotAuthorizedException thrown if user does not have role. */ public void checkAuthorization(Action action, IncomingWebRequestContext context) { // throws NotAuthorizedException string clientApplicationName = (string)context.GetType().GetProperty(RequestHandler.APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR).ToString(); ClientApplication clientApplication = appSensorServer.getConfiguration().findClientApplication(clientApplicationName); appSensorServer.getAccessController().assertAuthorized(clientApplication, action, new Context()); }
public static void CheckModifiedSince(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, DateTime serverModifiedDate) { DateTime modifiedSince = Convert.ToDateTime(incomingRequest.Headers[HttpRequestHeader.LastModified]); if (modifiedSince != serverModifiedDate) return; outgoingResponse.SuppressEntityBody = true; outgoingResponse.StatusCode = HttpStatusCode.NotModified; }
public IncomingWebRequestContextWrapper(IncomingWebRequestContext incomingRequest) { if (incomingRequest == null) { throw new ArgumentNullException("incomingRequest"); } this.incomingRequest = incomingRequest; }
public static void CheckETag(IncomingWebRequestContext incomingRequest, OutgoingWebResponseContext outgoingResponse, Guid ServerETag) { string test = incomingRequest.Headers[HttpRequestHeader.IfNoneMatch]; if (test == null) return; Guid? eTag = new Guid(test); if (eTag != ServerETag) return; outgoingResponse.SuppressEntityBody = true; outgoingResponse.StatusCode = HttpStatusCode.NotModified; }
private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody, OperationContext context) { string ip = null; object remoteEndpointProperty; if (OperationContext.Current.IncomingMessageProperties.TryGetValue(RemoteEndpointMessageProperty.Name, out remoteEndpointProperty)) { ip = ((RemoteEndpointMessageProperty)remoteEndpointProperty).Address; } var baseUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri); if(!baseUri.OriginalString.EndsWith("/")) { baseUri = new Uri(string.Concat(baseUri.OriginalString, "/")); } var relativeUri = baseUri.MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri)); var expectedRequestLength = GetExpectedRequestLength(webRequest.Headers.ToDictionary()); var nancyUrl = new Url { BasePath = webRequest.UriTemplateMatch.BaseUri.AbsolutePath, Scheme = webRequest.UriTemplateMatch.RequestUri.Scheme, HostName = webRequest.UriTemplateMatch.BaseUri.Host, Port = webRequest.UriTemplateMatch.RequestUri.IsDefaultPort ? null : (int?)webRequest.UriTemplateMatch.RequestUri.Port, Path = string.Concat("/", relativeUri), Query = webRequest.UriTemplateMatch.RequestUri.Query }; byte[] certificate = null; if (context.ServiceSecurityContext != null && context.ServiceSecurityContext.AuthorizationContext.ClaimSets.Count > 0) { var claimset = context.ServiceSecurityContext.AuthorizationContext.ClaimSets.FirstOrDefault( c => c is X509CertificateClaimSet) as X509CertificateClaimSet; if (claimset != null) { certificate = claimset.X509Certificate.RawData; } } return new Request( webRequest.Method, nancyUrl, RequestStream.FromStream(requestBody, expectedRequestLength, false), webRequest.Headers.ToDictionary(), ip, certificate); }
private static IRequest CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody) { var relativeUri = webRequest.UriTemplateMatch.BaseUri.MakeRelativeUri(webRequest.UriTemplateMatch.RequestUri); return new Request( webRequest.Method, string.Concat("/", relativeUri), webRequest.Headers.ToDictionary(), requestBody); }
public User Authorize(IncomingWebRequestContext request) { var headers = request.Headers; var auth_header = headers.Get("sma_auth"); if (auth_header == null) throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized); // Return 401 string token = auth_header.Split()[1]; if (!ValidateToken(token)) throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized); // Return 401 return userDA.GetOneByID(sessionDA.GetOneByToken(token).UserID); }
private static IRequest CreateNancyRequestFromIncomingRequest(IncomingWebRequestContext request, Stream body) { var relativeUri = request.UriTemplateMatch.BaseUri.MakeRelativeUri(request.UriTemplateMatch.RequestUri); return new Request( request.Method, string.Concat("/", relativeUri), request.Headers.ToDictionary(), body ?? new MemoryStream()); }
private string GetQueryStringValue(IncomingWebRequestContext context, string key) { try { var queryStrings = context.UriTemplateMatch.QueryParameters; return queryStrings[key]; } catch { return null; } }
private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody) { var relativeUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri).MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri)); return new Request( webRequest.Method, string.Concat("/", relativeUri), webRequest.Headers.ToDictionary(), requestBody, webRequest.UriTemplateMatch.RequestUri.Scheme, webRequest.UriTemplateMatch.RequestUri.Query); }
private static string GetClientInformation(IncomingWebRequestContext context) { var headerInfo = new StringBuilder(); foreach (string key in context.Headers.Keys) { headerInfo.Append("Session("); headerInfo.Append(key); headerInfo.Append(") - "); headerInfo.Append("<br/>"); } return "UserAgent: " + context.UserAgent + "<br/>" + "Content-Type: " + context.ContentType + "<br/>" + "Header: " + headerInfo + "<br/>"; }
public IIdentity Authenticate( IncomingWebRequestContext request, OutgoingWebResponseContext response, object[] parameters, UserNamePasswordValidator validator, bool secure, bool requiresTransportLayerSecurity, string source) { if (requiresTransportLayerSecurity && !secure) throw new BasicRequiresTransportSecurityException(); var authentication = new BasicAuthentication(request.Headers); if (!authentication.Authenticate(validator)) throw new BasicUnauthorizedException(source); return new GenericIdentity(authentication.Username, "WebBasicAuthenticationHandler"); }
//@Override public void filter(IncomingWebRequestContext context) { //throws WebApplicationException //should only run on first request if (! checkedConfigurationHeaderName) { updateHeaderFromConfiguration(); checkedConfigurationHeaderName = true; } // Get the client application identifier passed in HTTP headers parameters String clientApplicationIdentifier = context.Headers.Get(HEADER_NAME); if (clientApplicationIdentifier == null) { throw unauthorized; } context.Headers.Set(RequestHandler.APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR, clientApplicationIdentifier); }
/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> /// <param name="parameters">The parameters.</param> /// <param name="secure">if set to <c>true</c> [secure].</param> /// <param name="requiresTransportLayerSecurity">if set to <c>true</c> [requires transport layer security].</param> /// <param name="scope">The scope.</param> /// <returns></returns> public IIdentity Authenticate(IncomingWebRequestContext request, OutgoingWebResponseContext response, object[] parameters, bool secure, bool requiresTransportLayerSecurity, string scope, bool allowAnonymous) { var clientProvider = new ClientProvider(); var passwordProvider = new PasswordProvider(); var tokenProvider = new TokenProvider(); var scopes = new List<string>(); var oAuthProvider = OAuthFactory.BuildOAuthProvider(clientProvider, tokenProvider, scopes, passwordProvider: passwordProvider); var token = request.Headers["Authorization"]; if (string.IsNullOrWhiteSpace(token)) { token = HttpContext.Current.Request.QueryString["access_token"]; } else { if (!string.IsNullOrWhiteSpace(token) && token.StartsWith("OAuth") && token.Contains(" ")) { var splitToken = token.Split(' '); if (splitToken.Length > 1) { token = splitToken[1]; } } } var authentication = oAuthProvider.VerifyToken(token, scope); if (authentication.ErrorCode != ErrorCode.None) { if (allowAnonymous) { return null; } var errorCode = authentication.StatusCode(); var oauthError = authentication.Error(); if (errorCode == HttpStatusCode.Unauthorized) { response.Headers.Add(HttpResponseHeader.WwwAuthenticate, string.Format("OAuth realm='PollMe Service', error='{0}'", oauthError)); } throw new WebFaultException<string>(oauthError, authentication.StatusCode()); } return new GenericIdentity("Authorized User", "OAuth2"); }
/// <summary> /// From the initial web request, extract some basic information. /// </summary> /// <param name="context">The web request context.</param> /// <param name="headers">(out) The headers of the request.</param> /// <param name="operation">(out) The operation requested.</param> /// <param name="isSSL">(out) True if the operation is using SSL.</param> /// <returns>An errordetail instance holding any error that was encountered, or null if no errors were encountered.</returns> private static errordetail GatherBasicInfo(System.ServiceModel.Web.IncomingWebRequestContext context, out WebHeaderCollection headers, out string operation, out bool isSSL) { errordetail result = null; headers = context.Headers; int lastSlashPos = context.UriTemplateMatch.BaseUri.AbsolutePath.LastIndexOf('/') + 1; operation = context.UriTemplateMatch.BaseUri.AbsolutePath.Substring(lastSlashPos); // string.Empty; isSSL = context.UriTemplateMatch.BaseUri.Scheme == "https"; if (Functions.IsEmptyString(operation)) { result = new errordetail(string.Format("Unable to determine operation: \"{0}\"", operation), HttpStatusCode.BadRequest); } return(result); }
private static Request CreateNancyRequestFromIncomingWebRequest(IncomingWebRequestContext webRequest, Stream requestBody) { var address = ((RemoteEndpointMessageProperty) OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name]); var relativeUri = GetUrlAndPathComponents(webRequest.UriTemplateMatch.BaseUri).MakeRelativeUri(GetUrlAndPathComponents(webRequest.UriTemplateMatch.RequestUri)); var expectedRequestLength = GetExpectedRequestLength(webRequest.Headers.ToDictionary()); return new Request( webRequest.Method, string.Concat("/", relativeUri), webRequest.Headers.ToDictionary(), RequestStream.FromStream(requestBody, expectedRequestLength, false), webRequest.UriTemplateMatch.RequestUri.Scheme, webRequest.UriTemplateMatch.RequestUri.Query, address.Address); }
public IIdentity Authenticate( IncomingWebRequestContext request, OutgoingWebResponseContext response, object[] parameters, Type validatorType, bool secure, bool requiresTransportLayerSecurity, string source) { if (requiresTransportLayerSecurity && !secure) throw new BasicRequiresTransportSecurityException(); var authentication = new BasicAuthentication(request.Headers); var validator = validatorType != null ? DependencyResolver.Current.GetOperationService<UserNamePasswordValidator>(OperationContainer.GetCurrent(), validatorType) : DependencyResolver.Current.GetOperationService<UserNamePasswordValidator>(OperationContainer.GetCurrent()).ThrowIfNull(); if (!authentication.Authenticate(validator)) throw new BasicUnauthorizedException(source); return new GenericIdentity(authentication.Username, "WebBasicAuthenticationHandler"); }
public NetHttpServiceRequest(IncomingWebRequestContext request) { this.request = request; MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties; RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; Headers.Add("REMOTE_HOST", endpointProperty.Address); Params = HttpUtility.ParseQueryString(request.UriTemplateMatch.RequestUri.Query); if (Method.Equals("post", StringComparison.CurrentCultureIgnoreCase) || Method.Equals("put", StringComparison.CurrentCultureIgnoreCase)) { NetHttpPostBody postBody; if (NetHttpUtility.TryParsePostBody(out postBody)) { postBody.Parameters.Keys.Cast<String>().ToList().ForEach((k) => { Params.Add(k, postBody.Parameters[k]); }); } } }
/// <summary> /// This is where we issue the challenge if they have no authenticated. /// </summary> public void Set401AuthenticationHeaders(System.ServiceModel.Web.IncomingWebRequestContext context, bool isNonceStale) { string realm = Realm; string nonce = GetCurrentNonce(); StringBuilder challenge = new StringBuilder("Digest"); challenge.Append(" realm=\""); challenge.Append(realm); challenge.Append("\""); challenge.Append(", nonce=\""); challenge.Append(nonce); challenge.Append("\""); challenge.Append(", opaque=\"0000000000000000\""); challenge.Append(", stale="); challenge.Append(isNonceStale ? "true" : "false"); challenge.Append(", algorithm=MD5"); challenge.Append(", qop=\"auth\""); System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate", challenge.ToString()); }
private IAsyncResult DispatchToHttpServer( IncomingWebRequestContext incomingRequest, Stream body, OutgoingWebResponseContext outgoingResponse, bool bufferBody, AsyncCallback callback, object state) { var request = MakeHttpRequestMessageFrom(incomingRequest, body, bufferBody); var tcs = new TaskCompletionSource<Stream>(state); _server.SubmitRequestAsync(request, new CancellationToken()) .ContinueWith(t => { var response = t.Result; CopyHttpResponseMessageToOutgoingResponse(response, outgoingResponse); Action<Task<Stream>> complete = (t2) => { if (t2.IsFaulted) tcs.TrySetException( t2.Exception.InnerExceptions); else if (t2.IsCanceled) tcs.TrySetCanceled(); else tcs.TrySetResult(t2.Result); if (callback != null) callback(tcs.Task); }; if (response.Content == null) { tcs.TrySetResult(null); if (callback != null) callback(tcs.Task); } else { response.Content.ReadAsStreamAsync() .ContinueWith(complete); } }); return tcs.Task; }
private static bool Authenticate(IncomingWebRequestContext context) { bool Authenticated = false; string normalizedUrl; string normalizedRequestParameters; //context.Headers NameValueCollection pa = context.UriTemplateMatch.QueryParameters; if (pa != null && pa["oauth_consumer_key"] != null) { // to get uri without oauth parameters string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace (context.UriTemplateMatch.RequestUri.Query, ""); string consumersecret = "secret"; OAuthBase oauth = new OAuthBase(); string hash = oauth.GenerateSignature( new Uri(uri), pa["oauth_consumer_key"], consumersecret, null, // totken null, //token secret "GET", pa["oauth_timestamp"], pa["oauth_nonce"], out normalizedUrl, out normalizedRequestParameters ); Authenticated = pa["oauth_signature"] == hash; } return Authenticated; }
public static Principal GetContext(IncomingWebRequestContext request) { var token = request.Headers.Get("oauth_token") ?? String.Empty; if (String.IsNullOrEmpty(token)) { if(String.IsNullOrEmpty(request.UriTemplateMatch.QueryParameters["oauth_token"])) { throw new WebFaultException(HttpStatusCode.Unauthorized); } token = request.UriTemplateMatch.QueryParameters["oauth_token"]; } if (!AuthManager.ValidateToken(token)) { throw new WebFaultException(HttpStatusCode.Unauthorized); } var principal = AuthManager.GetPrincipal(token); return principal; }
public SyndicationItem CreateItem(IncomingWebRequestContext request, Stream stream) { var slug = request.Headers["Slug"]; var contentType = request.ContentType; return new MediaSyndicationItem() { Title = new TextSyndicationContent(slug), Id = slug, MediaContentType = contentType, MediaContent = stream.ReadToArray(), Links = { new SyndicationLink { Uri = new Uri(slug, UriKind.Relative), RelationshipType = "enclosure", Title = slug, MediaType = contentType, Length = request.ContentLength } } }; }
/// <summary> /// Makes the request object and fills it with everything except the user /// </summary> /// <param name="request">The incoming request context</param> /// <param name="data">The data dictionary</param> /// <returns></returns> private static Request makeRequest(IncomingWebRequestContext request, Dictionary<string, string> data, string authorization) { //gets the whole uri string pathUri = request.UriTemplateMatch.RequestUri.PathAndQuery; //we only want the important part. example user/23 string[] trimmedUri = pathUri.Split(new string[] {"/RestServiceImpl.svc/"},StringSplitOptions.None); string importantUri = trimmedUri[1]; //breaks up the important part of the uri and puts them in a linked list string[] uriParts = importantUri.Split('/'); LinkedList<string> uri = new LinkedList<string>(uriParts); //gets the request method RestMethods method = (RestMethods) Enum.Parse(typeof(RestMethods), request.Method); return new Request(uri, method, data, null, authorization); }
public SyndicationItem CreateItem(IncomingWebRequestContext request, Stream stream) { var item = SyndicationItem.Load(XmlReader.Create(stream)); item.Id = HttpUtility.UrlEncode(item.Title.Text); return item; }
public bool CanCreateItem(IncomingWebRequestContext request) { return request.ContentType.StartsWith(ContentTypes.AtomEntry); }
public IncomingWebRequestContextWrapper(IncomingWebRequestContext context) { this.context = context; }
private static HttpRequestMessage MakeHttpRequestMessageFrom(IncomingWebRequestContext oreq, Stream body, bool bufferBody) { var nreq = new HttpRequestMessage(new HttpMethod(oreq.Method), oreq.UriTemplateMatch.RequestUri); foreach (var name in oreq.Headers.AllKeys.Where(name => !_httpContentHeaders.Contains(name))) { //nreq.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name).Split(',').Select(s => s.Trim())); nreq.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name)); } if (body != null) { if (bufferBody) { var ms = new MemoryStream(); body.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); nreq.Content = new StreamContent(ms); }else{ nreq.Content = new StreamContent(body); } foreach (var name in oreq.Headers.AllKeys.Where(name => _httpContentHeaders.Contains(name))) { //nreq.Content.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name).Split(',').Select(s => s.Trim())); nreq.Content.Headers.TryAddWithoutValidation(name, oreq.Headers.Get(name)); } } return nreq; }
/// <summary> /// Validate whether the user is authenticated and whether the user is authorized for this operation. /// </summary> /// <remarks> /// This function will not return if the request is invalid. An error is thrown and the appropriate response returned to the client. /// If this function does return, the request can safely be considered valid. /// </remarks> public static void Validate() { // // Variables required for authentication and authorization. // System.ServiceModel.Web.IncomingWebRequestContext context = System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest; errordetail currentException = null; AuthenticationConfig auth = AuthenticationConfig.Instance; WebHeaderCollection headers = null; string ipAddress = string.Empty; string operation = string.Empty; bool isSSL = false; AuthenticationMethod operationAuthenticationMethod = AuthenticationMethod.Unknown; bool opRequiresCredentials = true; OttaMattaAuthentication authModule = null; // // Test for credentials // currentException = GatherBasicInfo(context, out headers, out operation, out isSSL); if (currentException == null) { currentException = GetCredentialStatus(auth, operation, out opRequiresCredentials, out operationAuthenticationMethod); } // // Validate SSL status // if (currentException == null) { currentException = ValidateSSLStatus(auth, operation, isSSL, operationAuthenticationMethod); } // // Authenticate the user // if (currentException == null) { currentException = ValidateAuthenticationCredentials(opRequiresCredentials, auth, context, operationAuthenticationMethod, out authModule); } // // Authorize the user for this operation // if (currentException == null) { currentException = AuthorizeUserForOperation(opRequiresCredentials, auth, authModule, operation); } // // Validate IP address // if (currentException == null) { currentException = AuthorizeIPAddressForUser(auth, authModule, operation, System.ServiceModel.OperationContext.Current); } // // Validate throttling // if (currentException == null) { currentException = ValidateThrottleForUser(authModule, operation); } // // Can't continue - return the response. // if (currentException != null) { throw new WebFaultException <errordetail>(currentException, currentException.statuscode); } }
private OwinContext MakeOwinContextFrom(IncomingWebRequestContext incomingRequest, Stream inputStream, Stream outputStream, IList<Tuple<Action<object>,object>> onSendingHeadersHandler) { var ctx = new OwinContext(); ctx.Request.Method = incomingRequest.Method; var reqUri = incomingRequest.UriTemplateMatch.RequestUri; ctx.Request.Scheme = reqUri.Scheme; ctx.Request.Path = new PathString(reqUri.AbsolutePath); ctx.Request.QueryString = new QueryString(reqUri.Query); var onSendingHeaders = new Action<Action<object>, object>((h, o) => onSendingHeadersHandler.Add(Tuple.Create(h, o))); ctx.Response.Set("server.OnSendingHeaders", onSendingHeaders); foreach (var name in incomingRequest.Headers.AllKeys) { ctx.Request.Headers.Append(name, incomingRequest.Headers.Get(name)); } ctx.Request.Body = inputStream; ctx.Response.Body = outputStream; return ctx; }
/// <summary> /// From the current context, determine if we have enough information to authenticate the user/request. /// </summary> /// <param name="opRequiresCredentials">Whether the operation requires credentials or not.</param> /// <param name="auth">An authentication configuration instance.</param> /// <param name="context">The server request context.</param> /// <param name="operationAuthenticationMethod">The authentication method required for the current operation.</param> /// <param name="authModule">(out) A authentication module that can be used to authenticate this user.</param> /// <returns>An errordetail instance holding any error that was encountered, or null if no errors were encountered.</returns> private static errordetail ValidateAuthenticationCredentials(bool opRequiresCredentials, AuthenticationConfig auth, System.ServiceModel.Web.IncomingWebRequestContext context, AuthenticationMethod operationAuthenticationMethod, out OttaMattaAuthentication authModule) { errordetail result = null; authModule = null; if (opRequiresCredentials) { if (operationAuthenticationMethod == AuthenticationMethod.Basic) { authModule = new BasicAuthentication(); } else { authModule = new DigestAuthentication(); } authModule.Context = context; authModule.Auth = auth; result = authModule.Authenticate(); } return(result); }