Set 'HttpOnly' = True, In JavaScript - httponly

Can we set HttpOnly = 'True' via JavaScript?
document.cookie = name + "=" + value + expires + ";secure; path=/";
Thanks in advance.

Related

Verification of signature failed Oauth 1 Upwork API

Hi I followed the upwork developers site and the twitter oauth signature generation document and I did the following:
timestamp = int(time.time())
nonce = ''.join([str(random.randint(0, 9)) for i in range(30)])
url = 'https://www.upwork.com/api/auth/v1/info.json'
quoted_url = quote('https://www.upwork.com/api/auth/v1/info.json')
to_hash = 'GET' + '&' + url + '&'
param_string = 'oauth_consumer_key=' + UPWORK_KEY + '&oauth_nonce=' + nonce + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + str(timestamp) + '&oauth_token=' + ACCESS_TOKEN + '&oauth_verifier=' + UPWORK_VERIFIER
to_hash += quote(param_string)
hashed = hmac.new(UPWORK_SECRET + '&' + ACCESS_TOKEN_SECRET, to_hash, hashlib.sha256).hexdigest()
r = requests.get('https://www.upwork.com/api/auth/v1/info.json?oauth_consumer_key=' + UPWORK_KEY + '&oauth_signature=' + hashed + '&oauth_nonce=' + nonce + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + str(timestamp) + '&oauth_token=' + ACCESS_TOKEN + '&oauth_verifier=' + UPWORK_VERIFIER)
r.text
But when I do this, I get:
u'{"server_time":1472207775,"error":{"status":401,"code":401,"message":"Verification of signature failed."}}'
However the following works fine:
client = upwork.Client(UPWORK_KEY, UPWORK_SECRET, oauth_access_token=ACCESS_TOKEN, oauth_access_token_secret=ACCESS_TOKEN_SECRET)
client.auth.get_info()
{u'info': {u'portrait_32_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_32?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=77Ab%2BTxcps9PIYCfPIZZuDpXAiY%3D&1470127549683826', u'capacity': {u'buyer': u'yes', u'affiliate_manager': u'no', u'provider': u'yes'}, u'company_url': u'', u'has_agency': u'0', u'portrait_50_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_50?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=K6Ea0Z6QSmBGcg%2BRCQUAvrai%2FKw%3D&1470127549683826', u'portrait_100_img': u'https://odesk-prod-portraits.s3.amazonaws.com/Users:dasugovinda:PortraitUrl_100?AWSAccessKeyId=1XVAX3FNQZAFC9GJCFR2&Expires=2147483647&Signature=Dht5wFsI%2FDpDDeURkY6KefP4yvc%3D&1470127549683826', u'location': {u'city': u'Santa Clara', u'state': u'CA', u'country': u'United States'}, u'ref': u'5356164', u'profile_url': u'https://www.upwork.com/users/~01d7463c22a4e5c195'}, u'auth_user': {u'timezone': u'America/Tijuana', u'first_name': u'Govinda', u'last_name': u'Dasu', u'timezone_offset': u'-25200'}, u'server_time': u'1472209119'}
Any ideas on what I'm doing wrong?
Thanks to the answer by #Blairg23 here, I figured out the following solution:
url = 'https://www.upwork.com/api/auth/v1/info.json'
auth = OAuth1(UPWORK_KEY, UPWORK_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
r = requests.get(url, auth=auth)
r.text
Just using an already-implemented version of oauth saves you a huge headache.

Are Spring Security RememberMe tokens case-sensitive?

Generating my Spring Security 4.0.1 RememberMe token I discovered that this token generating code failed on the token decode:
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
String md5String = DatatypeConverter.printHexBinary(md5Digest.digest((emailAddress + ":" + expiryTime + ":" + password + ":" + key).getBytes()));
String token = emailAddress + ":" + expiryTime + ":" + md5String;
Encoder encoder = Base64.getEncoder();
String encodedToken = encoder.encodeToString(token.getBytes());
But that this code succeeded:
String md5String = DatatypeConverter.printHexBinary(md5Digest.digest((emailAddress + ":" + expiryTime + ":" + password + ":" + key).getBytes())).toLowerCase();
The token decoder expected the MD5 string in lowercase even though the generated MD5 string was upper.
This is the md5String as originally generated (before the toLower()):
testLogin: md5String: E34B931F1F6C02C344AB28A8103F6D23
And this is the error message that shows the lowercase expectation:
Invalid remember-me cookie: Cookie token[2] contained signature 'E34B931F1F6C02C344AB28A8103F6D23' but expected 'e34b931f1f6c02c344ab28a8103f6d23'
(I have an extractRememberMeCookie override that fakes out the cookie from the header)
Is there a better way to do this that doesn't include the toLower() hack?
The problem here was Hex.encode, it uses all lowercase chars.
https://github.com/spring-projects/spring-security/blob/master/crypto/src/main/java/org/springframework/security/crypto/codec/Hex.java

Getting all videos of a channel using youtube API

I want to get all videos of a single channel that i have its Id. The problem that I am getting only the channel informations.
this is the link that I am using:
https://gdata.youtube.com/feeds/api/users/UCdCiB_pNQpR0M_KkDG4Dz5A?v=2&alt=json&q=goal&orderby=published&max-results=10
That link is for the now-retired V2 API, so it will not return any data. Instead, you'll want to use V3 of the API. The first thing you'll need to do is register for an API key -- you can do this by creating a project at console.developers.google.com, setting the YouTube data API to "on," and creating a public access key.
Since you have your user channel ID already, you can jump right into getting the videos from it; note, however, that if you ever don't know the channel ID, you can get it this way:
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername={username}&key={YOUR_API_KEY}
With the channel ID, you can get all the videos from the channel with the search endpoint, like this:
https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId={channel id here}&maxResults=25&key={YOUR_API_KEY}
In this case, ordering by date is the same as the old V2 parameter for ordering by "published."
There are also a lot of other parameters you can use to retrieve videos while searching a channel; see https://developers.google.com/youtube/v3/docs/search/list for more details.
I thought I would share my final result using JavaScript. It uses the Google YouTube API key and UserName to get the channel ID, then pulls the videos and displays in a list to a given div tag.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>YouTube Channel Listing</title>
<script type="text/javascript">
function getJSONData(yourUrl) {
var Httpreq = new XMLHttpRequest();
try {
Httpreq.open("GET", yourUrl, false);
Httpreq.send(null);
} catch (ex) {
alert(ex.message);
}
return Httpreq.responseText;
}
function showVideoList(username, writediv, maxnumbervideos, apikey) {
try {
document.getElementById(writediv).innerHTML = "";
var keyinfo = JSON.parse(getJSONData("https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=" + username + "&key=" + apikey));
var userid = keyinfo.items[0].id;
var channeltitle = keyinfo.items[0].snippet.title;
var channeldescription = keyinfo.items[0].snippet.description;
var channelthumbnail = keyinfo.items[0].snippet.thumbnails.default.url; // default, medium or high
//channel header
document.getElementById(writediv).innerHTML += "<div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/user/" + username + "' target='_blank'>"
+ "<img src='" + channelthumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + channeltitle + "' title='" + channeltitle + "' /></a>"
+ "<div style='width:100%;text-align:center;'><h1><a href='https://www.youtube.com/user/" + username + "' target='_blank'>" + channeltitle + "</a></h1>" + channeldescription + "</div>"
+ "</div>";
var videoinfo = JSON.parse(getJSONData("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + userid + "&maxResults=" + maxnumbervideos + "&key=" + apikey));
var videos = videoinfo.items;
var videocount = videoinfo.pageInfo.totalResults;
// video listing
for (var i = 0; i < videos.length; i++) {
var videoid = videos[i].id.videoId;
var videotitle = videos[i].snippet.title;
var videodescription = videos[i].snippet.description;
var videodate = videos[i].snippet.publishedAt; // date time published
var videothumbnail = videos[i].snippet.thumbnails.default.url; // default, medium or high
document.getElementById(writediv).innerHTML += "<hr /><div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>"
+ "<img src='" + videothumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + videotitle + "' title='" + videotitle + "' /></a>"
+ "<h3><a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>" + videotitle + "</a></h3>" + videodescription + ""
+ "</div>";
}
} catch (ex) {
alert(ex.message);
}
}
</script>
</head>
<body>
<div id="videos"></div>
<script type="text/javascript">
showVideoList("USER_NAME", "videos", 25, "YOUR_API_KEY");
</script>
</body>
</html>
ADDITION - I also wrote a function to handle if you are using a channel ID instead of a UserName based account.
Here is that code:
function showVideoListChannel(channelid, writediv, maxnumbervideos, apikey) {
try {
document.getElementById(writediv).innerHTML = "";
var vid = getJSONData("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelid + "&maxResults=" + (maxnumbervideos + 1) + "&key=" + apikey);
var videoinfo = JSON.parse(vid);
var videos = videoinfo.items;
var videocount = videoinfo.pageInfo.totalResults;
var content = "<div style='height:600px;overflow-y:auto;'>";
for (var i = 0; i < videos.length - 1; i++) {
var videoid = videos[i].id.videoId;
var videotitle = videos[i].snippet.title;
var videodescription = videos[i].snippet.description;
var videodate = videos[i].snippet.publishedAt; // date time published
var newdate = new Date(Date.parse((videodate + " (ISO 8601)").replace(/ *\(.*\)/, "")));
var min = newdate.getMinutes();
if (min < 10) {
min = "0" + min;
}
if (newdate.getHours() > 12) {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + (newdate.getHours() - 12) + ":" + min + " PM";
} else if (newdate.getHours() == 12) {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + newdate.getHours() + ":" + min + " PM";
} else {
newdate = newdate.getMonth() + 1 + "/" + newdate.getDate() + "/" + newdate.getFullYear() + " " + newdate.getHours() + ":" + min + " AM";
}
var videothumbnail = videos[i].snippet.thumbnails.default.url; // default, medium or high
content += "<hr /><div style='width:100%;min-height:90px;'>"
+ "<a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>"
+ "<img src='" + videothumbnail + "' style='border:none;float:left;margin-right:10px;' alt='" + videotitle + "' title='" + videotitle + "' /></a>"
+ "<h3><a href='https://www.youtube.com/watch?v=" + videoid + "' target='_blank'>" + videotitle + "</a></h3>" + videodescription + "<br />"
+ "<span style='color:#738AAD;font-size:Small;'>" + newdate + "</span>"
+ "</div>";
}
content += "</div>";
document.getElementById(writediv).innerHTML = content;
} catch (ex) {
alert(ex.message);
}
}
It is very easy method to get channel videos using your channel API key:
Step 1: You must have an YouTube account.
Step 2: Create your YouTube channel API key
Step 3: Create project console.developers.google.com,
<?php
$API_key = 'Your API key'; //my API key dei;
$channelID = 'Your Channel ID'; //my channel ID
$maxResults = 5;
$video_list =
json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?
order=date&part=snippet&channelId='.$channelID.
'&maxResults='.$maxResults.'&key='.$API_key.''));
?>
Example : https://www.googleapis.com/youtube/v3/channelspart=snippet&forUsername=
{username}&key={YOUR_API_KEY}
Here is the way to get all videos with only 2 quotas using YouTube Data API (v3)
First of all do a list on channels with part=contentDetails (1 quota) :
https://youtube.googleapis.com/youtube/v3/channels?part=contentDetails&id=[CHANNEL_ID]&key=[YOUR_API_KEY]
You will get this result :
{
...
"items": [
{
...
"contentDetails": {
"relatedPlaylists": {
"likes": "",
"uploads": "UPLOADS_PLAYLIST_ID"
}
}
}
]
}
Then take UPLOADS_PLAYLIST_ID and do a list on playlistItems with part=contentDetails (1 quota):
https://youtube.googleapis.com/youtube/v3/playlistItems?part=contentDetails&playlistId=[UPLOADS_PLAYLIST_ID]&key=[YOUR_API_KEY]
You will get this result:
{
...
"items": [
{
...
"contentDetails": {
"videoId": "VIDEO_ID",
"videoPublishedAt": "2022-10-27T16:00:08Z"
}
},
...
],
"pageInfo": {
"totalResults": 5648,
"resultsPerPage": 5
}
}
You got the list of the videos under items
You can of course change the size of this list by adding maxResults=50 (max value is 50)

YQL Weather Forecast

I currently have a piece of code that only displays the current weather in a given zipcode. Can someone help me with getting a 5 day forecast. Here is what I have so far.
var loc = zipcode;
var u = 'f';
var query = "SELECT item.condition FROM weather.forecast WHERE location='" + loc + "' AND u='" + u + "'";
var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
var url = '<http://query.yahooapis.com/v1/public/yql?q=>' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;
window['wxCallback'] = function(data) {
var info = data.query.results.channel.item.condition;
$('#wxIcon').css({
backgroundPosition: '-' + (61 * info.code) + 'px 0'
}).attr({
title: info.text
});
$('#wxIcon2').append('<img src="<http://l.yimg.com/a/i/us/we/52/>' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
$('#wxTemp').html(info.temp + '°' + (u.toUpperCase()));
};
$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
jsonpCallback: 'wxCallback'
});
and here is the YQL console. LINK
I found forecast but I don't know how to implement it. I'm pretty new when it comes to YQL... Thanks!
I have posted a complete sample here - https://gist.github.com/mvark/5231461
Check the Yahoo Weather API documentation for more details about the API

Twitter oauth Request Token Response code 401

I am working on a twitter oauth login. However, when I do the request_token, the very first step, the response code always return 401 Unauthorized.
I have searched a lot for a week, but I cannot find the solution, please help.
Here is my connection:
URL url = new URL("https://api.twitter.com/oauth/request_token");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Host","api.twitter.com");
conn.setRequestProperty("Authorization", data);
conn.setRequestMethod("POST");
conn.connect();
For my data:
String data = "OAuth oauth_nonce=\"" + oauth_nonce
+ "\", oauth_callback=\"" + oauth_callback
+ "\", oauth_signature_method=\"" + oauth_signature_method
+ "\", oauth_timestamp=\"" + oauth_timestamp
+ "\", oauth_consumer_key=\"" + oauth_consumer_key
+ "\", oauth_signature=\"" + oauth_signature
+ "\", oauth_version=\"" + oauth_version + "\"";
Also, I am sure that my signature is right, because I used the parameter of twitter example, I can calculate the same result as its example, so I think my method is right.
Here is my calculation:
String oauth_para = "oauth_callback=" + oauth_callback
+ "&oauth_consumer_key=" + oauth_consumer_key
+ "&oauth_nonce=" + oauth_nonce
+ "&oauth_signature_method=" + oauth_signature_method
+ "&oauth_timestamp=" + oauth_timestamp
+ "&oauth_version=" + oauth_version;
String signingRequests = "POST&" + requestToken + "&" + URLEncoder.encode(oauth_para, "UTF-8");
String key = oauth_consumer_secret + "&";
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = null;
try {
mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
}
catch(Exception e) {
System.err.println("Error: " + e);
}
byte[] rawHmac = mac.doFinal(signingRequests.getBytes());
String oauth_signature = Base64.encodeBytes(rawHmac);
oauth_signature = URLEncoder.encode(oauth_signature);
I understand that the nonce and timestamp should be random and unique. So, my method is like that:
StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
StringBuffer sb = new StringBuffer();
Random r = new Random();
int range = buffer.length();
for (int i = 0; i < 43;i ++) {
sb.append(buffer.charAt(r.nextInt(range)));
}
long epoch = System.currentTimeMillis() / 1000;
String oauth_nonce = sb.toString();
Can somebody help me?
P.S: I have also removed my apps, and then create a new one. The result also is the same. Also, the apps is write and read already.
hey,,, I was getting the same problem 1 min ago, but I figured this out. My problem, at least, was that in the configuration of the application(inside twitter), my application type was Client, when should be Browser! So I changed to Browser, put a callback URL and worked fine!!

Resources