Get details of the user that invoked the JMX operation - java

I am trying to get the details of the user that invoked the JMX operation for logging purpose. I have tried below code. But that does not seem to work as it returns blank each time. What am I dooing wrong. Or is there any better way of doing this?
private String getUserName() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject != null) {
Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
JMXPrincipal principal = principals.iterator().next();
return principal.getName();
}
return "";
}

The above code did work.
What I did (for all that might be wondering like I was):
1) Added following JVM args
-Dcom.sun.management.jmxremote.ssl=**false**
-Dcom.sun.management.jmxremote.authenticate=**true**
-Dcom.sun.management.jmxremote.access.file=**PATH-TO jmxremote.access**
-Dcom.sun.management.jmxremote.password.file=**PATH-TO jmxremote.password**
2) Added following entries in the jmxremote.access file
admin readwrite \ create javax.management.monitor.*,javax.management.timer.* \ unregister
user readonly
3) Added below lines in the jmxremote.password file
admin adminPassword
user userPassword
4) Added the below code in my MBean java file and called the method getUserName() inside the JMXoperation
private String getUserName() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
if (subject != null) {
Set<JMXPrincipal> principals = subject.getPrincipals(JMXPrincipal.class);
JMXPrincipal principal = principals.iterator().next();
return principal.getName();
}
return "";
}
When I run it in debug mode, I am seeing the user that invoked the JMXOperation.

Related

Can't get Bcrypt.checkpw to verify password in java play framework

I have had an application written a few years ago and upgraded some of the jars but not the bcrypt
It is written in java using the play framework.
BCrypt is provided from "org.mindrot" % "jbcrypt" % "0.3m"
I use BCrypt.checkpw(password.trim(), user.getPassword())
where password is the captured plaintext and user.getPassword is the stored hash in mysql stored as char(60).
I hash passwords using BCrypt.hashpw(password.trim(), BCrypt.gensalt(15))
checkpw works interestingly with original passwords but any new ones it fails and always responds false
One interesting observation is I had a password in my dev database which I know is 'password'
Its hash looks like this
$2a$10$UvKgjjT./SuMlD6gsoyD0e2lBcOwFtL/mfGmneTou/lrU1R/ZwMLK
vs
a new one I just created and set its password to 'password'
and its hash looks like this
$2a$10$rNJzD52/muHMkBF1Co9XF.VkQNRHQ3HCW.DYzke7jnY424voZwyq6
I know they should differ but the format looks different somewhat?
Please any help appreciated as this makes no sense as nothing has changed but new users cannot register
Code:
The password is set within my User class
public void setPassword(String password) {
play.Logger.debug("setPassword |" + password.trim() +"|");
this.password = BCrypt.hashpw(password.trim(), BCrypt.gensalt(15));
}
I call this within my register method
public Result registeruser() {
JsonNode json = request().body().asJson();
.
.
.
if (json.has("password")) {
user.setPassword(json.findPath("password").textValue())
}
.
.
.
user.save()
.
.
.
}
I then have the following Authenticate method
public static Users authenticate(String email, String password) {
play.Logger.debug("email is " + email);
play.Logger.debug("authenticate password entered |" + password.trim() +"|");
Users user = Users.find.query().where().eq("email", email).findOne();
if (user != null) {
play.Logger.debug("password hash from db |" + user.getPassword() +"|");
Boolean checkPassword = BCrypt.checkpw(password.trim(), user.getPassword());
play.Logger.debug("checkPassword " + checkPassword);
if (checkPassword) {
return user;
} else {
return null;
}
}
}
Relevant debug output from running
In setPassword part
[debug] application - setPassword |password|
in authenticate part
[debug] application - authenticate password entered |password|
[debug] application - password hash from db |$2a$10$EiuMUWfbCoO.A1GxKk9YeOhqtK0bn4O8Y/W9U/7bEN/CSObOm6jUa|
[debug] application - checkPassword false
The reason for this was in setPassword was not the right place to do the hashing and I kept getting a blank hashpw. This used to work in the earlier version of play but clearly not anymore
I moved it to a #PrePersist method as follows:
#PrePersist
public void hashPassword(){
play.Logger.debug("hashPassword |" + this.password +"|");
String hashed = BCrypt.hashpw(this.password, BCrypt.gensalt(15));
play.Logger.debug("hashed " + hashed);
this.password = hashed;
}
Problem was solved

