HttpSession session=request.getSession(false); ruturning null - session

my code is
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession(false);
if(session==null){
response.sendRedirect(request.getContextPath());
}else{
doPost(request,response);
}
}
the url pattern for this servlet is /loginServlet.
i wrote this code so that if user is logged in and makes a get request by hitting enter on the url then the request must be forwarded to doPost()
or else if the user is not logged in then he get to the login page
but the problem is that its always returning to the login page that means request.getSession(false) always returning null
how can i solve this problem
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("name");
String commun=request.getParameter("commun");
String password=request.getParameter("password");
Connection conn = null;
Statement statement = null;
try{
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/community");
conn = ds.getConnection();
statement = conn.createStatement();
String sql = "select memberragas from windowragas where memberragas='"+name+"' and liquid_key='"+commun+"' and chabhiragas='"+password+"'";
ResultSet rs =statement.executeQuery(sql);
if(rs.next()){
System.out.println("welcome "+name+"");
HttpSession session=request.getSession();
session.setAttribute("name", name);
session.setAttribute("commun", commun);
RequestDispatcher rd = request.getRequestDispatcher("/homey");
rd.forward(request, response);
}else{
System.out.println("either ur username or password or community was wrong");
response.sendRedirect(request.getContextPath());
}
}
catch (NamingException ex) {
System.err.println(ex);
} catch (SQLException ex) {
System.err.println(ex);
}finally {
try {
if (statement != null) statement.close();
if (conn != null) conn.close(); // return to pool
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
in the doPost() i m creating the session for the first time

I believe the issue is that when you call doPost() directly from your doGet() method, the request parameters name, commun and password are not available. Hence, the authenticating SQL query fails and your else block executes.
} else {
System.out.println("either ur username or password or community was wrong");
response.sendRedirect(request.getContextPath());
}
This is effectively the same as your doGet()'s if block and hence gives an impression that your session is null.
if (session == null) {
response.sendRedirect(request.getContextPath());
}
So to fix the issue, if the session exists, redirect the user immediately instead of trying to execute doPost() to authenticate them again. The presence of name attribute can further assure that the user has been authenticated before.
if (session != null && session.getAttribute("name") != null) {
RequestDispatcher rd = request.getRequestDispatcher("/homey");
rd.forward(request, response);
} else {
response.sendRedirect(request.getContextPath());
}

Related

How to get the Access Token in Okta SSO, Getting java.io.FileNotFoundException

I am new to the Okta SSO, trying to get the Access token using below code.Am i using right API and package to do this? Please suggest, Thanks in advance
private com.microsoft.aad.adal4j.AuthenticationResult.AuthenticationResult getAccessToken(
AuthorizationCode authorizationCode, String currentUri)
throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId,
clientSecret);
com.microsoft.aad.adal4j.AuthenticationContext context = null;
com.microsoft.aad.adal4j.AuthenticationResult result = null;
java.util.concurrent.ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext("https://dev-xxxxxxx.okta.com/oauth2/oauth2/authorize", true,
service);
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} catch(InterruptedException e){
LOGGER.error(e);
} catch(MalformedURLException e){
LOGGER.error("Malformed URL :"+e);
}finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
return result;
}
10:59:05,653 ERROR AuthenticationContext:148 - [Correlation ID: cc2fccef-6c3c-4638-ae53-02d8ac2504c7] Request to acquire token failed.
java.io.FileNotFoundException: https://xxxxxx/common/discovery/instance?api-version=1.0&authorization_endpoint=https://xxxxxxxx/oauth2/oauth2/authorize
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.microsoft.aad.adal4j.HttpHelper.readResponseFromConnection(HttpHelper.java:86)
at com.microsoft.aad.adal4j.HttpHelper.getResponse(HttpHelper.java:182)
at com.microsoft.aad.adal4j.HttpHelper.executeGetRequest(HttpHelper.java:158)
at com.microsoft.aad.adal4j.HttpHelper.executeHttpGet(HttpHelper.java:59)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doDynamicInstanceDiscovery(AuthenticationAuthority.java:149)
at com.microsoft.aad.adal4j.AuthenticationAuthority.doInstanceDiscovery(AuthenticationAuthority.java:135)
at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon(AuthenticationContext.java:775)
at com.microsoft.aad.adal4j.AuthenticationContext.access$100(AuthenticationContext.java:64)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:141)
at com.microsoft.aad.adal4j.AuthenticationContext$1.call(AuthenticationContext.java:130)

Spring boot RestTemplate close connection for NULL responses results in ConnectionPoolTimeoutExceptions

We have a spring boot Application which makes RESTFul calls to a bunch of backends, one of them returns null reponses at times, and we are observing the connections are not released during these instances because of this code in RestTemplate class:
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException {
Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
handleResponse(url, method, response);
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
String resource = url.toString();
String query = url.getRawQuery();
resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + resource + "\": " + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
Is there a way we can release the connection or consume the contents for when response is null or erring out?
Edited to add code causing errors:
MyHttpClientClass{
private X getResponseBody(RestClient client, URI uri, HttpMethod method, HttpEntity<T> entity, Class<R> responseType, MyErrorHandler errorHandler) {
try
{ String host = this.getHost();
ResponseEntity<X> resp = client.exchange(uri, method, entity, responseType);
return resp.getBody();
} catch (HttpServerErrorException | HttpClientErrorException e)
{ handleHttpException(e, errorHandler);
throw e;
} catch (Exception e) {
log(e);
throw e; } } }
-----------
Class1 implements Callable<T>
{
#Override public T doCall() throws Exception {
try
{ return this.getRestClient().exchange(this.getUri(),
this.getHttpMethod(), this.getEntity(), getResponseType()).getBody(); } catch (HttpClientErrorException ex) { throw ex; } catch (HttpStatusCodeException ex) { if(this.isNeededRetry(ex)) { throw ex; }else { return generateErrorResponse(ex).getBody(); } } catch (RestClientException ex) { throw ex; } catch (Exception ex) { throw ex; } } }
----------
MySpringApplicationClass{
public X get(String api, String params, Class<R> responseType, String path, List<String> pathVariables, MyErrorHandler errorHandler)
{
return getResponseBody(...);
}}

