reading two variable values after decrypting - java

I am working on "Forgot Password". I am trying to create a reset token with email + current_time. email is user login whilst code will check if time >= 5 minutes then this link will not work. Here is my code:
// preparing token email + time
Date now = new Date();
String prepareToken = "?email="+email+"&tokenTime="+now.getTime();
// encrypt prepareToken value
Encryptor enc = new Encryptor();
resetToken = enc.encrypt(resetToken);
The token will be sent as for example as http://domainname.com/ForgotPassword?resetToken=adj23498ljj238809802340823
Problem:
When user click it then I got as request parameter and obviously decrypt this parameter but how can I get email in one String + time as another String
Please advise

If your issue is simply parsing the decoded String to get some sort of Map of your parameters, I'd suggest you to read Parse a URI String into Name-Value Collection .
Hope it helps.
EDIT :
Assuming you have the splitQuery(URL url) method from the previous link and that you successfully decoded the token :
public String getEmailFromToken(String decodedToken) {
// if you decoded your token it will looks like the prepareToken String
String stubUrl = "http://localhost"+decodedToken;
Map<String,String> map = splitQuery(new URL(stubUrl));
return map.get("timeToken");
}
I created a properly formed URL to respect the URL syntax.
With little tweak, you should be able to implement splitQuery for a String. I hope you can manage that.

Related

Need to get value after Domain name in url using java

We are getting url from JSON Response and which we open in in Chrome.The page loads , there is submit button which we click then it redirect to url as :-
https://www.google.com/AB1234
We need the need to retrieve only "AB1234" value from url.
tried following code to get value ="AB1234"
String url = driver.getCurrentUrl();
int index=url.lastIndexOf("/");
String result = url.substring(0,index);
but here getting initial part of url:https://www.google.com/
You need to call substring function with index +1 .
Try below code :
String url = driver.getCurrentUrl();
int index = url.lastIndexOf("/");
String result = url.substring(index + 1);
To parse a URI, it's likely a good idea to use a URI parser.
Given http://example.com/bar
String path = URI.create(driver.getCurrentUrl()).getPath();
will get you '/bar'.
Given http://example.com/bar/mumble the same code gets '/bar/mumble'. It's unclear from your question whether this is what you want. Nevertheless, you should at least start the parse as above.

Update JWT token field using numbus library

I have a Signed JWT token and I need to update an existing field, let's call it userName. I'm using NIMBUS + JOSE and. I figured out how to parse it and extract the claims:
SignedJWT.parse(token)
but parsing is not the only thing i need: I have update the field and reassemble its token back. Is there an easy way or any kind of idiomatic solution that will work without recreating the token from scratch.
I spend some time trying to figure out how to modify JWT token using the library.
And I used a quick and dirty solution:
// Split token into parts (parts are separated with '.'
final String[] tokenParts = token.split("\\.");
// decode payload part
final String decodedPayload =
new String(Base64.getDecoder().decode(tokenParts[1]), "UTF-8");
// enrich payload with additional userName field by adding it to the end of
// JSON. Remove the last character which is '}' and append data as String
final String updatedDecodedPayload =
decodedPayload.substring(0, decodedPayload.length() - 1)
+ ",\"userName\":\"" + "Richard" + "\"}";
// update payload with userId field and encode it back to base64
tokenParts[1] = Base64.getEncoder().encodeToString(
updatedDecodedPayload.getBytes()
);
final String updatedToken = String.join(".", tokenParts));

How to handle foreign addresses in Java application that calls Nominatim Webservice

The following code produces a string that has question marks as the display name when I insert an Iranian address(?????, ???????). However if I put the same url into my browser, it returns Tehran, Iran instead of question marks. I know that it has something to do with encoding but how do I get the English text as the browser returns in my java application?
String rawAddress = "Tehran";
String address = URLEncoder.encode(rawAddress, "utf-8");
String geocodeURL = "http://nominatim.openstreetmap.org/search?format=json&limit=1&polygon=0&addressdetails=0&email=myemail#gmail.com&languagecodes=en&q=";
String formattedUrl = geocodeURL + address;
URL theGeocodeUrl = new URL(formattedUrl);
System.out.println("HERE " +theGeocodeUrl.toString());
InputStream is = theGeocodeUrl.openStream();
final ObjectMapper mapper = new ObjectMapper();
final List<Object> dealData = mapper.readValue(is, List.class);
System.out.println(dealData.get(0).toString());
I tried the following code but it produced this: تهران, �ايران‎ for the display name which should be Tehran, Iran.
System.out.println(new String(dealData.get(0).toString().getBytes("UTF-8")));
Use "accept-language" in the URL parameter for Nominatim to specify the preferred language of Nominatim's results, overriding whatever default the HTTP header may set. From the documentation:
accept-language= <browser language string>
Preferred language order for showing search results, overrides the
value specified in the "Accept-Language" HTTP header. Either uses
standard rfc2616 accept-language string or a simple comma separated
list of language codes.

Android Programming - Post Google Form/Spreedsheet (REQUIRED FIELD)

