Thursday 19 November 2015

Spring Security Implementation in Project

Step-1 

Add dependency for Spring Security inside the pom.xml

<!-- Below two dependency are for Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>

</dependency>

Step-2
Configure the filter for spring security

         <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> 


Note : springSecurityFilterChain -> filter name we cannot change since this is the name of
of spring bean which is responsible for spring security.


Step-3
Design Login Page for Spring Security

URI to open this page...............

login-page="/bank/auth"

@RequestMapping(value = "/auth", method = RequestMethod.GET)
public String auth(Model model,HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
System.out.println("_____userAgent____  = "+userAgent);
model.addAttribute("applicationMessage",
"Please Log in using your credentials!");
return NavigationConstant.COMMON_PAGE +
               NavigationConstant.LOGIN_PAGE;

}

 <form method="post" action="../j_spring_security_check">
        <p><input type="text" name="j_username"  id="loginId" value="" placeholder="Bank userid"></p>
        <p><input type="password" id="password" name="j_password" value="" placeholder="Password"></p>
        <p >
     <!--   <input type="button" name="commit" style="background: url(images/logs.jpg); width:100px; height:35px;" />         -->
     <a href="${pageContext.request.contextPath}/bank/customerRegistration">
      Sign Up 
         <button type="button" class="btn" id="signid" style="width:140px;background-color:#156AEB;color:white;">Login</button>
        </p>

      </form>



Step-4
Create Spring security meta configuration file

    <!-- <security:global-method-security pre-post-annotations="enabled" proxy-target-class="true"/>  -->              
<!-- This is where we configure Spring-Security  -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/bank/auth/denied" >

     <security:intercept-url pattern="/bank/customerRegistration" access="permitAll"/>

    <security:intercept-url pattern="/bank/lockUnlockCustomers" access="permitAll"/>
     <security:intercept-url pattern="/bank/auth" access="permitAll"/>
     <security:intercept-url pattern="/MTID/**" access="permitAll"/>
      <security:intercept-url pattern="/bank/logout" access="permitAll"/>
      <security:intercept-url pattern="/auth/register.htm" access="permitAll"/>


<security:intercept-url pattern="/bank/**" access="hasRole('admin')"/>

<security:intercept-url pattern="/bank/**" access="hasAnyRole('admin','customer')"/>
<!-- Below three are not in use so far -->
<security:intercept-url pattern="/customer/**" access="hasRole('customer')"/>
<security:intercept-url pattern="/admin/**" access="hasRole('admin')"/>
<security:intercept-url pattern="/common/**" access="hasAnyRole('admin','user')"/>

 <security:form-login login-page="/bank/auth"
authentication-failure-url="/bank/invalidLogin" 
default-target-url="/bank/homescreen.htm"/>

<security:logout 
invalidate-session="true" 
logout-success-url="/bank/auth" 
logout-url="/auth/logout.htm"/>


</security:http>


Step-5

<!-- Declare an authentication-manager to use a custom userDetailsService -->
<security:authentication-manager>
       <security:authentication-provider user-service-ref="customUserDetailsService"><!--
        <security:password-encoder ref="passwordEncoder"/>
       --></security:authentication-provider>

</security:authentication-manager>


Step-6

@Transactional(readOnly = true)
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

protected static Logger logger = Logger.getLogger(CustomUserDetailsService.class);

@Autowired
@Qualifier("BankAuthServiceImpl")
private BankAuthService bankAuthService;

/**
* Retrieves a user record containing the user's credentials and access. 
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// Declare a null Spring User
UserDetails user = null;
         try {

LoginForm loginForm=bankAuthService.findLoginDetailByUserName(username);
          
           user =  new User(
loginForm.getUserId(), 
loginForm.getPassword(),
true,
true,
true,
true,

getAuthorities(loginForm.getRole()) );
    
      }


When user object is return from this method loadUserByUsername then userid and password will be matched with html form ..

if it is not valid ????? 
authentication-failure-url="/bank/invalidLogin" 

if it is valid ????? 
default-target-url="/bank/homescreen.htm"/>

Step-7

@RequestMapping(value="homescreen.htm",method = RequestMethod.GET)
public String handleRequestInternalModel model) throws Exception {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

  //here we are accessing for logged in user
 Collection<? extends GrantedAuthority> grantedList=authentication.getAuthorities();

if(grantedList!=null && grantedList.size()>0){
        Iterator<? extends GrantedAuthority> iterator=grantedList.iterator();
        if(iterator.hasNext()){
        GrantedAuthority ga=iterator.next();
           nextPage=ga.getAuthority(); //admin,user
        }

        }



 //Here setting data inside the user session
 LoginForm dLoginForm=bankAuthService.findLoginDetailByUserName(authentication.getName());

HttpSession session=request.getSession();
    session.setAttribute(NavigationConstant.USER_SESSION_DATA,

loginForm);// Storing session information

if(nextPage.equals(RoleContant.CUSTOMER.getValue())){
return NavigationConstant.CUSTOMER_PAGE
+ NavigationConstant.CUSTOMER_HOME_PAGE;
}else{
List<String> imagePathList = bankAuthService.imageAdminSliderList();
model.addAttribute("imageList", imagePathList);
return NavigationConstant.ADMIN_PAGE
+ NavigationConstant.ADMIN_HOME_PAGE;

}

}


Step-8

HOME PAGE AFTER AUTHENTICATION

    Spring Security Flow  ->>
    

When we clicked  some other link to access the page

Example below link
http://localhost:5050/synergy-bank/bank/addImagePortfolio

    
bank/addImagePortfolio ->>

spring-security.xml

this setting will come in picture
<security:intercept-url pattern="/bank/**" access="hasAnyRole('admin','customer')"/>

So you must have either admin or customer role to access the page....
this role will be already present inside spring security when user is already authenticated

Case 1 :
When user is already authenticated
      ->>> Case a (role is valid ) ->> Access the resource 
      ->>> Case b (role is not valid ) ->> 
              Then forward request to 
                access-denied-page="/bank/auth/denied" > this logic URL


Case 3 :
When user is not authenticated
<security:form-login login-page="/bank/auth"
authentication-failure-url="/bank/invalidLogin" 

default-target-url="/bank/homescreen.htm"/>

Then you will be forwarded to
login-page="/bank/auth"  with GET command

       This is the login page




Session Timeout

web.xml

<session-config>
  <session-timeout>10</session-timeout>
 </session-config>


<security:logout 
invalidate-session="true" 
logout-success-url="/bank/auth" 
logout-url="/auth/logout.htm"/>
<security:session-management invalid-session-url="bank/auth/?invalid=true" />


Note : when use is idle for 10 minutes or more and clicks on some links to access the page
then he will fowarded to invalid-session-url="bank/auth/?invalid=true" to show the message

like " Dear user your session has expired , please login again......"

























No comments:

Post a Comment