how to convert blob data into byte array and get image from DB and send it to UI through rest api

#Override
public byte[] findByusernameAndtenantId(String username,int tenantId) throws SQLException {
Connection con=null;
Blob img ;
byte[] imgData = null ;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con=DriverManager.getConnection("jdbc:cassandra://169.46.155.77:9042/demo");
String query = "SELECT PHOTO FROM demo.IGNITE_USERS where USER_NAME=? and TENANT_ID=?";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next ())
{
img = result.getBlob(1);
imgData = img.getBytes(1,(int)img.length());
}
result.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null)
try{
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
return imgData ;
}
this is my implementation code .
#RequestMapping(value ="/Image",method = RequestMethod.POST, produces="image/jpg")
public ResponseEntity<byte[]> getImage(#RequestParam String username,#RequestParam int tenantId) throws SQLException
{
byte[] img=null;
img=authService.findByusernameAndtenantId(username,tenantId);
System.out.println("testing functionality");
return new ResponseEntity<byte[]>(img, HttpStatus.OK);
}
this is my controller code
when I run the spring boot program , and do a POST call in Postman client to get the image I am getting Class not found exception : org.apache.cassandra.cql.jdbc.Cassandra Driver.
Can you please help me how to return that image from cassandra DB stored as Blob ?

session.getAttribute returns null

I'am using jsp and servlet to realize the authentication before any access to the application
The is the code of my doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Account account;
try {
//Checking if the user already exists
account = accountBesinessLocal.findByLogin(String.valueOf(username));
if (account != null) {
logger.log(Level.WARNING, "[User exists:{0}]", username);
if (accountBesinessLocal.authentificateUser(String.valueOf(username), String.valueOf(password))) {
HttpSession session = request.getSession(true);
System.out.println(session);
session.setAttribute("username", account.getLogin());
session.setAttribute("password", account.getPassword());
System.out.println("this "+session.getAttribute(username)+" is connected");
response.sendRedirect(home.xhtml");
} else {
request.setAttribute("erreur", "Incorrect Authentication");
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} else {
request.setAttribute("erreur", "Incorrect Authentication");
logger.log(Level.WARNING, "[User does not exist:{0}]", username);
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} finally {
}
}
When i try to get the login of the user conneced with session.getAttribute(username);
it returns null.
How can i solve this?
You must use
session.getAttribute("username")
and not
session.getAttribute(username)
the value of username is whatever the user has entered in the login input field. It's not "userame".
Side note: your code doesn't compile, s you might be running code that isn't the one ou posted.

Posting HTTPS form results in html 404 status code

I keep getting a HTML 404 reply from the server when I try to login via a httppost (https). Not sure if this is a cookie problem or something else. The code should be good as I have copied it from another activity. I need some help.
This is my current code:
public int postData(String usernamne, String password) {
String url = "https://domainname.com/nclogin.submit";
HttpPost httppost = new HttpPost(url);
try {
KeyStore trusted = null;
try {
trusted = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
trusted.load(null, "".toCharArray());
MySSLSocketFactory sslf = null;
try {
sslf = new MySSLSocketFactory(trusted);
} catch (KeyManagementException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
}
sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("f_username", "myemail#address.com"));
nameValuePairs.add(new BasicNameValuePair("f_passwd", "mypassword"));
nameValuePairs.add(new BasicNameValuePair("f_method", "LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", sslf, 443));
SingleClientConnManager cm = new SingleClientConnManager(httppost.getParams(), schemeRegistry);
// NEW API WONT ALLOW THIS IN THE MAIN THREAD! hence ASYNC
DefaultHttpClient client = new DefaultHttpClient(cm, httppost.getParams());
HttpResponse result = client.execute(httppost);
// Check if server response is valid
StatusLine status = result.getStatusLine();
Log.d(TAG, "STatus" + result.getStatusLine());
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
HttpEntity entity = result.getEntity();
InputStream is = entity.getContent();
if (is != null) {
is.close(); // release connection
}
String phpsessid = "";
// cookies from another blog
// http://stackoverflow.com/questions/4224913/android-session-management
List cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d(TAG, "no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
// Log.d(TAG, "COOKIE-" + i + " " +
// cookies.get(i).toString());
if (cookies.get(i).toString().contains("PHPSESSID")) {
phpsessid = cookies.get(i).toString();
Log.d(TAG, "COOKIE FOR PHPSESSID - " + phpsessid);
}
}
} // end of blog
entity.consumeContent();
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return 1;
} // end of postData()
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
I know the url is correct, as are the name value pairs, as I can login via a query string via a browser or via wget:
https://domainname.com/nclogin.submit?f_username=myemail#email.com&f_passwd=password&f_method=LOGIN
This results in a connection established and a redirect to my dashboard page.
The HTML code (source) from the login page can be viewed
here

Resources