Android POST Data to server - http-post

please help me! I send this post to sever for authorization via email, but server answered
"error":"Wrong input parameters"
I know to items is true !and proplem is not in items!
public String RegistrationByEmail(String email, String username, String password) throws IOException {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy
= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://speechyard.com/api/register");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("pssword", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Id_Token_from_website2 = responseHandler(response);
Log.v(TAG, "Id_Token_from_website : " + Id_Token_from_website2);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return Id_Token_from_website2;
}

you may have a typo here:
nameValuePairs.add(new BasicNameValuePair("pssword", password));
I think it should be:
nameValuePairs.add(new BasicNameValuePair("password", password));
you forgot the a in password

Related

Okta URL redirection issue

I have developed an application which do SSO in various applications. I am able to authorize user and able to redirect on application embedded link by passing sessionToken which is a value of cookieToken in that url and this piece of code is working fine and not asking for login again.
#GetMapping("get-sso-url/{user_id}")
public ResponseEntity<Object> getSSOUrl(#PathVariable("user_id") String userId, #RequestParam("app_id") String appId){
log.info("DashboardController::getSSOUrl::START");
UserActivityDetails userActivityDetails = userActivityService.getUserActivity(userId);
AppInfoDetails appInfoDetails = appInfoService.findById(appId);
String appUrl = appInfoDetails.getApiEndpoint() + userActivityDetails.getCookieToken();
log.debug("DashboardController::getSSOUrl::appUrl " + appUrl);
log.info("DashboardController::getSSOUrl::END");
return new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.OK);
}
Now I just want to verify that the url is returning HttpStatus.OK or not? so I have written like this:
public ResponseEntity<Object> getSSOUrl(#PathVariable("user_id") String userId, #RequestParam("app_id") String appId){
log.info("DashboardController::getSSOUrl::START");
UserActivityDetails userActivityDetails = userActivityService.getUserActivity(userId);
AppInfoDetails appInfoDetails = appInfoService.findById(appId);
String appUrl = appInfoDetails.getApiEndpoint() + userActivityDetails.getCookieToken();
log.debug("DashboardController::getSSOUrl::appUrl " + appUrl);
log.info("DashboardController::getSSOUrl::END");
return checkAppResponse(appUrl).equals(HttpStatus.OK) ? new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.OK)
: new ResponseEntity<>(new UrlResponse(appUrl), HttpStatus.NOT_FOUND);
}
private HttpStatus checkAppResponse(String appUrl){
try{
URL url = new URL(appUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
int statusCode = httpURLConnection.getResponseCode();
if(statusCode == 200)
return HttpStatus.OK;
} catch (MalformedURLException e) {
throw new CustomRuntimeException(e.getMessage());
} catch (IOException e) {
throw new RuntimeException(e);
}
return HttpStatus.NOT_FOUND;
}
After adding above check, when I'm trying to redirect on application it asks me to login to the okta first.
Here is a sreenshot

How to Redirect request as post using ResponseEntity

I trying to include response from other url from ResponseEntity for oauth authorization but it is failing as I am unable to specify request method.
Below is the code
#RequestMapping(value = "/login/otp", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
#ResponseBody
public ResponseEntity<?> getOTP(#Valid #RequestBody String loginDtls,UriComponentsBuilder ucBuilder) {
LoginDAO login = null;
ResponseEntity<?> resp = null;
try {
ObjectMapper mapper = new ObjectMapper();
String userId = "";
try {
JsonNode root = mapper.readTree(loginDtls);
userId = root.get("userId").textValue();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("UserController : getting otp for contact "+ userId);
login = loginService.findByUserId(userId);
if (login==null) {
System.out.println("A UserDAO with name " + userId + " does not exist");
resp = new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
String otp = GenUtil.generateOTP();
LoginDAO loginUpd = new LoginDAO(login);
loginUpd.setOtp(otp);
loginUpd.setOtpTimestamp(new Timestamp(System.currentTimeMillis()));
loginService.updateLogin(loginUpd);
System.out.println(loginUpd);
resp = getAuthenticated(ucBuilder);
System.out.println(resp.getStatusCodeValue());
System.out.println(resp.getBody());
}catch(Exception e) {
e.printStackTrace();
}
resp = new ResponseEntity<String>(login.toString(), HttpStatus.OK);
return resp;
}
private ResponseEntity<?> getAuthenticated(UriComponentsBuilder ucBuilder){
HttpHeaders headers = new HttpHeaders();
URI uri= ucBuilder.path("/oauth/token"+PASSWORD_GRANT).build().toUri();
List<MediaType> accept = new ArrayList<MediaType>();
accept.add(MediaType.APPLICATION_JSON_UTF8);
headers.setAccept(accept);
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setBasicAuth("my-trusted-client", "secret");
System.out.println(headers);
ResponseEntity<?> resp = ResponseEntity.created(uri).headers(headers).build();
return resp;
}

Authorization code malformed or invalid when getting Azure AD access token with Spring

I have this error when I try to generate the token.
I have do this tutorial http://blog.xebia.in/index.php/2017/12/21/spring-security-and-oauth2-with-azure-active-directory/.
My problem is when I try to get an access token after I have the code.
I have this error:
Here is the related code:
public AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true, service);
//here are the error
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, resource, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}

Android - How can I get the email from the online login and show it to next intent

I created an online login on my mobile app, basically I have an online database, and I use asynctask for login. Basically I want to display the email that the user input from the app and display it to the next intent how can I do that, How can I pass the email that the user input to onPostExecute?
Here is the code in the onPostExecute when the user successfully logged in.
protected void onPostExecute(String result)
{
if (result.equals("Login Successfully!")) {
Toast.makeText(context, "Welcome to OKShop", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Main2Activity.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
And here is the login URL
else if (type.equals("login")) {
String email = params[1];
String password = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine())!= null) {
result+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Calling a different host from Spring Controller

My localhost is : http://localhost:8585/api/getproducts where i use #Requestmapping(/api/getproducts) in my ProductController to get to my product page.
On click of a button, i need to call an api on a different host :
http://10.120.130.22:9292/ and i tried to use the below code in a new Controller to call the host:
#RequestMapping("Trainer/reStaff/")
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody response(#RequestParam("trainingId") final int trainingId, HttpServletRequest request)
throws ClientProtocolException, IOException {
String hostname="http://10.120.130.22:9292/";
CloseableHttpClient httpclient = HttpClients.custom().build();
CloseableHttpResponse response=null;
try{
String uri=hostname+"Trainer/reStaff/?trainingId="+trainingId;
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
response = httpclient.execute(httpPost);
String responseData = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode()==200)
System.out.println(responseData+"\n");
else
System.out.println("Error :" + responseData+"\n");
}finally {
httpclient.close();
response.close();
}
But i get the error : HTTP Status 404 - type Status reportmessage description The requested resource is not available.
How do i call the new host from my controller?
I understood how this works. We need to pass the url through httpPost in the service layer :
HttpPost httpPost = new HttpPost(hostUri);
JsonObject jsonResponse = null;
try {
String httpRequestBody = jsonRequestBuilder.build().toString();
logger.info("Request Body: " + httpRequestBody);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(httpRequestBody));
HttpResponse httpResponse = httpClient.execute(httpPost);
logger.debug("Response Status: " + httpResponse.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
StringBuffer httpResponseBody = new StringBuffer();
while ((line = reader.readLine()) != null) {
httpResponseBody.append(line);
}
logger.info("Response Body: " + httpResponseBody.toString());
JsonReader jsonReader = Json.createReader(new StringReader(httpResponseBody.toString()));
jsonResponse = jsonReader.readObject();
jsonReader.close();
} catch (Exception ex) {
logger.error("Error occurred while invoking POST on ep: " + hostUrl, ex);
} finally {
httpPost.releaseConnection();
}
logger.debug("Exiting");
return jsonResponse;

Resources