Set cookie with ramaze framework? - ruby

Before
request.cookies[:user_id] = 1
After:(get cookie)
request.cookies[:user_id]
return nil

Related

how to send https/http request with network credentials in go

in c#
var uri = new Uri("https://demo.com/");
var encoding = new UTF8Encoding();
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Credentials = new NetworkCredential(utility.commonkey, utility.commonsecrerkey);
request.ContentType = "application/json";
request.Accept = "application/vnd.demo+json;version=3;";
request.ContentLength = encoding.GetByteCount(json);
request.Headers.Add("data", json);
HttpWebResponse response = null;
and in go i can add only add these
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Basic sdfsfscefewfewfew")
req.Header.Set("Accept", "application/vnd.demo+json; version=3;")
here in go the challenge is how to add network credentials in go
From what I see in the C# docs what you're referring at as keys, could only be username and password. You could use the analogue http.Request's method to set username and password for basic auth.
// username has the same value as utility.commonkey
// password is the corresponding password in plain text
req.SetBasicAuth(username, password);
Don't forget to remove the following line from your Go code as well
req.Header.Set("Authorization", "Basic sdfsfscefewfewfew")

How can I check for a response cookie in Asp.net Core MVC (aka Asp.Net 5 RC1)?

I'm converting a web forms application to asp.net core mvc. In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http). In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)
for(int i = 0; i < cookies.Count; i++) {
if(cookies[i].Name == cookieName) {
return cookies[i];
}
}
But the interface for accessing response cookies in asp.net core mvc looks like this:
Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties. But there has gotta be some way to do it?
In an action method I tried setting two cookies on the response object and then immediately trying to access them. But intellisense doesn't show any methods, properties or indexers that would allow me to access them:
For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.
Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not. So given this interface, how do I check for the existence of a response cookie and get it's properties? I've thought about trying to hack in via the response headers collection but that seems pretty lame.
There is an extension method available in Microsoft.AspNetCore.Http.Extensions called GetTypedHeaders(). This can be called on HttpContext.Response to read Set-Cookie headers. For example in middleware perhaps we want to intercept a Set-Cookie response header and replace it:
public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.OnStarting(state =>
{
var context = (HttpContext)state;
var setCookieHeaders = context.Response.GetTypedHeaders().SetCookie;
// We assume only one cookie is found. You could loop over multiple matches instead.
// setCookieHeaders may be null if response doesn't contain set-cookie headers
var cookie = setCookieHeaders?.FirstOrDefault(x => x.Name == "mycookiename");
if (cookie == null)
{
return Task.CompletedTask;
}
var opts = new CookieOptions
{
HttpOnly = true,
Expires = DateTimeOffset.Now.AddHours(12),
SameSite = SameSiteMode.Lax,
Secure = true
};
context.Response.Cookies.Delete(cookie.Name.Value);
context.Response.Cookies.Append(cookie.Name.Value, "mynewcookievalue", opts);
return Task.CompletedTask;
}, httpContext);
await _next(httpContext);
}
Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers.Values)
foreach (var header in headers)
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
return null;
}
There is an obvious problem with Shaun's answer: it will match any HTTP-header having matching value. The idea should be to match only cookies.
A minor change like this should do the trick:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
string header = headers.Value;
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
return null;
}
Now the checking for a cookie name will target only actual cookie-headers.
You can use this function to get full information about the cookie set value
private SetCookieHeaderValue GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
var cookieSetHeader = response.GetTypedHeaders().SetCookie;
if (cookieSetHeader != null)
{
var setCookie = cookieSetHeader.FirstOrDefault(x => x.Name == cookieName);
return setCookie;
}
return null;
}
In my case I had to get only value of auth= and don't care about other values, but you can easy rewrite code to get dict of cookie values.
I wrote this extension for HttpResponseMessage, in order to avoid work with index and substring, I separate string to array and then cast it to dictionary
internal static string GetCookieValueFromResponse(this HttpResponseMessage httpResponse, string cookieName)
{
foreach (var cookieStr in httpResponse.Headers.GetValues("Set-Cookie"))
{
if(string.IsNullOrEmpty(cookieStr))
continue;
var array = cookieStr.Split(';')
.Where(x => x.Contains('=')).Select(x => x.Trim());
var dict = array.Select(item => item.Split(new[] {'='}, 2)).ToDictionary(s => s[0], s => s[1]);
if (dict.ContainsKey(cookieName))
return dict[cookieName];
}
return null;
}
You can get the cookie string value from the response using this method. In this case, I'm using this logic in a CookieService, that is the reason you will see that I'm using the _contextAccessor. Notice that in this case, I'm returning null if the value of the cookie is empty. (This is optional)
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
If you are looking for a solution that gets the cookie from the response or the request in that order then you can use this.
private string GetCookieString(string cookieName)
{
return GetCartCookieFromResponse(cookieName) ?? GetCartCookieFromRequest(cookieName) ?? "";
}
private string GetCookieFromRequest(string cookieName)
{
return _contextAccessor.HttpContext.Request.Cookies.ContainsKey(cookieName) ? _contextAccessor.HttpContext.Request.Cookies[cookieName] : null;
}
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
The snippet seems to work for me. The result for me (derived from Shaun and Ron) looks like:
public static string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
// inspect the cookies in HttpResponse.
string match = $"{cookieName}=";
var p1 = match.Length;
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
foreach (string header in headers.Value)
{
if (header.StartsWith(match) && header.Length > p1 && header[p1] != ';')
{
var p2 = header.IndexOf(';', p1);
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
}
return null;
}
In cases where multiple "Set-Cookie" headers exists the last one should be used:
private string GetCookieValueFromResponse(Microsoft.AspNetCore.Http.HttpResponse response, string cookieName)
{
var value = string.Empty;
foreach (var header in response.Headers["Set-Cookie"])
{
if (!header.Trim().StartsWith($"{cookieName}="))
continue;
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
value = header.Substring(p1 + 1, p2 - p1 - 1);
}
return value;
}

