How to set domain in response["set-cookie"] - ruby-on-rails

So the thing is, this code works very well:
response["set-cookie"]="cookieName=#{#cookieValue.split.join}"
I can set a cookie, with a correct name and content (yes, split.join is correct too). But I need to set a domain too.
My website goes on domain like this: mysubdomain.mywebsite.com
But I need to set the cookie for domain mywebsite.com.
If I add it like this, the cookie is just not there:
response["set-cookie"]="cookieName=#{#cookieValue.split.join};Path=/;Domain=mywebsite.com"
I need to set a cookie with response["set-cookie"] because it is the only method that works for my long string. I tried every method, but I need to use this one.
So the question is: How can I set a domain by using response["set-cookie"] for setting cookie?

Well, prefer using an initializer here. Create a new file config/initializers/cookies.rb, and put the following code there:
options = {
key: 'your_cookie_name',
domain: 'your_domain'
}
Rails.application.config.session_store :cookie_store, options
This will make your cookie-related configuration at one place, although, it's not mandatory. You can still use the domain option to specify domain name for your cookie.

I wasn't able to make that works. I think Rails have some safety mechanism that prevents this (but it is correct to set cookie for domain from subdomain).
But I was able to do it by javascript:
document.cookie = "#{#cookieName}=#{#cookieContent};domain=yourdomain.com"
One line of code, works perfectly. Just put it in your view or to separate file and require it in application.js I am on subdomain but finally can set cookie for parent domain.

Related

MVC Core 2.0 Cookie authentication LoginPath option

I'm trying to use cookie based authentication in MVC 2.0 with localized URL. In "Configuration" function I'm using:
services.AddAuthentication("MyScheme")
.AddCookie("MyScheme", options =>
{
options.AccessDeniedPath = "/Auth/Forbidden/";
options.LoginPath = "/Auth/SignIn/";
});
Everything would be fine, but I'm using localized URL like:
template: "{culture}/{controller=Home}/{action=Index}/{id?}"
Is it possible somehow to specify sime pattern in options above to suit the localization URL (like /en/Auth/SignIn/ or other languages)? Right now it is strongy set and this causes problems.
Thank you.
The Action<CookieAuthenticationOptions> has the [PathString] LoginPath and [PathString] AccessDeniedPath properties available to it, including the Cookie that is in the process of being constructed (CookieBuilder) and the CookieManager.
I'm not sure if it's absolutely necessary, but I feel fairly confident that you could attach a handler to one or more CookieAuthenticationOptions.Events that re-writes the cookie's path properties accordingly using the provided RedirectContext passed to the handler. See ref - CookieAuthenticationHandler to examine the details of how the path strings are used. In particular, you might look at the CookieAuthenticationEvents:RedirectToAccessDenied and CookieAuthenticationEvents:RedirectToLogin.
That said, I would first want to verify that you're not missing out on a way to get what you want via what's already built-in. Assuming your setup is something like
services.AddMvc(options => { options.Filters.Add(new MiddlewareFilterAttribute(typeof(LocalizationPipeline))); });
I would think that the RouteDataRequestCultureProviderwould handle appending the culture to the /Auth/Forbidden URL that ends up being issued, hinting that there might be a more optimal solution somewhere in how the components are being configured rather than in custom rewriting of paths.
Some additional references:
https://andrewlock.net/url-culture-provider-using-middleware-as-mvc-filter-in-asp-net-core-1-1-0/
https://github.com/aspnet/Security/blob/488eb44467eb677eab62bdc49aa6255cc1be3119/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationOptions.cs

How to remove a query parameter from URL without refresh the router in Ember js

I have a website built from Ember.js. A user can access a page through URL http://..../view?showTitle=true. However I don't want to explicitly expose the parameter showTitle=true to the user (meaning user will only see http://..../view). This URL is automatically generated and serves as a redirect destination URL. So, I have to remove it manually somewhere before the page load. But I still need this value of this query parameter to query data. Is there a way to achieve that (A example would be great)? What about do it without refreshing the router?
Actually, an example of your scenario would be greater :)
There are some other ways to store data while transitioning to a route. Such as: storing the params in transition object or storing the value in a service. Create a redirection route, use beforeModel hook to grab the value from query params then do a redirection to the real route.
A working example is: ember-twiddle-1
By the way, even if you don't describe your queryParamsin your routes, you can access them via transition.queryParams. This seems a bit hacky. But it works: ember-twiddle-2 (Note: It doesn't work in the same route.)
Updated:
At the setupController hook you can override the controller parameters. So you can remove the parameters from the url. ember-twiddle-3

swagger - how to set security properly

