Spring Step by Step with Spring Security part-7


Welcome again to my tutorial step by step spring.Those who are already completed
my previous tutorials, can proceed with us otherwise please take a look with my previous tutorials.


You can see my previous tutorial on form handling Form Handling on spring.


Today we work with Spring security.We need a lot of change in my previous tutorials.Then we can start...:)

First we need to change in our pom.xml file.we add following dependency in pom.xml
 
         
        
            org.springframework
            spring-context
            ${spring.version}
        

        
        
            org.springframework.security
            spring-security-web
            3.2.3.RELEASE
        

        
            org.springframework.security
            spring-security-config
            3.2.3.RELEASE
        
Then we need to some change on web.xml
 

 
        contextConfigLocation
        
            /WEB-INF/spring-security.xml
        
    

    
  dispatcher
  org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            
                /WEB-INF/dispatcher-servlet.xml
            
        
        1
 

 
  dispatcher
  /
 

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
        
    

    
        springSecurityFilterChain
        /*
    
 
Now we need to add a file where spring security context defined
 




    
        
        
        
        
        
        
        
            
        
    


    
    
        
            
            
        
    
    


I changed my previous aplication context like this.

    

    
        
        
    



Here from spring-security context we see that I add a custom Userdetail security by which we can authenticate a user
package com.flopcoder.security;

import com.flopcoder.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) {
        try {
            System.out.println("Here.......................");
            com.flopcoder.model.User domainUser = userDao.getUserByUsername(username);
            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            int roleId = 0;
            System.out.println("Come here............");
            return new User(
                    domainUser.getUserName(),
                    domainUser.getPassword(),
                    enabled,
                    accountNonExpired,
                    credentialsNonExpired,
                    accountNonLocked,
                    getAuthorities(roleId)
            );
        } catch (Exception ert) {
            ert.printStackTrace();
            return null;
        }
    }

    public Collection getAuthorities(Integer role) {
        List authList = getGrantedAuthorities(getRoles(role));
        return authList;
    }

    public List getRoles(Integer role) {
        List roles = new ArrayList();
        roles.add("ROLE_ADMIN");
        return roles;
    }

    public static List getGrantedAuthorities(List roles) {
        List authorities = new ArrayList();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }
}

Now We need a security controller that will maintain authentication process
package com.flopcoder.controller;

import com.flopcoder.model.User;
import com.flopcoder.security.CustomUserDetailService;
import com.flopcoder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Created by Flop Coder on 7/2/14.
 */
@Controller
public class SecurityController {

    @Autowired
    CustomUserDetailService customUserDetailService;

    @Autowired
    UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(User user) {
        ModelAndView ret = new ModelAndView();

        user.setName("default");
        user.setAddress("Dhaka");
        user.setMobile("default");
        user.setEmail("default");
        ret.setViewName("login");
        ret.addObject("user", user);
        return ret;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView processLogin(
            @ModelAttribute("user") User user, BindingResult result, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        if (result.hasErrors()) {
            modelAndView.setViewName("login");
            modelAndView.addObject("user", user);
            return modelAndView;
        }

        UserDetails userDetails = customUserDetailService.loadUserByUsername(user.getUserName());
        if (userDetails == null || !user.getPassword().equals(userDetails.getPassword())) {
            modelAndView.setViewName("login");
            modelAndView.addObject("message", "Wrong credential");
            modelAndView.addObject("user", user);
            return modelAndView;
        }

        try {
            Authentication tokenResult = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(tokenResult);
            if (tokenResult != null) {
                modelAndView.addObject("user",userService.getUserByUsername(user.getUserName()));
                modelAndView.setViewName("hello");
            }
        } catch (NullPointerException ert) {
            modelAndView.setViewName("login");
            modelAndView.addObject("message", "No user found for any role.Please try again...");
            modelAndView.addObject("user", user);
            return modelAndView;
        }
        return modelAndView;
    }

    @RequestMapping(value = "/access-denied", method = RequestMethod.GET)
    public ModelAndView accessDenied() {
        return new ModelAndView("access_denied");
    }
}

Now we need to modify our UserService to add a method like this.
package com.flopcoder.service;

import com.flopcoder.dao.IUserDao;
import com.flopcoder.dao.UserDao;
import com.flopcoder.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Flop Coder on 6/1/14.
 */

@Service
public class UserService implements IUserService{

