Logging user access in alfresco log file - alfresco

I added the following line in alfresco log 4j file.
log4j.logger.org.alfresco.util.log.NDC=debug
log4j.appender.File.layout.ConversionPattern=%d{ABSOLUTE} %x %-5p [%c] %m%n
But still the log file is not logging the user login access.
How to make alfresco share to log the user login details.

Share does not support NDC logging of the username out of the box - only the repository does. However, it can easily be implemented with a filter:
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String userId = AuthenticationUtil.getUserId((HttpServletRequest) request);
NDC.remove();
if (userId != null) {
NDC.push("User:" + userId);
}
chain.doFilter(request, response);
}

Related

'Same-Site=None' is set on the server, but the client cannot verify it

Set-Cookie does not work because LAX is stored as the default value when there is no SameSite value in Chrome as follows. In Firefox, it works because the default value is not LAX.
'Same-Site=None' is set on the server, but the client cannot verify it. In this situation, I want to know where the problem occurred between the client and the server and how to solve it.
[Image] Chrome Response Headers (Not Working)
[Image] Chrome Response Cookies (Not Working)
[Image] Firefox Request Headers (Working)
[Image] Server Test Result
'SameSite=None' has been added to the server as follows.
public class CookieAttributeFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse)response;
chain.doFilter(request, response);
log.info("CookieAttributeFilter");
Collection<String> headers = httpServletResponse.getHeaders(HttpHeaders.SET_COOKIE);
boolean firstHeader = true;
for (String header : headers) {
if (firstHeader) {
httpServletResponse
.setHeader(HttpHeaders.SET_COOKIE, String.format("%s;Secure;%s", header, "SameSite=" + "None"));
firstHeader = false;
continue;
}
httpServletResponse
.addHeader(HttpHeaders.SET_COOKIE, String.format("%s;Secure;%s", header, "SameSite=" + "None"));
}
}
}

Get beautified URL from HttpServletRequest

I am using the org.omnifaces.filter.HttpFilter to redirect visitors on login page when nobody is logged in.
#Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, HttpSession session, FilterChain chain) throws ServletException, IOException {
String loginUrl = "/myapp/login?redirect_url=" + req.getRequestURL();
boolean loggedIn = (req.getRemoteUser() != null);
if (loggedIn) {
chain.doFilter(req, res); // So, just continue request.
} else {
Servlets.facesRedirect(req, res, loginUrl);
}
}
I want to redirect not logged in users to /login?redirect_url=previous_page_url
The problem is that all my URLs are beautified by pretty-faces and when I try to get the previous URL with HttpServletRequest.getRequestURI(), it gives me the ugly URL.
For example, I configured an url /myapp/my-page-3 which displays /views/module1/page3.xhtml.
But HttpServletRequest.getRequestURI() is giving me /views/module1/page3.xhtml and not /myapp/my-page-3.
Any ideas ?
When the servlet based URL rewrite engine uses under the covers RequestDispatcher#forward() to forward an incoming friendly-URL request to the desired resource, then you can use request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI) to find out the original request URI.
String originalRequestURI = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
As you're already using OmniFaces, you can use Servlets#getRequestURI() to automatically detect it and return it when present, else fall back to the default HttpServletRequest#getRequestURI().
String requestURI = Servlets.getRequestURI(request);

Cannot call sendRedirect() after downloading PDF