Rampart: how to use a JKS certificate without any password

I have the following situation:
a JKS keystore file without password, containing a private key ALSO unprotected. I've tried to configure Rampart in order to use this keystore, but i keep getting the following error:
Caused by: org.apache.rampart.RampartException: No password supplied by the callback handler for the user : "username"
my password callback handler is as follows:
public class PWCBHandlerCertificate implements CallbackHandler {
public void handle( Callback[] callbacks ) throws IOException, UnsupportedCallbackException {
for ( int i = 0; i < callbacks.length; i++ ) {
WSPasswordCallback pwcb = (WSPasswordCallback) callbacks[i];
String id = pwcb.getIdentifer();
int usage = pwcb.getUsage();
if ( usage == WSPasswordCallback.DECRYPT || usage == WSPasswordCallback.SIGNATURE ) {
Element temp = pwcb.getCustomToken();
// used to retrieve password for private key
if ( "username".equals( id ) ) {
pwcb.setPassword( "" );
}
}
}
}
}
what am i missing?
Thanks in advance
It turned out that rampart 1.5.2 (i don't know about newer versions, i must keep this one...) forces the certificate to have a valid password (not null and not empty).
I downloaded the source for rampart 1.5.2, and i found the following code inside the class BindingBuilder.java (package org.apache.rampart.builder):
WSPasswordCallback[] cb = { new WSPasswordCallback(user,
WSPasswordCallback.SIGNATURE) };
try {
handler.handle(cb);
if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword())) {
password = cb[0].getPassword();
log.debug("Password : " + password);
} else {
//If there's no password then throw an exception
throw new RampartException("noPasswordForUser",
new String[]{user});
}
}
The problem resides here:
if(cb[0].getPassword() != null && !"".equals(cb[0].getPassword()))
The exception is thrown if the password is received null or empty from the callback. In order to avoid this problem i had to comment out a part of the code like this:
if(cb[0].getPassword() != null /*&& !"".equals(cb[0].getPassword())*/)
I recompiled the class and replaced the resulting .class inside rampart-core-1.5.2.jar
The exception disappeared, i can now successfully use the passwordless certificate.
I hope it helps.

Direct download from Google Drive using Google Drive API

