Spring 4 mvc login intercepting - spring

I am new at Spring mvc. I am working on a webpage on which users will be able to log in after they have registered and activated themselves.
I sucessfully implemented the Login part, it works fine.
I would like to check if the user has already activated his/her accout via email before the login process launches. Is it possible?
I have tried to solve it with a Login interceptor, but it seems the default "/j_spring_security_check" can not be intercepted. Except this link the interceptor works with all of the url-s.
Is it possible to intercept this default link?
My spring-security.xml
...
<http use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
<access-denied-handler error-page="/403" />
<form-login login-page="/login"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password"/>
<logout logout-success-url="/login?logout" />
<!--enable csrf protection-->
<csrf />
</http>
<authentication-manager>
<authentication-provider user-service-ref="loginService" />
</authentication-manager>
LoginService
#Service("loginService")
public class LoginServiceImpl implements UserDetailsService {
//It is a regular UserDetailsService nothing extra stuff and works fine
...
}
Login.jsp
....
<div id="login-box">
<span style="color: red">${message}</span>
<c:url value="/j_spring_security_check" var="loginUrl"/>
<form name='f' action="${loginUrl}" method="post">
<p>
<label for="username">Email</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<button type="submit" class="btn">Log in</button>
</form>
</div>
...
mvc-dispatcher-servlet.xml
...
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/j_spring_security_check"/>
<bean id="logininterceptor" class="org.psi.controller.LoginInterCeptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
...
LoginInterceptor
public class LoginInterCeptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//Do some check
System.out.println("some check");
return true;
}
}
Any other possible solution are welcome.

I would accomplish this by using either the locked or enabled property on the UserDetails object and let Spring handle the rest rather than trying to intercept the request. When the user confirms their email via the link you send them, flip the flag in the database to indicate the the user is either enabled or not locked.
Alternatively, if you really want to go the intercept route, what I might do is have the login form point to something other than j_spring_security_check, intercept whatever that is, and then (if desired) forward the request to j_spring_security_check. I'm not sure if you can actually override that url.

Related

Spring security redirecting to login page for authenticated urls

I am new to spring. I am creating a spring mvc app. I have a admin url "/admin/".If I login with user credentials with ROLE_ADMIN then I can access the admin page. Right now this scenario is working fine. But If I have not logged in with ROLE_ADMIN and I try to access /admin/ url spring security is redirecting me to /login page.
Here what I want to not expose to outer world that /admin/(or admin url exists) url need authentication. And I want to show default exception page or home page if someone who is not authorized try to access /admin/ url.
Also I need to have custom "/login" url like "/custom_url/" instead of "/login"
But right now I don't have any idea how to achieve this. Any help is appreciated.
applicationContext.xml
</bean>
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**"
access="hasRole('ROLE_ADMIN')" />
<security:form-login
login-page="/login"
default-target-url="/admin"
always-use-default-target="true"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<security:logout logout-success-url="/" invalidate-session="true" logout-
url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
authorities-by-username-query="SELECT
username, authority From authorities WHERE username = ?"
users-by-username-query="SELECT
username, password, enabled FROM users WHERE username = ?" />
</security:authentication-provider>
</security:authentication-manager>
Login Controller
#RequestMapping("/login")
public String login(#RequestParam(value="error", required = false) String
error, #RequestParam(value="logout",
required = false) String logout, Model model) {
if (error!=null) {
model.addAttribute("error", "Invalid username and password");
}
if(logout!=null) {
model.addAttribute("msg", "You have been logged out successfully.");
}
return "login";
}
login.jsp
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name="loginForm" action="<c:url
value="/j_spring_security_check" />" method="post">
<c:if test="${not empty error}">
<div class="error" style="color: #ff0000;">${error}</div>
</c:if>
<div class="form-group">
<label for="username">User: </label>
<input type="text" id="username" name="username"
class="form-control" />
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password"
class="form-control" />
</div>
<input type="submit" value="Submit" class="btn btn-default">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
I am using Spring security 4.
Change the authentication-failure-url="/login?error" to authentication-failure-url="/". This will redirect you to Home page.
The correct xml-snippet in applicationContext.xml is as following:
<security:form-login
login-page="/login"
default-target-url="/admin"
always-use-default-target="true"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/"
username-parameter="username"
password-parameter="password" />
Note: You can change value of authentication-failure-url attribute to an exception page as per need.

UserDetailsService is not invoked in spring security