I saw many questions like the one I am asking, but they are not exactly about what I am looking for.
I am using Command pattern, and want to create PDF-file and download it. Creating is perfect, but when I want to download it, it's starts downloading and throws an exception.
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
java.lang.IllegalStateException: getOutputStream() has already been called for this response
Here is my code from Command Pattern
#Override
public String execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException, AppException {
String fontPath = request.getServletContext().getRealPath(AppConstants.FONT_PATH);
DBManager db = DBManager.getInstance();
String ticketCode = request.getParameter("ticketCode");
String place = request.getParameter("place");
int amountTickets = Integer.valueOf(place);
String flightName = Encoding.encoding(request.getParameter("flightName"));
User user = (User) request.getSession().getAttribute("client");
String locale = (String) request.getServletContext().getAttribute("currentLocale");
db.updateFlightTickets(flightName, --amountTickets);
///////create pdf document and represent it to the byte array
ByteArrayOutputStream baos =ReportCreator.createReport(locale, fontPath, ticketCode, place, user,
db.getFlightByName(flightName));
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"Ticket\"");
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
return Path.SUCCESS;
}
Here is my "success page", sorry but can not add more, not enough reputation
<fmt:message key="success_jsp.label.success" />
And here is my servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String commandName = request.getParameter("command");
Command command = CommandContainer.get(commandName);
String forward = "";
try {
forward = command.execute(request, response);
} catch (AppException ex) {
request.setAttribute("errorMessage", ex.getMessage());
}
if (forward.equals(Path.SUCCESS)) {
response.sendRedirect(forward);
} else {
request.getRequestDispatcher(forward).forward(request, response);
}
}
Part of code in JSP, where click is calling the servlet
<td><button><fmt:message key="welcome_jsp.submit.buy_ticket" /></button></td>
How can i avoid it?
The exception says you are trying to working with the request/response once you redirect it or viceversa, and it's not valid.
Once you redirect a request, you cannot do anything else with the request/response, so getting the output stream and writing something to it is completely insane.
It's true about vice-versa situation, writing something and then redirect it will cause the browser will ignore the response data, or exception on server as I'm guessing you got.(but it depends on container)
So you either do not redirect the browser, or provide the pdf file with the target servlet/cgi where you are trying to redirect.
=================
And your current situation/problem:
Server sets the content-length, content-type,... and starts to write down some stream to the browser, since you haven't set any status, container will set default 200 OK which indicates there is some right response for the request.
Then browser will get some data(the pdf file) as 200 OK data(and consider it done), now how would you redirect the user once the response is almost done?!!?!!?!
I still do not understand why do you like to redirect a request when it's almost closed? you like to redirect the user after download complete? you cannot.

Filters not working properly

