Thursday, 3 October 2013

Simple Login With Spring Security

Spring Security

here i have used form-login to configure spring security login.

if you want to restrict user to access all url and want to allow specific url portion then you can use do that by <intercept-url />

and using form-login we can control the user authentication filer or success.and we can display our custom login form.

when you are using <http-basic /> then web browser is displaying a log in dialog for user authentication.

To enable HTTP basic, just change “form-login” to “http-basic” tag.
Spring-security.xml
<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.0.3.xsd">
 
 
 <http>
 <intercept-url pattern="/welcome*" access="ROLE_USER" />
 
                  <!-- this is for http basic

                                  <http-basic />
                  
                  -->
 
<form-login login-page="/login" default-target-url="/welcome"
   authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
 </http>
 <authentication-manager>
    <authentication-provider>
        <user-service>
  <user name="jayesh" password="anki" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
 </authentication-manager>
 
</beans:beans>
 
 
login.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
  
<form action="j_spring_security_check" method="POST">

UserName: <input type="text" name="j_username" />
 
Password: <input type="password" name="j_password" />
 
<input type="submit" value="Login" />
 
</form>
</body>
</html>