My desktop application, written in java, tries to download public files from Google Drive. As i found out, it can be implemented by using file's webContentLink (it's for ability to download public files without user authorization).
So, the code below works with small files:
String webContentLink = aFile.getWebContentLink();
InputStream in = new URL(webContentLink).openStream();
But it doesn't work on big files, because in this case file can't be downloaded directly via webContentLink without user confirmation with google virus scan warning. See an example: web content link.
So my question is how to get content of a public file from Google Drive without user authorization?
Update December 8th, 2015
According to Google Support using the
googledrive.com/host/ID
method will be turned off on Aug 31st, 2016.
I just ran into this issue.
The trick is to treat your Google Drive folder like a web host.
Update April 1st, 2015
Google Drive has changed and there's a simple way to direct link to your drive. I left my previous answers below for reference but to here's an updated answer.
Create a Public folder in Google Drive.
Share this drive publicly.
Get your Folder UUID from the address bar when you're in that folder
Put that UUID in this URL
https://googledrive.com/host/<folder UUID>/
Add the file name to where your file is located.
https://googledrive.com/host/<folder UUID>/<file name>
Which is intended functionality by Google
new Google Drive Link.
All you have to do is simple get the host URL for a publicly shared drive folder. To do this, you can upload a plain HTML file and preview it in Google Drive to find your host URL.
Here are the steps:
Create a folder in Google Drive.
Share this drive publicly.
Upload a simple HTML file. Add any additional files (subfolders ok)
Open and "preview" the HTML file in Google Drive
Get the URL address for this folder
Create a direct link URL from your URL folder base
This URL should allow direct downloads of your large files.
[edit]
I forgot to add. If you use subfolders to organize your files, you simple use the folder name as you would expect in a URL hierarchy.
https://googledrive.com/host/<your public folders id string>/images/my-image.png
What I was looking to do
I created a custom Debian image with Virtual Box for Vagrant. I wanted to share this ".box" file with colleagues so they could put the direct link into their Vagrantfile.
In the end, I needed a direct link to the actual file.
Google Drive problem
If you set the file permissions to be publicly available and create/generate a direct access link by using something like the gdocs2direct tool or just crafting the link yourself:
https://docs.google.com/uc?export=download&id=<your file id>
You will get a cookie based verification code and prompt "Google could not scan this file" prompt, which won't work for things such as wget or Vagrantfile configs.
The code that it generates is a simple code that appends GET query variable ...&confirm=### to the string, but it's per user specific, so it's not like you can copy/paste that query variable for others.
But if you use the above "Web page hosting" method, you can get around that prompt.
I hope that helps!
If you face the "This file cannot be checked for viruses" intermezzo page, the download is not that easy.
You essentially need to first download the normal download link, which however redirects you to the "Download anyway" page. You need to store cookies from this first request, find out the link pointed to by the "Download anyway" button, and then use this link to download the file, but reusing the cookies you got from the first request.
Here's a bash variant of the download process using CURL:
curl -c /tmp/cookies "https://drive.google.com/uc?export=download&id=DOCUMENT_ID" > /tmp/intermezzo.html
curl -L -b /tmp/cookies "https://drive.google.com$(cat /tmp/intermezzo.html | grep -Po 'uc-download-link" [^>]* href="\K[^"]*' | sed 's/\&/\&/g')" > FINAL_DOWNLOADED_FILENAME
Notes:
this procedure will probably stop working after some Google changes
the grep command uses Perl syntax (-P) and the \K "operator" which essentially means "do not include anything preceding \K to the matched result. I don't know which version of grep introduced these options, but ancient or non-Ubuntu versions probably don't have it
a Java solution would be more or less the same, just take a HTTPS library which can handle cookies, and some nice text-parsing library
I know this is an old question but I could not find a solution to this problem after some research, so I am sharing what worked for me.
I have written this C# code for one of my projects. It can bypass the scan virus warning programmatically. The code can probably be converted to Java.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
public class FileDownloader : IDisposable
{
private const string GOOGLE_DRIVE_DOMAIN = "drive.google.com";
private const string GOOGLE_DRIVE_DOMAIN2 = "https://drive.google.com";
// In the worst case, it is necessary to send 3 download requests to the Drive address
// 1. an NID cookie is returned instead of a download_warning cookie
// 2. download_warning cookie returned
// 3. the actual file is downloaded
private const int GOOGLE_DRIVE_MAX_DOWNLOAD_ATTEMPT = 3;
public delegate void DownloadProgressChangedEventHandler( object sender, DownloadProgress progress );
// Custom download progress reporting (needed for Google Drive)
public class DownloadProgress
{
public long BytesReceived, TotalBytesToReceive;
public object UserState;
public int ProgressPercentage
{
get
{
if( TotalBytesToReceive > 0L )
return (int) ( ( (double) BytesReceived / TotalBytesToReceive ) * 100 );
return 0;
}
}
}
// Web client that preserves cookies (needed for Google Drive)
private class CookieAwareWebClient : WebClient
{
private class CookieContainer
{
private readonly Dictionary<string, string> cookies = new Dictionary<string, string>();
public string this[Uri address]
{
get
{
string cookie;
if( cookies.TryGetValue( address.Host, out cookie ) )
return cookie;
return null;
}
set
{
cookies[address.Host] = value;
}
}
}
private readonly CookieContainer cookies = new CookieContainer();
public DownloadProgress ContentRangeTarget;
protected override WebRequest GetWebRequest( Uri address )
{
WebRequest request = base.GetWebRequest( address );
if( request is HttpWebRequest )
{
string cookie = cookies[address];
if( cookie != null )
( (HttpWebRequest) request ).Headers.Set( "cookie", cookie );
if( ContentRangeTarget != null )
( (HttpWebRequest) request ).AddRange( 0 );
}
return request;
}
protected override WebResponse GetWebResponse( WebRequest request, IAsyncResult result )
{
return ProcessResponse( base.GetWebResponse( request, result ) );
}
protected override WebResponse GetWebResponse( WebRequest request )
{
return ProcessResponse( base.GetWebResponse( request ) );
}
private WebResponse ProcessResponse( WebResponse response )
{
string[] cookies = response.Headers.GetValues( "Set-Cookie" );
if( cookies != null && cookies.Length > 0 )
{
int length = 0;
for( int i = 0; i < cookies.Length; i++ )
length += cookies[i].Length;
StringBuilder cookie = new StringBuilder( length );
for( int i = 0; i < cookies.Length; i++ )
cookie.Append( cookies[i] );
this.cookies[response.ResponseUri] = cookie.ToString();
}
if( ContentRangeTarget != null )
{
string[] rangeLengthHeader = response.Headers.GetValues( "Content-Range" );
if( rangeLengthHeader != null && rangeLengthHeader.Length > 0 )
{
int splitIndex = rangeLengthHeader[0].LastIndexOf( '/' );
if( splitIndex >= 0 && splitIndex < rangeLengthHeader[0].Length - 1 )
{
long length;
if( long.TryParse( rangeLengthHeader[0].Substring( splitIndex + 1 ), out length ) )
ContentRangeTarget.TotalBytesToReceive = length;
}
}
}
return response;
}
}
private readonly CookieAwareWebClient webClient;
private readonly DownloadProgress downloadProgress;
private Uri downloadAddress;
private string downloadPath;
private bool asyncDownload;
private object userToken;
private bool downloadingDriveFile;
private int driveDownloadAttempt;
public event DownloadProgressChangedEventHandler DownloadProgressChanged;
public event AsyncCompletedEventHandler DownloadFileCompleted;
public FileDownloader()
{
webClient = new CookieAwareWebClient();
webClient.DownloadProgressChanged += DownloadProgressChangedCallback;
webClient.DownloadFileCompleted += DownloadFileCompletedCallback;
downloadProgress = new DownloadProgress();
}
public void DownloadFile( string address, string fileName )
{
DownloadFile( address, fileName, false, null );
}
public void DownloadFileAsync( string address, string fileName, object userToken = null )
{
DownloadFile( address, fileName, true, userToken );
}
private void DownloadFile( string address, string fileName, bool asyncDownload, object userToken )
{
downloadingDriveFile = address.StartsWith( GOOGLE_DRIVE_DOMAIN ) || address.StartsWith( GOOGLE_DRIVE_DOMAIN2 );
if( downloadingDriveFile )
{
address = GetGoogleDriveDownloadAddress( address );
driveDownloadAttempt = 1;
webClient.ContentRangeTarget = downloadProgress;
}
else
webClient.ContentRangeTarget = null;
downloadAddress = new Uri( address );
downloadPath = fileName;
downloadProgress.TotalBytesToReceive = -1L;
downloadProgress.UserState = userToken;
this.asyncDownload = asyncDownload;
this.userToken = userToken;
DownloadFileInternal();
}
private void DownloadFileInternal()
{
if( !asyncDownload )
{
webClient.DownloadFile( downloadAddress, downloadPath );
// This callback isn't triggered for synchronous downloads, manually trigger it
DownloadFileCompletedCallback( webClient, new AsyncCompletedEventArgs( null, false, null ) );
}
else if( userToken == null )
webClient.DownloadFileAsync( downloadAddress, downloadPath );
else
webClient.DownloadFileAsync( downloadAddress, downloadPath, userToken );
}
private void DownloadProgressChangedCallback( object sender, DownloadProgressChangedEventArgs e )
{
if( DownloadProgressChanged != null )
{
downloadProgress.BytesReceived = e.BytesReceived;
if( e.TotalBytesToReceive > 0L )
downloadProgress.TotalBytesToReceive = e.TotalBytesToReceive;
DownloadProgressChanged( this, downloadProgress );
}
}
private void DownloadFileCompletedCallback( object sender, AsyncCompletedEventArgs e )
{
if( !downloadingDriveFile )
{
if( DownloadFileCompleted != null )
DownloadFileCompleted( this, e );
}
else
{
if( driveDownloadAttempt < GOOGLE_DRIVE_MAX_DOWNLOAD_ATTEMPT && !ProcessDriveDownload() )
{
// Try downloading the Drive file again
driveDownloadAttempt++;
DownloadFileInternal();
}
else if( DownloadFileCompleted != null )
DownloadFileCompleted( this, e );
}
}
// Downloading large files from Google Drive prompts a warning screen and requires manual confirmation
// Consider that case and try to confirm the download automatically if warning prompt occurs
// Returns true, if no more download requests are necessary
private bool ProcessDriveDownload()
{
FileInfo downloadedFile = new FileInfo( downloadPath );
if( downloadedFile == null )
return true;
// Confirmation page is around 50KB, shouldn't be larger than 60KB
if( downloadedFile.Length > 60000L )
return true;
// Downloaded file might be the confirmation page, check it
string content;
using( var reader = downloadedFile.OpenText() )
{
// Confirmation page starts with <!DOCTYPE html>, which can be preceeded by a newline
char[] header = new char[20];
int readCount = reader.ReadBlock( header, 0, 20 );
if( readCount < 20 || !( new string( header ).Contains( "<!DOCTYPE html>" ) ) )
return true;
content = reader.ReadToEnd();
}
int linkIndex = content.LastIndexOf( "href=\"/uc?" );
if( linkIndex < 0 )
return true;
linkIndex += 6;
int linkEnd = content.IndexOf( '"', linkIndex );
if( linkEnd < 0 )
return true;
downloadAddress = new Uri( "https://drive.google.com" + content.Substring( linkIndex, linkEnd - linkIndex ).Replace( "&", "&" ) );
return false;
}
// Handles the following formats (links can be preceeded by https://):
// - drive.google.com/open?id=FILEID
// - drive.google.com/file/d/FILEID/view?usp=sharing
// - drive.google.com/uc?id=FILEID&export=download
private string GetGoogleDriveDownloadAddress( string address )
{
int index = address.IndexOf( "id=" );
int closingIndex;
if( index > 0 )
{
index += 3;
closingIndex = address.IndexOf( '&', index );
if( closingIndex < 0 )
closingIndex = address.Length;
}
else
{
index = address.IndexOf( "file/d/" );
if( index < 0 ) // address is not in any of the supported forms
return string.Empty;
index += 7;
closingIndex = address.IndexOf( '/', index );
if( closingIndex < 0 )
{
closingIndex = address.IndexOf( '?', index );
if( closingIndex < 0 )
closingIndex = address.Length;
}
}
return string.Concat( "https://drive.google.com/uc?id=", address.Substring( index, closingIndex - index ), "&export=download" );
}
public void Dispose()
{
webClient.Dispose();
}
}
And here's how you can use it:
// NOTE: FileDownloader is IDisposable!
FileDownloader fileDownloader = new FileDownloader();
// This callback is triggered for DownloadFileAsync only
fileDownloader.DownloadProgressChanged += ( sender, e ) => Console.WriteLine( "Progress changed " + e.BytesReceived + " " + e.TotalBytesToReceive );
// This callback is triggered for both DownloadFile and DownloadFileAsync
fileDownloader.DownloadFileCompleted += ( sender, e ) => Console.WriteLine( "Download completed" );
fileDownloader.DownloadFileAsync( "https://INSERT_DOWNLOAD_LINK_HERE", #"C:\downloadedFile.txt" );
#Case 1: download file with small size.
You can use url with format https://drive.google.com/uc?export=download&id=FILE_ID and then inputstream of file can be obtained directly.
#Case 2: download file with large size.
You stuck a wall of a virus scan alert page returned. By parsing html dom element, I tried to get link with confirm code under button "Download anyway" but it didn't work. Its may required cookie or session info.
enter image description here
SOLUTION:
Finally I found solution for two above cases. Just need to put httpConnection.setDoOutput(true) in connection step to get a Json.
)]}' { "disposition":"SCAN_CLEAN",
"downloadUrl":"http:www...",
"fileName":"exam_list_json.txt", "scanResult":"OK", "sizeBytes":2392}
Then, you can use any Json parser to read downloadUrl, fileName and sizeBytes.
You can refer follow snippet, hope it help.
private InputStream gConnect(String remoteFile) throws IOException{
URL url = new URL(remoteFile);
URLConnection connection = url.openConnection();
if(connection instanceof HttpURLConnection){
HttpURLConnection httpConnection = (HttpURLConnection) connection;
connection.setAllowUserInteraction(false);
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.connect();
int reqCode = httpConnection.getResponseCode();
if(reqCode == HttpURLConnection.HTTP_OK){
InputStream is = httpConnection.getInputStream();
Map<String, List<String>> map = httpConnection.getHeaderFields();
List<String> values = map.get("content-type");
if(values != null && !values.isEmpty()){
String type = values.get(0);
if(type.contains("text/html")){
String cookie = httpConnection.getHeaderField("Set-Cookie");
String temp = Constants.getPath(mContext, Constants.PATH_TEMP) + "/temp.html";
if(saveGHtmlFile(is, temp)){
String href = getRealUrl(temp);
if(href != null){
return parseUrl(href, cookie);
}
}
} else if(type.contains("application/json")){
String temp = Constants.getPath(mContext, Constants.PATH_TEMP) + "/temp.txt";
if(saveGJsonFile(is, temp)){
FileDataSet data = JsonReaderHelper.readFileDataset(new File(temp));
if(data.getPath() != null){
return parseUrl(data.getPath());
}
}
}
}
return is;
}
}
return null;
}
And
public static FileDataSet readFileDataset(File file) throws IOException{
FileInputStream is = new FileInputStream(file);
JsonReader reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.beginObject();
FileDataSet rs = new FileDataSet();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equals("downloadUrl")){
rs.setPath(reader.nextString());
} else if(name.equals("fileName")){
rs.setName(reader.nextString());
} else if(name.equals("sizeBytes")){
rs.setSize(reader.nextLong());
} else {
reader.skipValue();
}
}
reader.endObject();
return rs;
}
This seems to be updated again as of May 19, 2015:
How I got it to work:
As in jmbertucci's recently updated answer, make your folder public to everyone. This is a bit more complicated than before, you have to click Advanced to change the folder to "On - Public on the web."
Find your folder UUID as before--just go into the folder and find your UUID in the address bar:
https://drive.google.com/drive/folders/<folder UUID>
Then head to
https://googledrive.com/host/<folder UUID>
It will redirect you to an index type page with a giant subdomain, but you should be able to see the files in your folder. Then you can right click to save the link to the file you want (I noticed that this direct link also has this big subdomain for googledrive.com). Worked great for me with wget.
This also seems to work with others' shared folders.
e.g.,
https://drive.google.com/folderview?id=0B7l10Bj_LprhQnpSRkpGMGV2eE0&usp=sharing
maps to
https://googledrive.com/host/0B7l10Bj_LprhQnpSRkpGMGV2eE0
And a right click can save a direct link to any of those files.
Using a Service Account might work for you.
Check this out:
wget https://raw.githubusercontent.com/circulosmeos/gdown.pl/master/gdown.pl
chmod +x gdown.pl
./gdown.pl https://drive.google.com/file/d/FILE_ID/view TARGET_PATH
Update as of August 2020:
This is what worked for me recently -
Upload your file and get a shareable link which anyone can see(Change permission from "Restricted" to "Anyone with the Link" in the share link options)
Then run:
SHAREABLE_LINK=<google drive shareable link>
curl -L https://drive.google.com/uc\?id\=$(echo $SHAREABLE_LINK | cut -f6 -d"/")
If you just want to programmatically (as oppossed to giving the user a link to open in a browser) download a file through the Google Drive API, I would suggest using the downloadUrl of the file instead of the webContentLink, as documented here: https://developers.google.com/drive/web/manage-downloads
https://github.com/google/skicka
I used this command line tool to download files from Google Drive. Just follow the instructions in Getting Started section and you should download files from Google Drive in minutes.
For any shared link replace FILENAME and FILEID, (for very large files requiring confirmation):
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O- | sed -rn 's/.confirm=([0-9A-Za-z_]+)./\1\n/p')&id=FILEID" -O FILENAME && rm -rf /tmp/cookies.txt
(For small files):
wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O FILENAME
I would consider downloading from the link, scraping the page that you get to grab the confirmation link, and then downloading that.
If you look at the "download anyway" URL it has an extra confirm query parameter with a seemingly randomly generated token. Since it's random...and you probably don't want to figure out how to generate it yourself, scraping might be the easiest way without knowing anything about how the site works.
You may need to consider various scenarios.
I simply create a javascript so that it automatically capture the link and download and close the tab with the help of tampermonkey.
// ==UserScript==
// #name Bypass Google drive virus scan
// #namespace SmartManoj
// #version 0.1
// #description Quickly get the download link
// #author SmartManoj
// #match https://drive.google.com/uc?id=*&export=download*
// #grant none
// ==/UserScript==
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
await sleep(5000);
window.close();
}
(function() {
location.replace(document.getElementById("uc-download-link").href);
demo();
})();
Similarly you can get the html source of the url and download in java.
I faced an issue in direct download because I was logged in using multiple Google accounts.
Solution is append authUser=0 parameter. Sample request URL to download :https://drive.google.com/uc?id=FILEID&authuser=0&export=download
https://drive.google.com/uc?export=download&id=FILE_ID replace the FILE_ID with file id.
if you don't know were is file id then check this article Article LINK