I made two filters for my auction web application. I implemented two filters, the first which performs simple logging operations, and the second, which check if the user is authorized to access a particular resource.
The troubles is that These filters work correctly only the first time I connect to the website. Infact it displays the name of the the user in the toolbar, and this happens only if you logged in correctly. Afterwards, I log out and I repeat the process, but the second filter does not work at all.
I put println statements to check if the filters are actually executed, but it isn't the case. The first filter works constantly. The strange part arises when I change the xml mapping. Infact, when I take the mapping out for both filters, the first filter continues working! I went nuts all day yesterday trying to understand this.
Weirder yet, If I rewrite the xml mapping for the filters, they work both for the first log in process, but then, once I log out and repeat the operation, the log in filter doesnt work anymore. To make my web application I am just JAVA7, netbeans 7.2 and Tomcat 7. I fear that this may be a bug with the Netbeans IDEA, but I am not sure.
The xml mapping is the following:
<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">
<filter>
<filter-name>FiltroLoggingFumettopoli</filter-name>
<filter-class>Filtri.FiltroLoggingFumettopoli</filter-class>
</filter>
<filter-mapping>
<filter-name>FiltroLoggingFumettopoli</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter>
<filter-name>FiltroLogin</filter-name>
<filter-class>Filtri.FiltroLogin</filter-class>
</filter>
<filter-mapping>
<filter-name>FiltroLogin</filter-name>
<url-pattern>/Registrato/*</url-pattern>
<servlet-name>IlMioConto</servlet-name>
<servlet-name>Vendi</servlet-name>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>**
Here is the first filter which does the logging in the log fil:
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("FiltroLoggingFumettopoli:DoBeforeProcessing");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
this.log(httpRequest.getRemoteHost()+" is trying to access page: "+httpRequest.getRequestURL()+
" il "+TimeUtility.ottieniDataOra()+". "+filterConfig.getFilterName());
System.out.println("FILTRO FILE DI LOG----> LOGGING OCCURED IN LOG FILE: "
+httpRequest.getRequestURL()+" il "+TimeUtility.ottieniDataOra()+". "+filterConfig.getFilterName());
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("FiltroLoggingFumettopoli:DoAfterProcessing");
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
doBeforeProcessing(request, response);
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
here is the filter which checks if it is an authorized user who wants access to the resources that are contained in the Registrato folder, and a few servlets:
public class FiltroLogin implements Filter
{
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
{
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request,ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession sessione = httpRequest.getSession();
ServletContext sc = filterConfig.getServletContext();
String filterName = filterConfig.getFilterName();
String servletPath = "Servlet path: " + httpRequest.getServletPath();
String url ="";
Utente user = null;
user = (Utente) sessione.getAttribute("utente");
if(user == null){
Cookie[] cookies =httpRequest.getCookies();
String email = CookieUtility.ottieniValoreCookie(cookies, "userCookie");
if(email.equalsIgnoreCase("")){
System.out.println("FILTRO LOGIN----->NESSUN COOKIE TROVATO!");
System.out.println("FILTRO LOGIN----->SERVLET CONTEXT: "+sc.getContextPath());
url ="/MostraInserzioni";
httpResponse.sendRedirect(sc.getContextPath()+url);
return;
}
else{
System.out.println("FILTRO LOGIN----->COOKIE TROVATO: "+email);
user = UtenteSql.cercaUtente(email);
System.out.println("FILTRO LOGIN----->UTENTE TROVATO: "+user.getUsername());
sessione.setAttribute("utente", user);
String salutoUtente = "Benvenuto "+user.getNome();
sessione.setAttribute("messaggio", salutoUtente);
}
}
else
System.out.println("FILTRO LOGIN----->USER FOUND: "+user.getUsername());
sc.log(httpRequest.getRemoteHost()+" cerca di accedere alla risorsa: "+httpRequest.getRequestURL()+
" il "+TimeUtility.ottieniDataOra()+". "+filterConfig.getFilterName());
System.out.println("FILTRO FILE DI LOG----> LOGGING OCCURED IN LOG FILE: "
+httpRequest.getRequestURL()+" il "+TimeUtility.ottieniDataOra()+". "+filterConfig.getFilterName());
chain.doFilter(request, response);
}
public void destroy()
{
filterConfig = null;
}
}
Simply user = sessione == null ? null : (Utente) sessione.getAttribute("utente"); and after else { just: sessione = httpRequest.getSession(true); Prevents holding sessions for non-users. – Joop Eggen yesterday
HttpSession sessione = httpRequest.getSession(false);
if (sessione == null) {
System.out.println("FILTRO LOGIN----->USER NOT FOUND IN SESSION!");
– Salvatore Servodio 44 mins ago
Then I checked the cookies. If I find the cookie i need i simply create a new session and put the USER info in the session , otherwise i simply redirect to the login page

How to isolate authentication and user registration in Java/JSP

In RegServlet class, I have a doGet() method that overrides the doStuff() method. doStuff() method takes the user input from an HTML registration form, then connects to the DB, then stores the user input into the DB.
Here is the doStuff() method in my RegServlet class:
public void doStuff(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, InstantiationException, IllegalAccessException, SQLException {
String userName = request.getParameter("userName");
...
String email = request.getParameter("email");
if(!userName.isEmpty()&&!passWord.isEmpty()) {
request.setAttribute("userName", userName);
...
request.setAttribute("email", email);
//connect to DB
toDB.createConnection();
//insert information to DB
toDB.insertNewUser(userName, passWord, lastName, firstName, age, sex, email);
RequestDispatcher view = request.getRequestDispatcher("login.jsp");
view.forward(request, response);
} else {
RequestDispatcher view = request.getRequestDispatcher("index.jsp");
view.forward(request, response);
}
If the register button is clicked after everything has been entered correctly, it leads me to a login.jsp page. I am now trying to code the log-in mechanism in order for a user (who possesses username & password stored in the DB) to log in and search and add/drop courses.
I am having a hard time because I am not sure how I should go about this.
How can I isolate user registration and authentication? Should I make another class for session management or just another method in this RegServlet class?
Implement your own HTTPServletFilter that check if a user is authenticated:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
if ("a user is authenticated") {
filterChain.doFilter(req, res);
} else {
// authenticate a user
}
}
The link show the basic of HTTPServletFilter:
http://www.oracle.com/technetwork/java/filters-137243.html#70176

Resources