I have my own custom git servlet implemented using GitServlet.
I have my own authentication.
To clone or push, pull i want to authenticate against my authentication plugin.
To do this i need to read user/password from url given by user.
Like,
git clone http://sohanb:welcome#localhost:8080/git.ctr-0.0.1-SNAPSHOT/portal/.git
How can i get the usernmae i.e sohanb and password i.e welcome.
Updated question:
My git init code,
public void init(ServletConfig config) throws ServletException {
username = config.getInitParameter("username");
password=config.getInitParameter("password");
idpUrl=config.getInitParameter("idpUrl");
System.out.println("IDP URL is =======>> " + idpUrl);
setRepositoryResolver(new RepositoryResolver<HttpServletRequest>() {
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException,
ServiceNotEnabledException {
try {
System.out.println("name =============>> " +name);
System.out.println("parmrs if any ==========>> " + req.getParameterMap());
System.out.println("URL ===============>>" + req.getRequestURL().toString());
URL url = new URL(req.getRequestURL().toString());
System.out.println("Trying to get uswer info if any ====>> " +url.getUserInfo());
File gitParentFolder = new File("D:\\sigma-admin\\git.ctr\\git");
File gitRepoFolder = new File(gitParentFolder, name);
System.out.println("gitRepoFolder.exists() =======>>" + gitRepoFolder.exists());
if (gitRepoFolder.exists()) {
if (!gitRepoFolder.getAbsolutePath().endsWith(".git")) {
gitRepoFolder = new File(gitRepoFolder, ".git");
}
Repository db = Git.open(gitRepoFolder).getRepository();
db.incrementOpen();
return db;
} else {
throw new RepositoryNotFoundException("Unknown repository was requested by client " + name);
}
} catch (IOException e) {
throw new RepositoryNotFoundException(name, e);
}
}
});
}
My git war running under jettry server
http://localhost:8080/git.ctr-0.0.1-SNAPSHOT/
Now when i do git clone http://sohanb:welcome#localhost:8080/git.ctr-0.0.1-SNAPSHOT/portal/.git
The url i can see in logs/console,
http://localhost:8080/git.ctr-0.0.1-SNAPSHOT/portal/.git/
I don't know why use:pass missing from req url. Or it is not valid what i am trying to achieve.
Other suggestion to do this are most welcomed.
Please suggest.
A regex would be:
https?:\/\/(?<user>[^:]+):(?<password>[^#]+)
# look for http or https followed by ://
# capture everything up (but not including) a colon and capture it in a group called user
# match a colon
# capture everything up (but not including) an # and capture it in a group called password
See a demo here. It however somewhat depends on what you really want (working with the information in PHP, Python, the bash, etc.).
Since it is http:, you can use the java.net.URL:
URL url = new URL("http://sohanb:welcome#localhost:8080/git.ctr-0.0.1-SNAPSHOT/portal/.git");
String userInfo = url.getUserInfo(); // userInfo = "sohanb:welcome"
Check for null and then you can get what you want really easy:
String[] userInfoArray = userInfo.split(":");
String username = userInfoArray[0]; // sohanb
String password = userInfoArray[1]; // welcome
Related
I am developing an application with JWT authentication on the google cloud platform. Server side I added authentication via Cloud API Gateway to a cloud run backend. Now I am making a client to generate the JWT token and pass it in the call. To do this I am creating an application that must be deployed on CloudRun and I am following this documentation: https://cloud.google.com/api-gateway/docs/authenticate-service-account#making_an_authenticated_request. My problem is that I don't know how to indicate what it requires as saKeyfile. I tried to put only the name of the file that under src / main / resources / filetest.json but once I try to call the method it tells me file not found. I tried to indicate also the full path. Can anyone help me?
PS I'm using Java
EDIT:
here is my code which is the same of documentation
public void makeCall() {
String fullPath="src/main/resources/TEST1-id.json";
String saEmail="testsa#projectID.iam.gserviceaccount.com";
String audience="auth";
int expiryLenght=600;
String token;
try {
token=generateJwt(fullPath,saEmail,audience,expiryLenght);
System.out.println("Token generated: "+token);
URL url = new URL("apigatewayurl");
makeJwtRequest(token, url);
System.out.println("Call performed");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String generateJwt(final String saKeyfile, final String saEmail,
final String audience, final int expiryLength)
throws FileNotFoundException, IOException {
Date now = new Date();
Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));
// Build the JWT payload
JWTCreator.Builder token = JWT.create()
.withIssuedAt(now)
// Expires after 'expiraryLength' seconds
.withExpiresAt(expTime)
// Must match 'issuer' in the security configuration in your
// swagger spec (e.g. service account email)
.withIssuer(saEmail)
// Must be either your Endpoints service name, or match the value
// specified as the 'x-google-audience' in the OpenAPI document
.withAudience(audience)
// Subject and email should match the service account's email
.withSubject(saEmail)
.withClaim("email", saEmail);
// Sign the JWT with a service account
FileInputStream stream = new FileInputStream(saKeyfile);
ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
Algorithm algorithm = Algorithm.RSA256(null, key);
return token.sign(algorithm);
}
i've tried to use full path like in example and using only /TEST1-id.json
and here there is project structure. Is a springboot application which i will deploy in cloud run
The OP fixed the issue on this way
In the end I put the file in the root and copied it in the docker image and recover it as an environment variable in cloud run
EDIT: See my post below for answer how to fix this.
I am building a client app that will store some data in the user dropbox app folder. So currently I am using implicit grant that will redirect the user to the given redirect uri with the parameters passed after the # in the url
Example:
localhost:1666/Dropbox#access_token=...&token_type=.......
Creating a http listener over the localhost url it detects the request however everything after # is ignored and is not passed as part of the request. Is there a way to make capture the data after the #, or is there any other library that allows me to do so?
I am using the cpprestsdk https://github.com/microsoft/cpprestsdk
web::http::experimental::listener::http_listener* l = new web::http::experimental::listener::http_listener(m_authConfig.redirect_uri());
l->support([this](web::http::http_request request) -> void
{
auto uri = request.request_uri();
auto requestPath = web::uri::split_path(uri.path());
auto queryObjects = web::uri::split_query(uri.query());
auto s = uri.fragment();
if (request.request_uri().path() == U("/Dropbox")) && request.request_uri().query() != U(""))
{
request.reply(web::http::status_codes::OK, U("ok.") + uri.query());
}
else
{
request.reply(web::http::status_codes::OK, U("error.") + uri.query());
}
});
l->open().wait();
Thanks!
So after researching a bit, it turns out that # (fragments) are not sent back in most browsers, so to be able to get the data i return the following java-script script:
<script> window.location.replace([location.protocol, '//', location.host, location.pathname, '?', location.hash.substring(1,location.hash.length )].join(''));</script>
This will convert the hash part to a query string and redirect it the user to it so that the listener detects it.
My website (Spring MVC) allows users to sign up by using their Facebook accounts and sign into my site later with their Facebook accounts. I use scribejava (version 6.6.3) (https://github.com/scribejava/scribejava) for the Oauth integration with Facebook.
I have tested a use case and am unable to find a way to resolve it. Here is the list of steps:
The tester goes to my site's "Log in" page, clicks "Log in with Facebook", grants permissions at Facebook, gets redirected to my site, and signs out. This is a normal and successful flow.
The tester sign into Facebook at Facebook.com
The tester goes to Settings->Apps and Websites and removes my site
The tester goes to my site's "Log in" page, clicks "Log in with Facebook" button, gets redirected to Facebook, and sees an error message.
At step 4, the tester always gets an error message at the Facebook site instead of asking the tester to grant permissions again. See the following screenshot:
I cannot find a way at Facebook to remove this message when clicking on the "Log in with Facebook" button. Here is my code for the web interface. Did I miss something?
#RequestMapping( value="/facebook", method = RequestMethod.GET)
public void facebook(HttpServletRequest request,
#RequestParam(value = "page", required = true) String page,
HttpServletResponse response) throws Exception {
try {
OAuth20Service service = new ServiceBuilder(config.getProperty("facebook.clientId"))
.apiSecret(config.getProperty("facebook.clientSecret"))
.callback(getCallback())
.build(FacebookApi.instance());
String authUrl = service.getAuthorizationUrl();
response.sendRedirect(authUrl);
} catch (Exception e) {
response.sendRedirect("/oauthFail");
}
}
#RequestMapping( value="/facebook/callback", method = RequestMethod.GET)
public void facebookCallback(HttpServletRequest servletRequest,
#RequestParam(value = "code", required = false) String code,
#RequestParam(value = "error", required = false) String error,
HttpServletResponse servletResponse
) throws Exception {
try {
OAuth20Service service = new ServiceBuilder(config.getProperty("facebook.clientId"))
.apiSecret(config.getProperty("facebook.clientSecret"))
.callback(getCallback())
.build(FacebookApi.instance());
OAuth2AccessToken accessToken = service.getAccessToken(code);
final OAuthRequest request = new OAuthRequest(Verb.GET, "https://graph.facebook.com/v3.2/me");
service.signRequest(accessToken, request);
final com.github.scribejava.core.model.Response response = service.execute(request);
String body = response.getBody();
JSONObject jObject = new JSONObject(body);
String email = jObject.getString("email");
//success. use the email to create an account or if the email address exists, direct a userto their account page
} catch (Exception e) {
response.sendRedirect("/oauthFail");
}
}
How to handle this situation? I feel either something is wrong is my code or scribejava has a framework issue. Or this is a Facebook specific issue?
I have just tested the case. Couldn't reproduce.
Did you try running this Example
https://github.com/scribejava/scribejava/blob/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/FacebookExample.java
?
I think your problem can be with API versions logic in Facebook.
You can try to explicitly use the latest one .build(FacebookApi.customVersion("3.2"))
Is it possible to configure
where a file is uploaded to (it's currently being upload direct to the media library)
how a file is displayed in the Form Report (currently a long link string that can't be easily read nor clicked on)
which file types are allowed (e.g. images only)
how the file will be forwarded by email
We have a multi-site solution, so ideally we'd like to be able to set these on a form by form basis, but be able to configure defaults as Solution Default > Site default > Form specific.
I've already seen that there are code examples for limiting file size, which is something else we'd like to do.
So are any of these directly configurable, or will we need to code them?
Edit:
Web Forms For Marketers 2.3.0 rev.131126
Running on Sitecore 7.0 rev. 140120 (7.0 Update-4).
Yes you can define path where file will upload in case of file field.
Please see attached screenshot.
All file upload settings are located under:
/sitecore/System/Modules/Web Forms for Marketers/Settings/Field
Types/Simple Types/File Upload
The pipeline ran when a file is uploaded is "formUploadFile"; so you could reflector existing one and amend to add required changes.
To upload allowed file types use below link.
http://sitecorejunkie.com/2014/06/16/restrict-certain-files-from-being-uploaded-through-web-forms-for-marketers-forms-in-sitecore-an-alternative-approach/
here you can get idea that how you can restrict mime types in WFFM.
To send attachment in email you can create custom send email action in Sitecore and use below code
// send email with attachments
public static bool SendEmailWithAttachments(string To, string From, string Subject, string Message, string atchmnt1, string atchmnt2, string atchmnt3) {
bool result = true;
try {
MailMessage mailMsg = new MailMessage();
// mailaddress of sender
MailAddress mailFrom = new MailAddress(From);
mailMsg.From = mailFrom;
// mail addresses for recipients
string[] mailAddressList = To.Split(',');
foreach (string str in mailAddressList) {
try {
MailAddress mailTo = new MailAddress(str.Trim());
mailMsg.To.Add(mailTo);
}
catch { }
}
mailMsg.Subject = Subject;
mailMsg.Body = Message;
mailMsg.IsBodyHtml = true;
if (!string.IsNullOrEmpty(atchmnt1)) {
mailMsg.Attachments.Add(ReadAttachment(atchmnt1));
}
if (!string.IsNullOrEmpty(atchmnt2)) {
mailMsg.Attachments.Add(ReadAttachment(atchmnt2));
}
if (!string.IsNullOrEmpty(atchmnt3)) {
mailMsg.Attachments.Add(ReadAttachment(atchmnt3));
}
var smtp = new SmtpClient(Sitecore.Configuration.Settings.MailServer, Sitecore.Configuration.Settings.MailServerPort);
smtp.Send(mailMsg);
}
catch {
result = false;
}
return result;
}
// get attachement by media item id
public static Attachment ReadAttachment(string value) {
MediaItem mediaItem = null;
ItemUri itemUri = ItemUri.Parse(value);
if (itemUri != null) {
Item item = Database.GetItem(itemUri);
if (item != null) {
mediaItem = new MediaItem(item);
}
}
// create attachment using media item properties
Attachment attachment = new Attachment(mediaItem.GetMediaStream(), string.Join(".", new string[] { mediaItem.Name, mediaItem.Extension}), mediaItem.MimeType);
return attachment;
}
Now I'm bulding game by UNITY3D. I want to send json file to server to store it in database I build server by php with Yii Framework, i have problem with send data in client [UNITY3D] and retrieve it in server [Yii]. Please help me.UNITY3D code: I want to send 'name' -> to server
var url = "http://localhost:8888/TPP/index.php/site/saveName";
var form = new WWWForm();
form.AddField( "player", "Henry" );
var download = new WWW( url, form );
print(download);
yield download;
if(download.error) {
print( "Error downloading: " + download.error );
return;
} else {
// show the highscores
Debug.Log(download.text);
}
In Yii, i tried to get data in request
public function actionSaveName() {
if(isset($_POST['name']) {
echo $_POST['name'];
} else {
echo "nothing";
}
}
Is that right?
The unity part is fine, but in yii you'll have to check for $_POST['player'] instead of $_POST['name'] because according to the AddField() documentation, the first parameter is the name of the generated form element.
If you want to have it as name then you'll have to change AddField as : form.AddField("name", "Henry");