What is the proper way to check if a file/folder in a Box account is read-only using the Box Android library (apiV2)?

I am working on an android app used to access a Box account. The problem I am facing is how to determine a folder/file in the user's account is read only (shared with him/her as a Viewer) so that the upload/delete operations can be disabled.
What I currently do is:
1) Get the items in a folder:
BoxCollection itemsCollection = _boxClient.getFoldersManager()
.getFolderItems(folderId, folderContentRequest);
String userMail = ...
ArrayList<BoxTypedObject> result = null;
2) Determine which one is folder, get it's collaborations, check if it's accessible by the logged-in user, and check whether he is an editor:
if (itemsCollection != null) {
result = itemsCollection.getEntries();
for(BoxTypedObject boxObject : result) {
if(boxObject instanceof BoxAndroidFolder) {
BoxAndroidFolder folder = (BoxAndroidFolder)boxObject;
List<BoxCollaboration> folderCollaborations = _boxClient.getFoldersManager().getFolderCollaborations(folder.getId(), null);
for(BoxCollaboration collaboration : folderCollaborations) {
if( userMail.equalsIgnoreCase(collaboration.getAccessibleBy().getLogin()) &&
!BoxCollaborationRole.EDITOR.equalsIgnoreCase(collaboration.getRole()))
System.out.println("" + folder.getName() + " is readonly");
}
}
}
}
So, is there a simpler and faster (fewer requests) way to get that property of a folder with the android SDK?
You can first check the owner of the folder (folder.getOwnedBy()), if it's the current user then you don't need to check collaborations. However if it's not the current user you'll have to check collaborations.