ASP.NET web API identity External login redirect

I'm using ASP.net webAPI identity for Facebook login , I have angularjs application
when I call
MainURL + 'api/Account/ExternalLogins?returnUrl=%2F&generateState=true'
I don't want to return to web API page , instead I want Facebook to redirect me back to my angularJS app so I did this :
[AllowAnonymous]
[Route("ExternalLogins")]
public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
{
IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
string state;
if (generateState)
{
const int strengthInBits = 256;
state = RandomOAuthStateGenerator.Generate(strengthInBits);
}
else
{
state = null;
}
foreach (AuthenticationDescription description in descriptions)
{
ExternalLoginViewModel login = new ExternalLoginViewModel
{
Name = description.Caption,
Url = Url.Route("ExternalLogin", new
{
provider = description.AuthenticationType,
response_type = "token",
client_id = Startup.PublicClientId,
redirect_uri = new Uri("http://localhost:6263/com.html").AbsoluteUri,
// redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
state = state
}),
State = state
};
logins.Add(login);
}
return logins;
}
redirect_uri = new Uri("http://localhost:6263/com.html").AbsoluteUri,
but browser give me an error
response from service is :
/api/Account/ExternalLogin?provider=Facebook&response_type=token&client_id=self&redirect_uri=localhost%3A6263%2Fcom.html&state=j0y0wF0yhvA_tzqbJo0GijCecqfbNWT0vLQiXxcHDqM1
Im sure this is late. Take a look at your url, it has a double slash (//)

API to create cookie for FireFox

I want to write an application which will create cookies for firefox.
I want to create Client cookies so that firefox will send cookie content in HTTP request.
Similar to the win32 API InternetSetCookie()
Can you please guide on this ?
If you can point me to some code snippet or help, I will try to figure out from that.
This cookie needs to go to SQLITE database, but it seems from old questions that this database get locked if firefox is running. This locking is done in FF 3.5
Just want to confirm if this is the case with FF9 or do we have any API ?
Regards
On Firefox, you can write an add-on to achieve that. Take a look at the source code of the following add-ons. They provide features such as adding, deleting, editing cookies while Firefox is running. It seems they all work with Firefox 9.0.1 (latest stable).
Cookie Manager+
Advanced Cookie Manager
Add N Edit Cookie
Edit Cookie
Edit:
I am posting some cookie management code from the Evernote plugin's MozillaCookieManagerImpl.js file. I think the code speaks for itself. Have a look below. It shows how to access cookies, set, get and remove them etc.
Accessing Mozilla's Cookie Management Interface
Evernote.MozillaCookieManagerImpl = function MozillaCookieManagerImpl() {
};
Evernote.inherit(Evernote.MozillaCookieManagerImpl,
Evernote.CookieManagerImpl, true);
Evernote.MozillaCookieManagerImpl.isResponsibleFor = function(navigator) {
var ua = navigator.userAgent.toLowerCase();
return (ua.indexOf("firefox") >= 0 || ua.indexOf("thunderbird") >= 0 || ua
.indexOf("shredder") >= 0);
};
Evernote.MozillaCookieManagerImpl.prototype.manager = null;
Evernote.MozillaCookieManagerImpl.prototype._ios = null;
Evernote.MozillaCookieManagerImpl.prototype._cookieSrv = null;
Evernote.MozillaCookieManagerImpl.prototype._cookieManagerSrv = null;
Evernote.MozillaCookieManagerImpl.prototype.getIOService = function() {
if (this._ios == null) {
this._ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
}
return this._ios;
};
Evernote.MozillaCookieManagerImpl.prototype.getCookieService = function(
force) {
if (this._cookieSrv == null || force) {
this._cookieSrv = Components.classes["#mozilla.org/cookieService;1"]
.getService(Components.interfaces.nsICookieService);
}
return this._cookieSrv;
};
Evernote.MozillaCookieManagerImpl.prototype.getCookieManagerService = function(
force) {
if (this._cookieManagerSrv == null || force) {
this._cookieManagerSrv = Components.classes["#mozilla.org/cookiemanager;1"]
.getService(Components.interfaces.nsICookieManager);
}
return this._cookieManagerSrv;
};
Get Cookie
Evernote.MozillaCookieManagerImpl.prototype.get = function(name, url) {
var uri = this.getIOService().newURI(url, null, null);
var cookieMgr = this.getCookieManagerService();
if (cookieMgr) {
for ( var e = cookieMgr.enumerator; e.hasMoreElements();) {
var cookie = e.getNext().QueryInterface(Components.interfaces.nsICookie);
if (cookie && cookie.host == uri.host && cookie.name == name) {
return new Evernote.Cookie(cookie);
}
}
}
return null;
};
Set Cookie
Evernote.MozillaCookieManagerImpl.prototype.set = function(cookie, url) {
var uri = (typeof url == 'string') ? this.getIOService().newURI(url, null,
null) : null;
if (cookie instanceof Evernote.Cookie && typeof cookie.name == 'string'
&& cookie.name.length > 0) {
this.getCookieService().setCookieString(uri, null,
(cookie.name + "=" + cookie.value + ";"), null);
}
};
Removie Cookie
Evernote.MozillaCookieManagerImpl.prototype.remove = function(name, url) {
var cookieMgr = this.getCookieManagerService();
var urlParts = url.split("://", 2);
var domain = (urlParts.length == 2) ? urlParts[1] : urlParts[0];
urlParts = domain.split("/", 2);
var path = (urlParts.length == 2) ? urlParts[1] : null;
cookieMgr.remove(domain, name, path, false);
};

MVC 3 Globalization - Australian Currency

I have problem with austalian culture. I set this by the code:
string id = "en-AU";
string ret = Request.ServerVariables["HTTP_REFERER"] ?? "/";
string culture = CultureHelper.GetValidCulture(id);
HttpCookie cookie = Request.Cookies["_culture"];
if (cookie != null)
cookie.Value = culture;
else {
cookie = new HttpCookie("_culture");
cookie.HttpOnly = false;
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cookie);
then I want to display a price in AUD:
#String.Format("{0:C}", item.Price
but I get e.g $55.00. Why ?
In your code you are not actually applying the culture anywhere. Something like:
CultureInfo userCulture = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = userCulture;
Thread.CurrentThread.CurrentUICulture = userCulture;

Resources