    @Autowired
    IUserDao userDao;
    @Override
    public User getUserById(Integer id)
    {
        return userDao.getUserById(id);
    }

    public User save(User user)
    {
        return userDao.save(user);
    }
    @Override
    public User getUserByUsername(String username)
    {
        return userDao.getUserByUsername(username);
    }
}

and then corresponding interface
package com.flopcoder.service;

import com.flopcoder.model.User;

/**
 * Created by Flop Coder on 6/2/14.
 */
public interface IUserService {

    public User getUserById(Integer id);

    public User save(User user);

    public User getUserByUsername(String username);
}
After that we need to change corresponding dao to add a method getUserByUsername(username)
package com.flopcoder.dao;

import com.flopcoder.model.User;
import com.flopcoder.utils.DbUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

/**
 * Created by Flop Coder on 6/1/14.
 */
@Repository
public class UserDao implements IUserDao{

    @Override
    public User getUserById(Integer id) {
        User user = readbyId(id);
        return user;
    }


    @Override
    public User getUserByUsername(String username) {
        User user = readbyUsername(username);
        return user;
    }

    @Override
    public User save(User user) {

        SessionFactory sessionFactory = DbUtils.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Integer id = (Integer) session.save(user);
        user.setId(id);
        session.getTransaction().commit();
        session.close();
        return user;
    }

    private static User readbyId(Integer id) {
        SessionFactory sf = DbUtils.getSessionFactory();
        Session session = sf.openSession();

        User user = (User) session.get(User.class, id);
        session.close();
        return user;
    }

    private static User readbyUsername(String username) {
        SessionFactory sf = DbUtils.getSessionFactory();
        Session session = sf.openSession();

        Query query = session.createQuery("from User where userName = '"+username+"'");
        User user = (User) query.list().get(0);
        session.close();
        return user;
    }
}

Update Corresponding interface
package com.flopcoder.dao;

import com.flopcoder.model.User;

/**
 * Created by Flop Coder on 6/2/14.
 */
public interface IUserDao {
    public User getUserById(Integer id);

    public User getUserByUsername(String username);

    public User save(User user);
}

Here from our spring-security context we see that ROLE_ADMIN access all registration process but ROLE_MNGT can see the list of user so here from security controller we ridect page to access denied page. I add a method to UserController to map view user page
package com.flopcoder.controller;

import com.flopcoder.dao.UserDao;
import com.flopcoder.model.User;
import com.flopcoder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;

/**
 * Created by Flop Coder on 6/15/14.
 */
@Controller
@RequestMapping("/")
public class UserController {

    @Autowired
    UserService userService;
    @RequestMapping(value = "/registration/user",method = RequestMethod.GET)
    public ModelAndView register(User user)
    {
        ModelAndView ret = new ModelAndView();
        ret.setViewName("register");
        ret.addObject("user",user);
        return ret;
    }

    @RequestMapping(value = "/registration/user",method = RequestMethod.POST)
    public ModelAndView registerProcess(@ModelAttribute("user") User user)
    {
        ModelAndView ret = new ModelAndView();
        userService.save(user);
        ret.setViewName("register");
        ret.addObject("user",user);
        return ret;
    }

    @RequestMapping(value = "/view/user",method = RequestMethod.GET)
    public ModelAndView viewUser(User user)
    {
        ModelAndView ret = new ModelAndView();
        userService.save(user);
        ret.setViewName("welcome");
        ret.addObject("user",user);
        return ret;
    }
}
Now we need to add view pages I add a login page to login
**********************************login.jsp*********************************
 
    
        
    
    

    

        
        
        
        
User Name
Password
 



Here we change in register.jsp





    
    
    





SUBMIT



If we want to access registration user(User Registration) page it will redirect to me in login page like this.


After login we can register a user and also a user view page like this


but if now we want to access (User View) it will redirect to access denied page.


Now we need a access denied page to to redirect a user if he is not authenticate to view this page.
Here is access denied page.You just create a simple access_denied.jsp page
and then write simple body like this.

Access denied






Here the sounce code that you can download SpringSecurityWithFormHandling.zip. Thanks and Happy Coding...:P
Reactions

Post a Comment

0 Comments