dokuwiki authentication from java

Here is the scenario:
I want to use docuwiki to show help and other content to users. The users are grouped by to organization. Each organization gets their own content that should be private to them. Enter ACL. I get how I can create a user and limit him to a certain subsection of the wiki.
Now the fun part begins. How can I authenticate these users from my server? I'm running a Tomcat/Java/MSSQL stack. I have full control of both servers.
I'd imagine if it is possible, I would imagine I can post the username/password to the wiki from the servlet, and get some kinda token back that the user can access the site with. But I don't see anything in the documentation about this. If anyone has any ideas, pointers or alternatives, I'd appreciate it.
I think the thing that you need is named Single Sign On (SSO). As a possible solution you could setup an SSO provider (there is vast variety of them, also with support of Tomcat and dokuwiki) and configure your dokuwiki and tomcat to use it. Here is a sample of such provider.
For googlers that come after me:
I ended up writing my own authenticator. TO use authenticator place it in *\inc\auth* with the name sqlsrv.class.php (sqlsrv will be the code you use to specify this authenticator.)
Basically what happens with this is I generate a token on my server that uniquely identifies a logged in user. I then POST or GET to the wiki with the token. The authenticator then queries the server to see if the user should be authenticated, as well as to get the name, email and which ACL groups the user should belong to.
Notes: make sure you change the config options in the php file. And you'll need sqlsrv installed and enabled for your apache/php.
<?php
/**
* sqlsrv authentication backend
*
* #license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
class auth_sqlsrv extends auth_basic {
/**
* Constructor
*
* Carry out sanity checks to ensure the object is
* able to operate. Set capabilities.
*
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
function __construct() {
global $config_cascade;
global $connection;
$this->cando['external'] = true;
}
function trustExternal()
{
//$msgTxt = $_SESSION[DOKU_COOKIE]['auth']['info']['user']."x";
//msg($msgTxt);
//return true;
global $USERINFO;
global $conf;
global $connection;
//already logged in, no need to hit server
if (!empty($_SESSION[DOKU_COOKIE]['auth']['info']))
{
$USERINFO['name'] = $_SESSION[DOKU_COOKIE]['auth']['info']['user'];
$USERINFO['mail'] = $_SESSION[DOKU_COOKIE]['auth']['info']['mail'];
$USERINFO['grps'] = $_SESSION[DOKU_COOKIE]['auth']['info']['grps'];
$_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
return true;
}
//check server based on token
try
{
$token = $_GET["token"];
if($token==null)
$token = $_POST["token"];
if($token==null)
$token = $_SESSION[DOKU_COOKIE]['auth']['token'];
if($token==null)
{
msg("Could not authenticate. Please contact your admin.");
return false;
}
//config //NOTE: replace with the appropriate values
$myServer = "1.1.1.1,1433";
$myUser = "sqlaccount";
$myPass = "sqlpassword";
$myDB = "dbName";
//end config
//get connection
$connectionInfo = array('UID' => $myUser, 'PWD' => $myPass, "Database"=>$myDB);
$link = sqlsrv_connect($myServer, $connectionInfo);
//check connection
if($link === FALSE)
{
msg("Could not get connection, contact your admin.");
return false;
}
//run token against proc
//NOTE: this needs to be implemented on your server, returns :
//"user" - Name of the user //this does not have to be setup in the wiki
//"email" - user's email //this does not have to be setup in the wiki
//"groups" - Which groups //this *does* have to be setup in the wiki to be used with ACL
$sql = "exec WikiLogin '".$token."'";
$stmt = sqlsrv_query( $link, $sql);
//check statement
if( $stmt === false)
{
msg("Could not get connection statement, contact your admin.");
return false;
}
//if returned results, set user and groups
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
// set the globals if authed
$USERINFO['name'] = $row['user'];
$USERINFO['mail'] = $row['email'];
$USERINFO['grps'] = split(" ",$row['groups']);
//msg(implode($row," "));
//msg(implode($USERINFO," "));
$_SERVER['REMOTE_USER'] = $row['user'];
//uncomment after testing
$_SESSION[DOKU_COOKIE]['auth']['user'] = $row['user'];
$_SESSION[DOKU_COOKIE]['auth']['mail'] = $row['email'];
$_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
$_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
sqlsrv_free_stmt( $stmt);
sqlsrv_close($link);
return true;
}
return false;
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
catch (Exception $e)
{
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
}
}

Categories