So I have successfully post data onto a Google Spreadsheet using the Google Form source. Everything works perfect UNTIL I make the field (in the Google Form) "required." When I do that, the Android Emulator still responds as if the information sent was properly saved. But on the Google spreadsheet it isn't there.
Am I missing something?
This is my AsyncTask:
new BackgroundTask().execute(
"https://docs.google.com/forms/d/10QStmb9Nr-hcfv889FMSNTZdA_hNUErxeK7vISzkx0E/formResponse",
student.FirstName, "entry_2030274183=",
student.LastName, "entry_1558758483=",
student.Age, "entry_1871336861=",
student.Gender, "entry.2013677542=",
student.Grade, "entry_1921311866=");
This is my Background.
protected String doInBackground(String... params) {
HttpRequest reg = new HttpRequest();
String URL = params[0];
String FirstName = params[1];
String FirstNameEntry = params[2];
String LastName = params[3];
String LastNameEntry = params[4];
String Age = params[5];
String AgeEntry = params[6];
String Gender = params[7];
String GenderEntry = params[8];
String Grade = params[9];
String GradeEntry = params[10];
#SuppressWarnings("deprecation")
String data =
FirstNameEntry + URLEncoder.encode(FirstName) + "&" +
LastNameEntry + URLEncoder.encode(LastName) + "&" +
AgeEntry + URLEncoder.encode(Gender) + "&" +
GenderEntry + URLEncoder.encode(Age) + "&" +
GradeEntry + URLEncoder.encode(Grade);
String response = reg.sendPost(URL, data);
return response;
}
Do I need to put something in the entries if it is a required field?
If you want to look at the HttpRequest class go here (Not My Code):
Secure HTTP Post in Android
Much Appreciated
The only way I can immediately think of is by processing the response and then making your app behave accordingly.
For instance - I tried one test form and if the request send had some required field empty, then the HTTPResponse contains "Looks like you have a question or two that still need attention".
Another way would be to validate if the save was actually successful by searching for the text you gave in the "Confirmation Page".
In both cases, you should be able to differentiate between a successful post and a failed one.

insert a domain name into servlet authentication token

I am using Waffle for an SSO solution in my web-app.
Everything works fine but I would like to modify some functionality slightly:
Currently, if a user is not connected to the domain the SSO fails and opens a little authorization dialog:
The windows authorization requires the user name formatted like Domain\Username but most of my users will not know to add the domain in front of their username. So I would like to provide a default domain name if one is not specified.
I found a waffle function that I can override which will give me access to the decoded authentication token, I added a println to the waffle function and it shows the username in plain text (either with or without the domain depending on what is typed in the dialog):
public IWindowsSecurityContext acceptSecurityToken(String connectionId, byte[] token, String securityPackage) {
// I can see the passed username in the logs with this
System.out.println(new String(token));
// I don't understand any of the JNA stuff below this comment:
IWindowsCredentialsHandle serverCredential = new WindowsCredentialsHandleImpl(
null, Sspi.SECPKG_CRED_INBOUND, securityPackage);
serverCredential.initialize();
SecBufferDesc pbServerToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, Sspi.MAX_TOKEN_SIZE);
SecBufferDesc pbClientToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, token);
NativeLongByReference pfClientContextAttr = new NativeLongByReference();
CtxtHandle continueContext = _continueContexts.get(connectionId);
CtxtHandle phNewServerContext = new CtxtHandle();
int rc = Secur32.INSTANCE.AcceptSecurityContext(serverCredential.getHandle(),
continueContext, pbClientToken, new NativeLong(Sspi.ISC_REQ_CONNECTION),
new NativeLong(Sspi.SECURITY_NATIVE_DREP), phNewServerContext,
pbServerToken, pfClientContextAttr, null);
WindowsSecurityContextImpl sc = new WindowsSecurityContextImpl();
sc.setCredentialsHandle(serverCredential.getHandle());
sc.setSecurityPackage(securityPackage);
sc.setSecurityContext(phNewServerContext);
switch (rc)
{
case W32Errors.SEC_E_OK:
// the security context received from the client was accepted
_continueContexts.remove(connectionId);
// if an output token was generated by the function, it must be sent to the client process
if (pbServerToken != null
&& pbServerToken.pBuffers != null
&& pbServerToken.cBuffers.intValue() == 1
&& pbServerToken.pBuffers[0].cbBuffer.intValue() > 0) {
sc.setToken(pbServerToken.getBytes());
}
sc.setContinue(false);
break;
case W32Errors.SEC_I_CONTINUE_NEEDED:
// the server must send the output token to the client and wait for a returned token
_continueContexts.put(connectionId, phNewServerContext);
sc.setToken(pbServerToken.getBytes());
sc.setContinue(true);
break;
default:
sc.dispose();
WindowsSecurityContextImpl.dispose(continueContext);
_continueContexts.remove(connectionId);
throw new Win32Exception(rc);
}
return sc;
}
That whole function is from the Waffle API I only added the println at the beginning.
The passed username prints in plain text inside this token between a bunch of random byte chars (ÉsR=ÍtÍö?æ¸+Û-).
I am admittedly in very far over my head with JNA and java in general but I thought that because I can see the username here there must be a way to prepend the domain name to the username part of this token? I could be wrong.
My other idea was to add the domain to the pbClientToken that is created from the raw byte[] token this method is passed.
The pbClientToken is a JNA Structure object derivative. It has the Stucture method writeField which looked promising but I can't seem to figure out what field I should write. The Structure.getFields method doesn't seem to be available from pbClientToken.
I was hoping that this was a simple problem for someone more familiar with byte[] processing or JNA.
You cannot do this. What happens behind this dialog is a call to LogonUser on the user's machine, which gives you a ticket, which is then sent to the server. Unfortunately the server is not in the same domain, so even if you manage to extract the username it's completely useless.

Categories