Two questions:
When you define a new route and you want to protect it by requiring an api_key to be set in the header, do you do it by specifying a security section under that route in the yaml file, or do you put it under parameters (or in both)? If it works by putting it under parameters, what's the point of putting it under security?
The yaml file can tell you that certain routes are protected by an api_key, but it doesn't specify the value of that key (as far as I know). Does it mean I need the write some custom middleware that intercepts my routes and checks the validity of the key, or it can be auto-generated by one of the swagger tools?
Thanks.
Im currently on the same journey as you. I do know this:
What to add in my swagger.json to accept api key
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject
"security": [
{
"api_key": []
}
]
what to add in my controller ...
https://github.com/apigee-127/swagger-tools/blob/master/docs/Middleware.md
Pretty much use swagger-tools to use the middleware.swaggerSecurity.
What they dont tell you is how to validate the api_key
Well I found that it's simply taking the 'scopes' parameter which holds the actual key and comparing that against a list of valid keys that you have stored somewhere.
What I dont get is how to allow the flow to go to the next function (like 'next()' in express) or stop if there is an invalid API key supplied. There is a 'callback' parameter, but I dont know how to use it (yet).
I hope this works.
You do need to implement the security checks on your own. Swagger will help you define them, but implementing is your job.

Handling question mark in url in codeigniter

I am using a payment method which on success returns a url like mysite/payment/sucess?auth=SDX53641sSDFSDF, but since i am using codeigniter, question marks in url are not working for me.
I tried routing but it didnt work. As a final resort i created a pre system hook and unset the GET part from the url for with i had to set
$config["uri_protocol"] = "REQUEST_URI";
It worked that way but all other links in my site were not working as intended, tried changing the uri_protocol but could not make it work by any means.
So basically my problem is handling the ?auth=SDFSEFSDFXsdf5345sdf part in my url, whenever the paypment method redirects to my site with the url mentioned above, it gets redirected to homepage instead of the function inside controller.
How can i handle this, i'm using codeIgniter 1.7 version, and couldnt find any way.
Please suggest some solution.
I think I would extend the core URI class, by creating new file at application/libraries/MY_URI.php which will extend the CI_URI class, then copy the _fetch_uri_string method and here you can add your logic if the $_SERVER['QUERY_STRING'] is present:
class MY_URI extends CI_URI
{
function __construct()
{
parent::CI_URI();
}
//Whatever this method returns the router class is using to map controller and action accordingly.
function _fetch_uri_string()
{
if(isset($_SERVER['QUERY_STRING']) AND !empty($_GET['auth']))
{
//Do your logic here, For example you can do something like if you are using REQUEST_URI
$this->uri_string = 'payment/success/'.$_GET['auth'];
return;
//You will set the uri_string to controller/action/param the CI way and process further
}
//Here goes the rest of the method that you copied
}
}
Also please NOTE that you must do security check of your URL and I hope this works for you, otherwise you can try extending the CI_Router class or other methods (experiment little bit with few methods, though the _set_routing is important). These 2 classes are responsible for the intercepted urls and mapping them to controller/action/params in CI.
I believe this thread holds the answer.
Basically add
$config['enable_query_strings'] = TRUE;
to your config.php
hope this will help you ! no need to change htaccess,just change your code.
redirect(base_url()."controller_name/function_name");
Looking at the example code in the Stripe docs:
https://stripe.com/docs/payments/checkout/set-up-a-subscription
one might conclude that you can only retrieve a checkout_session_id as a named GET parameter like this:
'success_url' => 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
After playing around with .htaccess and config settings (as in previous answers) and finally getting it to work, it suddenly dawned on me that the DEVELOPER is in control of the success_url format, not Stripe. So one can avoid all the problems with a GET parameter by specifying the success url in the normal, clean Codeigniter format, like this:
'success_url' => 'https://example.com/success/{CHECKOUT_SESSION_ID}',
In my routes file, the incoming CHECKOUT_SESSION_ID string is passed to the Subscription controller's checkout_success method with this route:
$route['success/(:any)'] = 'subscription/checkout_success/$1';
The method accepts the $checkout_session_id like this:
function checkout_success($checkout_session_id)
{
// Do something with the $checkout_session_id...
}
I'm new to Stripe Checkout but this seems to simplify the integration without breaking Codeigniter's GET processing rules.

How to access AJAX hash values in ASP.NET MVC?

I'm considering using the hash method to create static urls to content that is managed by ajax calls in a Asp.Net MVC. The proof of concept i'm working on is a profile page /user/profile where one can browse and edit different sections. You could always ask for the following url /user/profile#password to access directly to you profile page, in the change password section
However, i'm wondering if i'm not starting this the bad way, since apparently i can't access the part after the hash in any way, except by declaring a route value for the hash in global.asax. So i'm wondering if this is the right way to access this part of the url?
Am i supposed to declare a route value, or is there another way to work with hash values (a framework, javascript or mvc)?
Edited to add:
In pure javascript, i have no problem using the window.location.hash property, i'm not sure though how standard it is in today's browsers, hence the question about a javascript framework/plugin that would use it.
The thing is that the part that follows the hash (#) is never sent to the server into the HTTP request so the server has absolutely no way of reading it. So no need to waste time in searching for something that doesn't exist.
You could on the other hand tune your routes to generate links that contain the hash part so that client scripts can read it.
Send the hash value document.location.hash as a parameter to the controller action of your choice.
This can be done in the code if needed...
RedirectResult(Url.Action("profile") + "#password");
should work fine

Resources