I am trying to use spring security with two login page and configure two different http section in my spring-security.xml I also have two authentication-manager which handles authentication using custom UserDetailsService.
Below are my code snippets
spring-security.xml
<!-- http Section for Admins -->
<http auto-config="true" use-expressions="true" authentication-manager-ref="adminAuth" pattern="/admin/**">
<intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/adminLogin" default-target-url="/admin/home" authentication-failure-url="/views/homePages/adminHome" username-parameter="username"
password-parameter="password"
login-processing-url="/authenticateAdmin" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf disabled="true"/>
</http>
<authentication-manager id="adminAuth" alias="adminAuth">
<authentication-provider user-service-ref='adminAuthService'>
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
<beans:bean id="adminAuthService" class="security.AdminAuth">
</beans:bean>
<!-- http Section for Students -->
<http auto-config="true" use-expressions="true" authentication-manager-ref="studentAuth" pattern="/student/**" >
<intercept-url pattern="/**" access="hasRole('ROLE_STUDENT')" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login login-page="/studentLogin" default-target-url="/student/home" authentication-failure-url="/studentLogin" login-processing-url="/authenticateStudent" />
<logout logout-success-url="/studentLogin" />
<!-- enable csrf protection -->
<csrf disabled="true"/>
</http>
<authentication-manager id="studentAuth" alias="studentAuth">
<authentication-provider user-service-ref='studentAuthService'>
<password-encoder hash="md5" />
</authentication-provider>
</authentication-manager>
<beans:bean id="studentAuthService" class="security.StudentAuth">
</beans:bean>
UserDetailService implementor class
package security;
#Service
public class AdminAuth implements UserDetailsService {
#Autowired
AdminService adminService;
public UserDetails loadUserByUsername(String authAttribute) throws UsernameNotFoundException {
Admin admin = getAdminByUname(authAttribute);
List<SimpleGrantedAuthority> authList = new ArrayList();
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
User user = new User(authAttribute, admin.getPassword(), authList);
return user;
}
private Admin getAdminByUname(String authAttribute) {
Admin admin = adminService.getAdminbyUname(authAttribute);
return admin;
}
}
Admin login page
<h2 class="text-center">Staff Login</h2>
<form class="login-form" action="/authenticateAdmin" method="POST">
<div class="form-group">
<label for="exampleInputEmail1" class="text-uppercase">Username</label> <input type="text" class="form-control" placeholder="Email or Mobile" id="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1" class="text-uppercase">Password</label> <input type="password" class="form-control" placeholder="" id="password">
</div>
<div class="form-check">
<label class="form-check-label"> <input type="checkbox" class="form-check-input"> <small>Remember Me</small>
</label>
<button type="submit" class="btn btn-login float-right">Submit</button>
</div>
</form>
Now when I open login page enter username/password and hit login then my loadUserByUsername is not getting invoked.
What I doing wrong here.

Failed to evaluate expression with spring security

