Can't get Spring security "remember me" feature to work - spring

I'm new to Spring and Java. Trying to set up security remember me feature.
Here is my security.xml and login.jsp files. What am I doing wrong?
security.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"/>
<security:password-encoder ref="passwordEncoder"/>
</security:authentication-provider>
</security:authentication-manager>
<security:http use-expressions="true">
<security:intercept-url pattern="/" access="permitAll"/>
<security:intercept-url pattern="/createplayer" access="isAuthenticated()"/>
<security:intercept-url pattern="/players" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/createaccount" access="permitAll"/>
<security:intercept-url pattern="/login" access="permitAll"/>
<security:intercept-url pattern="/logout" access="permitAll"/>
<security:intercept-url pattern="/welcome" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/**" access="denyAll"/>
<security:form-login login-page="/login" authentication-failure-url="/login?error=true"/>
<security:remember-me key="MyAppKey" remember-me-parameter="remember-me"
remember-me-cookie="remember-me"
token-validity-seconds="604800"
data-source-ref="dataSource"/>
</security:http>
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
</bean>
</beans>
login.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Login</h1>
<c:if test="${param.error != null}">
Login failed. Check if username or password are correct!
</c:if>
<form action = "/login", method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Name <br>
<input name="username"/> <br>
Password<br>
<input type="password" name="password"/> <br>
Remember me <br>
<input type="checkbox" name="remember-me">
<br><br>
<input type="submit"> <br><br>
</form>
<h2>${msg}</h2>
<br>
Create account <br>
</body>
</html>
P.S. I tried adding
<session-config>
<session-timeout>1</session-timeout>
</session-config>
to web.xml to check if "remember me" works, but instead it "remembering me" it always logs out in one minute.

Add id to your jdbc-user-service
<security:jdbc-user-service data-source-ref="dataSource" id="jdbcUserService/>
and refer to your service from remember-me by it's id like this:
<security:remember-me key="MyAppKey"
user-service-ref="jdbcUserService"/>

Related

Spring POST method not working

I am a beginner in Spring Security, When i try to post a data the following error is shown:
HTTP Status 405 - Request method 'POST' not supported
My controller method is:
#RequestMapping(value="/save", method=RequestMethod.POST)
public String create(#ModelAttribute(value="employee") Employee employee,ModelMap modelMap,#PathVariable String save)
{
//Validation code start
boolean error = false;
System.out.println(employee); //Verifying if information is same as input by user
System.out.println("get");
//validation code ends
//Store the employee information in database
//manager.createNewRecord(employee);
//Mark Session Complete
return "redirect:user";
}
My Spring security configuration is:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/admin/**" access="isAuthenticated()" />
<intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/user/**" access="isAuthenticated()" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/welcome"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password"/>
<session-management>
<concurrency-control max-sessions="1" error-if-maximum-exceeded="false" />
</session-management>
<logout logout-success-url="/user" />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- Select users and user_roles from database -->
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
</beans:beans>
My jsp page is:
<%# page contentType="text/html;charset=UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>Add Employee Form</title>
<style>
.error
{
color: #ff0000;
font-weight: bold;
}
</style>
</head>
<body>
<h2><spring:message code="lbl.page" text="Add New Employee" /></h2>
<br/>
<form:form action="save?${_csrf.parameterName}=${_csrf.token}" method='POST' modelAttribute="employee">
<table>
<tr>
<td>name:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>address:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form:form>
</body>
</html>
Web.xml Spring security content is:
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping
Please give your valuable suggestions...

2 authentication managers one authentication object

I'm trying to protect a resource by defining 2 HTTP elements and 2 authentication managers. Each HTTP element has a separate form to authenticate with. The first form and HTTP element is needed to access any resource. The second form is the authenticate with more complex authentication parameters (username, password, etc)
PROBLEM: When I have authenticated with first form to access the application, this works fine as expected, but then when I try to reach the second protected resource I never get to the form as it see's I need a new role (checks the auth object and fails as the role does not exist) here's where I'm a little lost.
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<!-- Exclude public pages and static resources -->
<http pattern="/favicon.ico" security="none" />
<http pattern="/js/**" security="none" />
<http pattern="/css/**" security="none" />
<http pattern="/img/**" security="none" />
<http pattern="/test**" auto-config="true" use-expressions="true" authentication-manager-ref="smsAuthManager">
<intercept-url pattern="/test" access="hasRole('ROLE_SMS_USER')" />
<intercept-url pattern="/refreshLoginPageTuring" access="permitAll" />
<intercept-url pattern="/loginTuring" access="hasRole('USER')" />
<form-login login-page="/loginTuring"
login-processing-url="/test-login"
authentication-failure-url="/accessdenied"/>
<logout logout-url="/logout" invalidate-session="true"/>
<!-- <access-denied-handler ref="/loginTuring"/> -->
</http>
<http auto-config="true" use-expressions="true" authentication-manager-ref="userPortal">
<intercept-url pattern="/getQRCode" access="permitAll" />
<intercept-url pattern="/refreshLoginPageTuring" access="permitAll" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/accessdenied" access="permitAll" />
<intercept-url pattern="/" access="hasRole('USER')" />
<form-login login-page="/login" default-target-url="/menu"
authentication-failure-url="/accessdenied" />
<logout logout-success-url="/logout" />
<intercept-url pattern="/errors/error" access="hasRole('USER')" />
<intercept-url pattern="/menu" access="hasRole('USER')" />
</http>
<authentication-manager id="userPortal">
<authentication-provider ref="userPortalAuthenticationProvider" />
</authentication-manager>
<authentication-manager id="smsAuthManager">
<authentication-provider ref="smsAuthenticationProvider" />
</authentication-manager>
FORM:
<form id="form1" action="/test-login" method="post">
<label for="j_username"><spring:message code = "login.username" /></label>
<input id="j_username" value="${username}" name="j_username" type="text">
<label for="j_password"><spring:message code = "login.password" /></label>
<input id="j_password" value="${password}" name="j_password" type="password">
<label for="otc"><spring:message code = "login.otc" /></label>
<input id="otc" name="otc" type="password">
<button name="submit" type="submit" id="login" onclick="return validateForm()" class="btn btn-primary">Login</button>
<button name="sessionstart" type="submit" id="sessionstart" onclick="return validateAndChangeToRefreshImgAction()" class="btn">Refresh Image</button>
<br/>
<input type="hidden" name="rmShown" value="1">
<img id="scimage" style="block" src="<c:url value="/img/empty.gif" />"/>
</form>
" method="post" class="login-form">
" name="j_username" type="text">

j_spring_security_check not invoke when use specific url pattern in http element

I'm trying to implement two security realms using spring security. I am using Spring security 3.1.4 RELEASE and Spring 3.2.0 RELEASE. In my web application there are two users and they should be authenticate separately. Therefore I tried to use multiple http elements to filter url pattern and redirect to corresponding login page.
Here is my Spring-security.xml.
<beans:beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd" xmlns:beans="http://www.springframework.org/schema/beans">
<security:http pattern="/admin/**" auto-config="true" use-expressions="true">
<security:form-login login-page="/admin/login" default-target-url="/admin/dashboard"
authentication-failure-url="/admin/loginfailed"/>
<security:logout logout-success-url="/admin/logout"/>
<security:intercept-url pattern="/admin/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/admin/login" access="permitAll"/>
<security:intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')"/>
</security:http>
<security:http pattern="/customer/**" auto-config="true" use-expressions="true">
<security:form-login login-page="/customer/login" default-target-url="/customer/reports"
authentication-failure-url="/customer/loginfailed"/>
<security:logout logout-success-url="/customer/logout"/>
<security:intercept-url pattern="/customer/j_spring_security_check" access="permitAll"/>
<security:intercept-url pattern="/customer/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<security:intercept-url pattern="/customer/login" access="permitAll"/>
<security:intercept-url pattern="/customer/*" access="hasRole('ROLE_ADMIN')"/>
</security:http>
<beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName">
<beans:value>java:/myDS</beans:value>
</beans:property>
</beans:bean>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT login_name AS username, password, 1 AS enabled
FROM tbl_user WHERE login_name=?"
authorities-by-username-query="SELECT login_name , CASE role_id WHEN 2 THEN 'ROLE_USER' WHEN 1 THEN 'ROLE_ADMIN'ELSE '' END AS authority
FROM tbl_user WHERE login_name=?"
/>
</security:authentication-provider>
</security:authentication-manager>
</beans:beans>
Here is my web.xml
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Here is my login.jsp
enter code here
<c:url value="/j_spring_security_check" var="url" />
<form c role="form" action="${url}" method='POST'>
<div>
<label>Email</label>
<div >
<input type="email" name="j_username" id="inputEmail3"
placeholder="Email">
</div>
</div>
<div >
<labe>Password</label>
<div>
<input type="password" name="j_password" id="inputPassword3"
placeholder="Password">
</div>
</div>
<div class="form-group">
<div>
<button type="submit">Sign in</button>
</div>
</div>
</form>
When I remove the url patterns in the http elements, it's perfectly works. Actually I can't remove both url patterns. I tried by removing "/customer/**" and it works for customer login. But when url pattern is present, j_spring_security_check 404 not fount error occurred.
According to the spring security documentation, we can add multiple http elements with different url patterns.
Please help me to find a solution for this.
You can add as many http elements as you want, BUT you will also have to change the login-url accordingly. Currently you haven't changed anything leaving the default /j_spring_security_check in place. Whereas you want a /admin/j_spring_security_check and /customer/j_spring_security_check.
To enable this you will need to configure the login-processing-url on the <form-login /> element, just like you specified the login-page attributes. Do this for each http element.
<security:form-login login-page="/admin/login" login-processing-url="/admin/j_spring_security_check" default-target-url="/admin/dashboard" authentication-failure-url="/admin/loginfailed" />

How to show hide elements using spring security

I have a button which i want to show in login page.
So when the user is logged in i want to hide this button. I think
<sec:authorize access="isAuthenticated()">
is useful for this so i included something like following in my jsp
<sec:authorize access="not isAuthenticated()">
<div class="pull-right">
But is not visible in the login page as well as after logged in.
What can be the problem.
<http pattern="/foobar/static-wro4j/**" security="none"/>
<http pattern="/foobar/static/**" security="none"/>
<http pattern="/foobar/login*" security="none"/>
<http pattern="/foobar/syndic/**" security="none"/>
<http pattern="/foobar/register/**" security="none"/>
<http pattern="/foobar/lostpassword/**" security="none"/>
<http auto-config="true" use-expressions="true" create-session="ifRequired">
<remember-me key="foobarRememberKey" token-validity-seconds="2592000"/>
<intercept-url pattern="/foobar/presentation" access="permitAll()"/>
<intercept-url pattern="/foobar/tos" access="permitAll()"/>
<intercept-url pattern="/foobar/license" access="permitAll()"/>
<intercept-url pattern="/foobar/404-error" access="permitAll()"/>
<intercept-url pattern="/foobar/500-error" access="permitAll()"/>
<intercept-url pattern="/foobar/rest/users" method="POST" access="permitAll()"/>
<intercept-url pattern="/metrics/**" access="hasRole('ROLE_ADMIN')"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login
login-processing-url="/foobar/authentication"
login-page="/foobar/login"
authentication-failure-url="/foobar/login?action=loginFailure"
default-target-url="/foobar/"
authentication-success-handler-ref="foobarAuthenticationSuccessHandler"/>
<http-basic/>
<logout logout-url="/foobar/logout"
logout-success-url="/foobar/login"/>
<openid-login authentication-failure-url="/foobar/login?action=loginFailure"
user-service-ref="openIdAutoRegisteringUserDetailsService">
<!-- Only Google Apps is supported -->
<attribute-exchange identifier-match="https://www.google.com/.*">
<openid-attribute name="email" type="http://axschema.org/contact/email" required="true" count="1"/>
<openid-attribute name="firstname" type="http://axschema.org/namePerson/first" required="true"/>
<openid-attribute name="lastname" type="http://axschema.org/namePerson/last" required="true"/>
</attribute-exchange>
</openid-login>
</http>
Make sure you have included the Spring Security Tag Library in the JSP:
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
In your security configuration include:
<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
Then use the authorize tag:
<sec:authorize access="isAuthenticated()">
<!-- Content for Authenticated users -->
</sec:authorize>
<sec:authorize access="isAnonymous()">
<!-- Content for Unauthenticated users -->
</sec:authorize>

Spring Security: jdbc-user-query, PreparedStatementCallback

I got a problem with my query but I don't know what has caused it so I need your help =)
I got the following exception:
PreparedStatementCallback; bad SQL grammar [select USERNAME as username, PASSWORD as password, from ams.user where USERNAME=?]; nested exception is com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from ams.user where USERNAME='admin'' at line 1
Here's my login.jsp:
<div class="box">
<h1><spring:message code="login.description" /></h1>
<br/>
<form name='f' action="<c:url value='j_spring_security_check' />" method='POST'>
<ol>
<li>
<label><spring:message code="user.user" />:</label>
<em><img src="images/star_red.png" alt="required"></img></em>
<input type='text' name='j_username'>
</li>
<li>
<label><spring:message code="user.password" />:</label>
<em><img src="images/star_red.png" alt="required"></img></em>
<input type='password' name='j_password' />
</li>
<li>
<label> </label>
<input type='hidden' name='remember_me' id="remember_hidden" value="false"/>
<input type='checkbox' id='remember_checkbox' onchange="toggleRememberMe()" class="checkbox"/>
<spring:message code="login.remember" />
</li>
<li>
<label> </label>
<input type="submit" value="<spring:message code="login"/>"/>
</li>
</ol>
<br />
<br />
</form>
<c:if test="${not empty param.login_error}">
<div class="error">
<br />
<spring:message code="login.error" />
<br />
<spring:message code="login.errorReason" />:
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</div>
</c:if>
</div>
Here's my Security-Context code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- <security:http auto-config="true" access-decision-manager-ref="accessDecisionManager"> -->
<security:http auto-config="true">
<security:intercept-url pattern="/login/login.do" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/login/doLogin.do" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/lib/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/css/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/images/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/resources/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_REMEMBERED" />
<security:form-login login-page="/login/login.do" authentication-failure-url="/login/login.do?login_error=true" default-target-url="/test/showTest.do"/>
<security:logout logout-success-url="/login/login.do" invalidate-session="true" />
<security:remember-me key="rememberMe"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select USERNAME as username, PASSWORD as password, from ams.user where USERNAME=?"
authorities-by-username-query="
select distinct user.USERNAME as username, permission.NAME as authority
from ams.user, ams.user_role, ams.role, ams.role_permission, ams.permission
where user.ID=user_role.USER_ID AND user_role.ROLE_ID=role_permission.ROLE_ID AND role_permission.PERMISSION_ID=permission.ID AND user.EMAIL=?"/>
<security:password-encoder ref="passwordEncoder" />
</security:authentication-provider>
</security:authentication-manager>
<bean id="passwordEncoder"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<constructor-arg value="256" />
</bean>
</beans>
Does anyone have an idea what might have caused this error?
Would really appreciate your help on this one =)
There is a comma in the sql after password, remove that
change sql from
select USERNAME as username, PASSWORD as password, from ams.user where USERNAME=?
to
select USERNAME as username, PASSWORD as password from ams.user where USERNAME=?

Resources