Implement simple authentication in Java servlet with tomcat server












1














Following the examples here and here, how I can implement simple authentication for Java servlet? The servlet is invoked via a URL which can be invoked from inside or outside the business network.



If the user is calling the url from inside the business network, then if the browser is running from an authenticated user account, or a valid network user, then the servlet should run.



If the user is calling the URL from outside the business network, then the user account must first perform authentication using forms based authentication (username/password), get a valid session ID as an authentication token, and use this token to pass it as a query parameter with the url. The token is simple a number or code that is passed as name/value pair. The servlet should check if the passed token is a valid session on the network, and it should allow or deny the request accordingly.



So basically, it's a two step process: first make sure the user calling the URL has a valid session on the network, if not, prompt him to authenticate. This step is outside the scope of this post. Let's assume that step one is done. Now, in step two, to call the servlet URL, the servlet will check if there is a valid authenticated session, if not, check if there is a session ID (token) passed in the url, and validate the session. If not, deny the request.



Below is a sample Java servlet which needs the above authentication mechanism:



package mypkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}


web.xml:



<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- To save as <CATALINA_HOME>webappshelloservletWEB-INFweb.xml -->

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>


I used to perform such authentication using ASP.NET, but I am relatively new to Java, and I need someone to point me in the right direction.










share|improve this question






















  • By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
    – Basil Bourque
    Nov 20 at 18:07
















1














Following the examples here and here, how I can implement simple authentication for Java servlet? The servlet is invoked via a URL which can be invoked from inside or outside the business network.



If the user is calling the url from inside the business network, then if the browser is running from an authenticated user account, or a valid network user, then the servlet should run.



If the user is calling the URL from outside the business network, then the user account must first perform authentication using forms based authentication (username/password), get a valid session ID as an authentication token, and use this token to pass it as a query parameter with the url. The token is simple a number or code that is passed as name/value pair. The servlet should check if the passed token is a valid session on the network, and it should allow or deny the request accordingly.



So basically, it's a two step process: first make sure the user calling the URL has a valid session on the network, if not, prompt him to authenticate. This step is outside the scope of this post. Let's assume that step one is done. Now, in step two, to call the servlet URL, the servlet will check if there is a valid authenticated session, if not, check if there is a session ID (token) passed in the url, and validate the session. If not, deny the request.



Below is a sample Java servlet which needs the above authentication mechanism:



package mypkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}


web.xml:



<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- To save as <CATALINA_HOME>webappshelloservletWEB-INFweb.xml -->

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>


I used to perform such authentication using ASP.NET, but I am relatively new to Java, and I need someone to point me in the right direction.










share|improve this question






















  • By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
    – Basil Bourque
    Nov 20 at 18:07














1












1








1







Following the examples here and here, how I can implement simple authentication for Java servlet? The servlet is invoked via a URL which can be invoked from inside or outside the business network.



If the user is calling the url from inside the business network, then if the browser is running from an authenticated user account, or a valid network user, then the servlet should run.



If the user is calling the URL from outside the business network, then the user account must first perform authentication using forms based authentication (username/password), get a valid session ID as an authentication token, and use this token to pass it as a query parameter with the url. The token is simple a number or code that is passed as name/value pair. The servlet should check if the passed token is a valid session on the network, and it should allow or deny the request accordingly.



So basically, it's a two step process: first make sure the user calling the URL has a valid session on the network, if not, prompt him to authenticate. This step is outside the scope of this post. Let's assume that step one is done. Now, in step two, to call the servlet URL, the servlet will check if there is a valid authenticated session, if not, check if there is a session ID (token) passed in the url, and validate the session. If not, deny the request.



Below is a sample Java servlet which needs the above authentication mechanism:



package mypkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}


web.xml:



<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- To save as <CATALINA_HOME>webappshelloservletWEB-INFweb.xml -->

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>


I used to perform such authentication using ASP.NET, but I am relatively new to Java, and I need someone to point me in the right direction.










share|improve this question













Following the examples here and here, how I can implement simple authentication for Java servlet? The servlet is invoked via a URL which can be invoked from inside or outside the business network.



If the user is calling the url from inside the business network, then if the browser is running from an authenticated user account, or a valid network user, then the servlet should run.



If the user is calling the URL from outside the business network, then the user account must first perform authentication using forms based authentication (username/password), get a valid session ID as an authentication token, and use this token to pass it as a query parameter with the url. The token is simple a number or code that is passed as name/value pair. The servlet should check if the passed token is a valid session on the network, and it should allow or deny the request accordingly.



So basically, it's a two step process: first make sure the user calling the URL has a valid session on the network, if not, prompt him to authenticate. This step is outside the scope of this post. Let's assume that step one is done. Now, in step two, to call the servlet URL, the servlet will check if there is a valid authenticated session, if not, check if there is a session ID (token) passed in the url, and validate the session. If not, deny the request.



Below is a sample Java servlet which needs the above authentication mechanism:



package mypkg;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the response message's MIME type
response.setContentType("text/html;charset=UTF-8");
// Allocate a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();

// Write the response message, in an HTML page
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Hello, World</title></head>");
out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
out.println("<p>Protocol: " + request.getProtocol() + "</p>");
out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request
out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
out.println("</body>");
out.println("</html>");
} finally {
out.close(); // Always close the output writer
}
}
}


web.xml:



<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- To save as <CATALINA_HOME>webappshelloservletWEB-INFweb.xml -->

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and
placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>


I used to perform such authentication using ASP.NET, but I am relatively new to Java, and I need someone to point me in the right direction.







java session authentication servlets token






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 17:54









tarekahf

3001617




3001617












  • By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
    – Basil Bourque
    Nov 20 at 18:07


















  • By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
    – Basil Bourque
    Nov 20 at 18:07
















By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
– Basil Bourque
Nov 20 at 18:07




By the way, you can more conveniently annotate your Servlet as shown here in place of a web.xml file.
– Basil Bourque
Nov 20 at 18:07

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398798%2fimplement-simple-authentication-in-java-servlet-with-tomcat-server%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53398798%2fimplement-simple-authentication-in-java-servlet-with-tomcat-server%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Ottavio Pratesi

Tricia Helfer

15 giugno