I have a Spring rest service, and I'm trying to add security to it. I followed this tutorial, but when I try to access the service directly I get the following error:
There was an unexpected error (type=Internal Server Error,
status=500). Failed to evaluate expression 'ROLE_USER'
Here's my security configuration:
webSecurityConfig.xml
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/**" access="ROLE_USER"/>
<form-login
authentication-success-handler-ref="mySuccessHandler"
authentication-failure-handler-ref="myFailureHandler"
/>
<logout />
</http>
<beans:bean id="mySuccessHandler"
class="com.eficid.cloud.security.rest.AuthenticationSuccessHandler"/>
<beans:bean id="myFailureHandler" class=
"org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="temp" password="temp" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
SpringSecurityConfig:
public class SpringSecurityConfig {
public SpringSecurityConfig() {
super();
}
}
I'm also getting this error when trying to use curl to log in:
{
"timestamp":1460399841286,
"status":403,"error":"Forbidden",
"message":"Could not verify the provided CSRF token because your session was not found.",
"path":"/spring-security-rest/login"
}
Do I need to add the csrf token manually to the command? The service has a self-signed certificate, if that makes any difference.
If you don't need CRF to be enabled, then you can disable it in webSecurityConfig.xml file like below:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/login.html" access="hasRole('ANONYMOUS')" />
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
<!-- This form is a default form that used to login
<http-basic/>
-->
<form-login login-page="/login.html"/>
<csrf disabled="true"/>
</http>
If CSRF is enabled, you have to include a _csrf.token in the page you want to login or logout.The below code needs to be added to the form:
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
You need hasRole('ROLE_USER') in the intercept-url element.
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
See the docs for the other expressions, that you can use.
Spring security blocks POST requests.
To enable it you can either:
Add after all you forms requests :
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" class="form-control" />
(For example:
<form id="computerForm" action="addComputer" method="POST">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" class="form-control" />
)
Or if you use anotation, you can allow POST directly in your code by adding the csrf().disable on your WebSecurityConfigurerAdapter (I havent found the xml equivalent yet) :
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.and().formLogin()
.csrf().disable()
;}

spring authentication: can't logout

I'm new to Spring. I can't logout with spring security.
Login works fine, and I'm following this post to implement the logout function.
but I can't make it work.
here's my spring-security.xml:
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/index" access="hasRole('ROLE_USER')" />
<security:logout logout-success-url="/index" logout-url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="matt3o" password="secret" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
and here's my index.jsp:
<c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>Welcome : ${pageContext.request.userPrincipal.name}
</c:if>
<p>Logout</p>
Please can somebody explain to me how loggin/loggout works and why my logout doesn't ?
In index.jsp I'm trying to logout in different ways, none of them works:
<!--1-->
<c:url value="/logout" var="logoutUrl" />
<form id="logout" action="${logoutUrl}" method="post" >
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
Logout
</c:if>
<br><br>
<!--2-->
logout1
<br><br>
<!--3-->
<a href='<c:url value="j_spring_security_logout" />'>logout</a>
Spring Security 4 requires a POST request to logout instead of a GET. Next to that by default it is secured using a CSFR token, which you would need to add to the form (see the javadoc).
So instead of a link use a form to invoke the logout.
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log out" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
or when using the security tag library
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log out" />
<sec:csrfInput />
</form>
See also here and here in the reference guide.
If you want to use a GET either configure the logout functionality as such that it supports GET requests (for this you need to provide an ant matcher) or by disabling CSFR which can be done by adding <sec:csfr disabled="true" /> to your xml configuration.
you can use
href="<c:url value="/logout"/>"

Call to j_spring_security_logout not working

I'm trying to setup the logut of my application with j_spring_security_logout but for some reason it's not working, I keep getting a 404 error.
I'm calling the function like this:
<img border="0" id="logout" src="./img/logout.png" />
I have in WebContent/jsp/ my application main page, and the login and logout pages are in WebContent/login/.
I've also checked this other post Problem with Spring security's logout but the solution given there is not working for me.
Here you can see 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>
And here my spring-security.xml
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-page="/login/login.jsp"
authentication-failure-url="/login/errorLogin.jsp"/>
<logout logout-success-url="/" logout-url="/login/logout.jsp" />
</http>
<beans:bean id="myAuthenticationProvider"
class="myapp.web.authentication.WSAuthenticationProvider">
</beans:bean>
<authentication-manager>
<authentication-provider ref="myAuthenticationProvider"/>
</authentication-manager>
Thanks in advance.
the logout-url refers to a virtual URL, you need not have any resource by that name. You can do either this:
<logout logout-success-url="/" logout-url="/j_spring_security_logout" />
and the link on your page like this
<c:url value="/j_spring_security_logout" var="logoutUrl" />
Log Out
OR this:
<logout logout-success-url="/" logout-url="/logout" />
and the link as follows:
<c:url value="/logout" var="logoutUrl" />
Log Out
You were mixing both thats why you were getting 404 error.
check whether csrf is enabled. If csrf enabled, need to use post method to logout, add csrf token as hidden field. then use JavaScript to post the form to logout
With spring security 4 Logout has to be done through form button. CSRF token has to be submitted along. j_spring_security_logout does not work any longer. After spending one day i got following to be working.
Step 1: In your JSP page
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post">
<input type="submit" value="Logout"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
Step 2
<security:http use-expressions="true">
<security:form-login login-page="/login" authentication-failure-url="/login?error=true" />
<security:logout logout-success-url="/login" invalidate-session="true" logout-url="/logout" />
</security:http>
Step 3 In your login controller
//Logout mapping
#RequestMapping("/logout")
public String showLoggedout(){
return "logout";
}
Step 4 You must have one logout.jsp
Important to see that it will land onto login page after logout.
<security:form-login login-page="/login" authentication-failure-url="/login?error=true" />
So this login page must be there with corresponding mappping to login.jsp or whatever to map in your controller.
also heres what your controller should look like
#RequestMapping("/logout")
public String logoutUrl(){
return "logout";
}
first set security-context.xml the following code...
<security:logout logout-success-url="/"
invalidate-session="true" />
then add this code to your jsp file..
<script>
function formSubmit() {
document.getElementById("logoutForm").submit();
}
</script>
<c:url var="logoutUrl" value="/logout" />
Logout
</li>
<form action="${logoutUrl}" method="post" id="logoutForm">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
In JAVA-BASED Spring MVC config, you have to configure it in your security config class:
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.servletApi().rolePrefix("");
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
This answer is doubled from, and is working on my case:
Spring Security Java Config not generating logout url

Resources