简体   繁体   中英

adding security in Struts 2 spring application

I am developing an application with spring 3 struts 2 and hibernate. After login only i have to display the pages

It is working fine. when i testing i found the big mistake

that is i copy the url of the page which needs to display only to logged-in user and paste it in other browser means it is displaying the page without login.

 <%
    String userId= (String)session.getAttribute("userId");             
    System.out.println(userId);                        

    if(userId == null || userId.equals("") ){
        response.sendRedirect("login.jsp");
    }

%>

I have included this for all jsp. I know this is not a best practice. Is any better option available?

How would i overcome this error?

if(userId == null || userId.equals("") ){
    response.sendRedirect("login.jsp");
}

should probably have a return in there to prevent rendering the page content:

if(userId == null || userId.equals("") ){
    response.sendRedirect("login.jsp");
    return;
}

Nothing in the javadoc suggests that sendRedirect causes abrupt exit or causes the response body to not be shipped to the client.

What is probably happening is that your response contains a redirect header, but also contains the page content which you might not have meant to send.

I am still at education so do know how good is my solution , but i did not crash so hope it is correct

and it is quite similar to @muthu 's code

I had used JPA-eclipselink and Struts2

Action Class

String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password";
Query checkLoginQuery = em.createQuery(checkLogin);
checkLoginQuery.setParameter("username", loginUsername);
checkLoginQuery.setParameter("password", loginPassword);

userEntity = (UserEntity) checkLoginQuery.getSingleResult();

Map sessionMap = ActionContext.getContext().getSession();
sessionMap.put("userEntity", userEntity);

JSP -> all jsp pages have this(bug:affected if session is not killed when browser is not closed )

<%@ taglib prefix="s" uri="/struts-tags" %>
<s:if test="%{#session.userEntity == null}">
            <jsp:forward page="login.jsp"/>
</s:if>


Correct me if I am wrong

Quoting this page

Both and RequestDispatcher.forward() are what I refer to as "server-side" redirects

The response.sendRedirect() is what I call a "client-side" redirect.

so a server side forward looks more safe to me , maybe I am wrong (I am sorry if I am miss interpreting it ,not worked in real life projects yet)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM