I am trying to make something with sessions. I have a login form which works well with MySQL database. Now I would like to have a set Session, where it says "Hello B85417" (My username). Everytime I log in I get a this message:
You put in the correct information Hellonull.
Kan anyone see what is wrong here? Best Regards from Mads
index.jsp:
<form action="LoginServlet">
Please enter your username
<input type="text" name="un"/><br>
Please enter your password
<input type="text" name="pw"/>
<input type="submit" value="submit">
</form>
from the login form you are coming to this page:
userLogged.jsp:
<body>
Hello <%= session.getAttribute("currentSessionUser") %>
The servlet who configures the login looks like this:
package ExamplePackage;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try {
UserBean user = new UserBean();
user.setUserName(request.getParameter("un"));
user.setPassword(request.getParameter("pw"));
user = UserDAO.login(user);
if (user.isValid()) {
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
response.sendRedirect("userLogged.jsp"); //logged-in page
RequestDispatcher rd = request.getRequestDispatcher("PersonalSite.jsp");
rd.include(request,response);
}
else
response.sendRedirect("invalidLogin.jsp"); //error page
}
catch (Throwable theException) {
System.out.println(theException);
}
}
}
It is working fine for me.
You should use
<%= session.getAttribute("currentSessionUser");%>
in the jsp
Request scope will ends in the LoginServlet so it wont available to next jsp. if you call directly userLogged.jsp from index.jsp then it works fine.
OR in the LoggedInServlet
we will have to forward or include the requests to the another jsp rather than redirect.
If you use request Dispatchers for that it will be best as per my knowledge.
RequestDispatcher rd = request.getRequestDispatcher("your_Jsp_name.jsp");
rd.include(request,response);
then only the http request you can get into the another jsp also from your LoginServlet.
OR
you can set these values to the session in the LoginServlet only as follows:
HttpSession session = request.getSession();
session.setAttribute("Your_KEY","Your_Value");
make sure to import javax.servlet.http.HttpSession in the ServletClass.
Related
I have a task from a company, that send me a virtual machine with everything set up. The task is that i have to create an API to retrieve Person details from the database and display it.
The problem is that when i run the application, the server returns an index.html with hello world text in it. However, when i try to change the index.html, it does not change in the browser, but when i do request through postman, i get the "updated" index.html.
What i also realised that i cannot access the API that i have created, to check if i can access APIs in the first place.
The path where the index.html returns is "http://hocalhost:8080/tutorial-applicans/"
My Service is PersonService.java:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Stateless
#Path("person")
public class PersonService{
#PersistenceContext(unitName = "de.erknrw_tutorial-applicants_pu")
private EntityManager em;
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String sayHello(){
return "Hello World!!!"
}
}
I am trying to get "Hello World!!!", but my path is wrong, when i tried "http://hocalhost:8080/tutorial-applicans/person/hello".
Might be worth mentioning that there is also a JAXRSConfiguration.java file:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Applications;
#ApplicationPath(JAXRSConfiguration.RESTROOT)
public class JAXRSConfiguration extends Application{
public static final String RESTROOT = "webresources";
}
How do access the sayHello()? How does the path look like?
Thanks in advance
When deploying on a webapp, the JAX-RS application is configured as a Servlet. So, you have to add the application path prior to the path of the resource.
The endpoint would be:
http://[server]:[port]/[context path]/[application path]/[resource path]/[operation path]
In your case:
http://hocalhost:8080/tutorial-applicans/webresources/person/hello
I'm new to JAX-RS and trying to figure out what is happening here:
I have a simple Hello World Jersey REST service running on Glassfish (Eclipse plugin). I can access it successfully from a browser.
Now, I'd like to call it from a Java class (so I can build JUnit tests around it) but I get this error on buildGet() method:
java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
Unless some magic I'm not aware of happens, I'm not packaging my service and/or client in any jar so it's not related to my application jar signature.
Anyone could explain what I'm doing wrong?
Why is the exception triggered on buildGet() metod and not on any method called before?
My main:
package com.test;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
public class HelloTest {
public static void main(String[] args)
{
Client client = ClientBuilder.newClient();
Response response = null;
try {
WebTarget webTarget = client.target("http://localhost:9595/Hello/api/ping");
Invocation helloInvocation = webTarget.request().buildGet();
response = helloInvocation.invoke();
}
catch (Throwable ex) {
System.out.println(ex.getMessage());
}
finally {
response.close();
}
}
}
My service:
package com.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("ping")
public class Hello
{
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello()
{
return "<html>" + "<title>" + "Hello" + "</title>"
+ "<body><h1>" + "Hello!!!" + "</body></h1>" + "</html>";
}
}
After struggling on this for a while, it seems that my Maven configuration had issues and some dependencies were not downloaded/built correctly. I restarted a new project, copied my source files and everything started to work as expected.
I'm trying to implement JSF authentication with PickeLink 2.6.0 (EAR, Wildfly 8.1.0), as shown in the PicketLink 'picketlink-authentication-jsf' quickstart. I provided an authentication marked with the #PicketLink annotation, but Identity.login() always returns FAILED. This is my JSF form:
<h:form>
<h:panelGrid styleClass="full">
<h:inputText value="#{loginCredentials.userId}" required="true"
pt:placeholder="Username" />
<h:inputSecret value="#{loginCredentials.password}" required="true"
pt:placeholder="Password" />
<h:commandButton value="Login" action="#{loginAction.login()}" />
</h:panelGrid>
</h:form>
This is my LoginAction bean in the WAR module:
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.picketlink.Identity;
import org.picketlink.Identity.AuthenticationResult;
import org.picketlink.credential.DefaultLoginCredentials;
#RequestScoped
#Named
public class LoginAction {
#Inject
private Identity identity;
#Inject
private DefaultLoginCredentials credentials;
protected Logger log = Logger.getLogger(this.getClass().getSimpleName());
public void login() {
this.log.info(String.format("%s => %s", this.credentials.getUserId(), this.credentials.getPassword())); // Does get printed!
AuthenticationResult result = this.identity.login();
this.log.info(result.toString());
if (AuthenticationResult.FAILED.equals(result)) {
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Authentication was unsuccessful. Please check your username and password "
+ "before trying again.", ""));
}
}
}
And my Authenticator in the EJB module:
import java.util.logging.Logger;
import javax.inject.Inject;
import org.picketlink.annotations.PicketLink;
import org.picketlink.authentication.BaseAuthenticator;
import org.picketlink.credential.DefaultLoginCredentials;
#PicketLink
public class Authenticator extends BaseAuthenticator {
#Inject
private DefaultLoginCredentials credentials;
#Inject
private ApplicationAuthenticator applicationAuthenticator;
protected Logger log = Logger.getLogger(this.getClass().getSimpleName());
#Override
public void authenticate() {
this.log.info("authenticate"); // Not printed!
this.log.info(String.format("%s => %s", this.credentials.getUserId(), this.credentials.getPassword()));
ProcessResult auth = this.applicationAuthenticator.authUser(
this.credentials.getUserId(), this.credentials.getPassword());
this.log.info(auth.toString());
if (auth.getResult()) {
this.setStatus(AuthenticationStatus.SUCCESS);
this.log.info(AuthenticationStatus.SUCCESS.toString());
} else {
this.setStatus(AuthenticationStatus.FAILURE);
this.log.info(AuthenticationStatus.FAILURE.toString());
}
}
}
Looks as if my Authenticator is not called at all. This is what I get from the log:
12:25:00,093 INFO [LoginAction] (LoginAction.java:27) defaultuser => defaultpass
12:25:00,105 INFO [idm] (DefaultPartitionManager.java:165) PLIDM001000: Bootstrapping PicketLink IDM Partition Manager
12:25:00,107 INFO [store] (AbstractIdentityStore.java:50) PLIDM001001: Initializing Identity Store [class org.picketlink.idm.file.internal.FileIdentityStore]
12:25:00,110 WARN [file] (FileDataSource.java:173) PLIDM001101: Working directory [C:\Users\JPANGA~1\AppData\Local\Temp\pl-idm] is marked to be always created. All your existing data will be lost.
12:25:00,165 INFO [file] (FileDataSource.java:180) PLIDM001100: Using working directory [C:\Users\JPANGA~1\AppData\Local\Temp\pl-idm].
12:25:00,252 INFO [LoginAction] (LoginAction.java:29) FAILED
The PicketLinks jars are at $EAR_ROOT/lib.
I read the docs at http://docs.jboss.org/picketlink/2/latest/reference/html-single/ and it looks like I'm not missing anything. Why can't I get my Authenticator to work?
After getting more familiar with CDI I realized my silly mistake (the answer wasn't in PLINK docs, but in EE docs). All I needed was to add
#Named
#RequestScoped
to the bean. It still won't work without setting the account after setting the authentication status (I missed that):
this.setStatus(AuthenticationStatus.SUCCESS);
this.setAccount(new User(username)); // <-- don't miss this!
I have exposed an api provided by a jetty server to a front-end application. I want to make sure that only the front-end application (from a certain domain) has access to that api - any other requests should be unauthorised.
What's the best best way of implementing this security feature?
Update: I have set up a CrossOriginFilter - however, I can still access the api via basic GET request from my browser.
Thanks!
Use the IPAccessHandler to setup whitelists and blacklists.
Example: this will allow 127.0.0.* and 192.168.1.* to access everything.
But 192.168.1.132 cannot access /home/* content.
package jetty.demo;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.IPAccessHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class IpAccessExample
{
public static void main(String[] args)
{
System.setProperty("org.eclipse.jetty.servlet.LEVEL","DEBUG");
System.setProperty("org.eclipse.jetty.server.handler.LEVEL","DEBUG");
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);
// Setup IPAccessHandler
IPAccessHandler ipaccess = new IPAccessHandler();
ipaccess.addWhite("127.0.0.0-255|/*");
ipaccess.addWhite("192.168.1.1-255|/*");
ipaccess.addBlack("192.168.1.132|/home/*");
server.setHandler(ipaccess);
// Setup the basic application "context" for this application at "/"
// This is also known as the handler tree (in jetty speak)
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
// make context a subordinate of ipaccess
ipaccess.setHandler(context);
// The filesystem paths we will map
String homePath = System.getProperty("user.home");
String pwdPath = System.getProperty("user.dir");
// Fist, add special pathspec of "/home/" content mapped to the homePath
ServletHolder holderHome = new ServletHolder("static-home", DefaultServlet.class);
holderHome.setInitParameter("resourceBase",homePath);
holderHome.setInitParameter("dirAllowed","true");
holderHome.setInitParameter("pathInfoOnly","true");
context.addServlet(holderHome,"/home/*");
// Lastly, the default servlet for root content
// It is important that this is last.
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("resourceBase",pwdPath);
holderPwd.setInitParameter("dirAllowed","true");
context.addServlet(holderPwd,"/");
try
{
server.start();
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}
Or alternatively, write your own Handler to filter based on some other arbitrary rule.
Such as looking for a required request header, something that your specific front-end application provides, but a browser would not.
package jetty.demo;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.HandlerWrapper;
public class BanBrowserHandler extends HandlerWrapper
{
#Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String xfe = request.getHeader("X-FrontEnd");
if ((xfe == null) || (!xfe.startsWith("MagicApp-")))
{
// not your front-end
response.sendError(HttpStatus.FORBIDDEN_403);
baseRequest.setHandled(true);
return;
}
getHandler().handle(target,baseRequest,request,response);
}
}
The class IPAccessHandler is deprecated. The InetAccessHandler is recommended.
org.eclipse.jetty.server.Server server = ...;
InetAccessHandler ipaccess = new InetAccessHandler();
ipaccess.include(clientIP);
ipaccess.setHandler(server.getHandler());
server.setHandler(ipaccess);
I have few pages in my application which run on https://localhost:8181 and few pages which run on http://localhost:8080.I want to downshift from https to http but not sure how to go about it.I know I have to use filter which manages the redirection from https to http and http to https.
I looked into this link [How to downshift from HTTPS to HTTP in your web application][1]
[1]: https://blogs.oracle.com/jluehe/entry/how_to_downshift_from_https but the link where the filters s used are broken..I do not have a clear idea as to what is supposed to be done inside the filters...
In my web.xml `
<filter>
<filter-name>Non SSL port</filter-name>
<filter-class>SSLFilter</filter-class>
<init-param>
<param-name>httpPort</param-name>
<param-value>8080</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>NON SSL pages</filter-name>
<url-pattern>/pages/success.xhtml</url-pattern>
<url-pattern>/pages/failure.xhtml</url-pattern>
<url-pattern>/pages/about.xhtml</url-pattern>
</filter-mapping>`
CAn some one guide me what needs to be done inside the filter so that the shifting between https to http is smooth.
I am using Glassfish 3.1.1 and JSF.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpsRedirectFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(request instanceof HttpServletRequest
&& response instanceof HttpServletResponse) {
HttpServletRequest httpReq = (HttpServletRequest) request;
String redirectTarget = httpReq.getRequestURL().toString();
redirectTarget = redirectTarget.replaceFirst("https", "http")
redirectTarget = redirectTarget.replaceFirst(":8443", ":8080");
redirectTarget = redirectTarget.replaceFirst("home", "home.do");
if(request.isSecure()) {
((HttpServletResponse)response).sendRedirect(redirectTarget);
} else {
chain.doFilter(request, response);
}
}
}
}