Spring Security Hibernate Role Based Login Project

spring+security+hibernate+role+based+login+project

Click here to download eclipse supported ZIP file



This is accessDenied.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AccessDenied page</title>
</head>
<body>
Dear <strong>${user}</strong>, You are not authorized to access this page
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>


This is admin.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Admin page</title>
</head>
<body>
Dear <strong>${user}</strong>, Welcome to Admin Page.
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>


This is dba.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DBA page</title>
</head>
<body>
Dear <strong>${user}</strong>, Welcome to DBA Page.
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>


This is login.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
<link href="<c:url value='/static/css/bootstrap.css' />"  rel="stylesheet"></link>
<link href="<c:url value='/static/css/app.css' />" rel="stylesheet"></link>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css" />
</head>
<body>
<div id="mainWrapper">
<div class="login-container">
<div class="login-card">
<div class="login-form">
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post" class="form-horizontal">
<c:if test="${param.error != null}">
<div class="alert alert-danger">
<p>Invalid username and password.</p>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">
<p>You have been logged out successfully.</p>
</div>
</c:if>
<div class="input-group input-sm">
<label class="input-group-addon" for="username"><i class="fa fa-user"></i></label>
<input type="text" class="form-control" id="username" name="ssoId" placeholder="Enter Username" required>
</div>
<div class="input-group input-sm">
<label class="input-group-addon" for="password"><i class="fa fa-lock"></i></label> 
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" required>
</div>
<input type="hidden" name="${_csrf.parameterName}"  value="${_csrf.token}" />

<div class="form-actions">
<input type="submit"
class="btn btn-block btn-primary btn-default" value="Log in">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>


This is welcome.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome page</title>
</head>
<body>
Dear <strong>${user}</strong>, Welcome to Home Page.
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>



This is CustomSuccessHandler.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
/**
 @author Chandra Vardhan
 */
@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

  private final static Logger LOGGER = Logger.getLogger(CustomSuccessHandler.class);
  
  
  private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
  
    @Override
    protected void handle(HttpServletRequest request, 
      HttpServletResponse response, Authentication authenticationthrows IOException {
        String targetUrl = determineTargetUrl(authentication);
 
        if (response.isCommitted()) {
            LOGGER.info("Can't redirect");
            return;
        }
 
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }
    
    protected String determineTargetUrl(Authentication authentication) {
      String url="";
      
        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();
        
    List<String> roles = new ArrayList<String>();

    for (GrantedAuthority a : authorities) {
      roles.add(a.getAuthority());
    }

    if (isDba(roles)) {
      url = "/db";
    else if (isAdmin(roles)) {
      url = "/admin";
    else if (isUser(roles)) {
      url = "/home";
    else {
      url="/accessDenied";
    }

    return url;
    }
 
    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
    
  private boolean isUser(List<String> roles) {
    if (roles.contains("ROLE_USER")) {
      return true;
    }
    return false;
  }

  private boolean isAdmin(List<String> roles) {
    if (roles.contains("ROLE_ADMIN")) {
      return true;
    }
    return false;
  }

  private boolean isDba(List<String> roles) {
    if (roles.contains("ROLE_DBA")) {
      return true;
    }
    return false;
  }

}


This is HelloWorldConfiguration.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.cv.springsecurity")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {
  
  @Bean(name="HelloWorld")
  public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
  }

  /*
     * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
     *
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }
}


This is HibernateConfiguration.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.cv.springsecurity" })
@PropertySource(value = "classpath:application.properties" })
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.cv.springsecurity" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }
  
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
    
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;        
    }
    
  @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }
}


This is SecurityConfiguration.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  @Qualifier("customUserDetailsService")
  UserDetailsService userDetailsService;

  @Autowired
  CustomSuccessHandler customSuccessHandler;
  
  
  @Autowired
  public void configureGlobalSecurity(AuthenticationManagerBuilder auththrows Exception {
    auth.userDetailsService(userDetailsService);
  }
  
  @Override
  protected void configure(HttpSecurity httpthrows Exception {
    http.authorizeRequests()
      .antMatchers("/""/home").permitAll()
      .antMatchers("/""/home").access("hasRole('USER')")
      .antMatchers("/admin/**").access("hasRole('ADMIN')")
      .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
      //.and().formLogin().loginPage("/login")
      .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
      .usernameParameter("ssoId").passwordParameter("password")
      .and().csrf()
      .and().exceptionHandling().accessDeniedPage("/Access_Denied");
  }

}


This is SecurityWebApplicationInitializer.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
 @author Chandra Vardhan
 */
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}


This is SpringMvcInitializer.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.configuration;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 @author Chandra Vardhan
 */
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[] { HelloWorldConfiguration.class };
  }
 
  @Override
  protected Class<?>[] getServletConfigClasses() {
    return null;
  }
 
  @Override
  protected String[] getServletMappings() {
    return new String[] { "/" };
  }

}


This is HelloWorldController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.springsecurity.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cv.springsecurity.service.UserService;
/**
 @author Chandra Vardhan
 */
@Controller
public class HelloWorldController {
  
  @Autowired
  UserService userService;

  
  @RequestMapping(value = "/""/home" }, method = RequestMethod.GET)
  public String homePage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "welcome";
  }

  @RequestMapping(value = "/admin", method = RequestMethod.GET)
  public String adminPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "admin";
  }

  @RequestMapping(value = "/db", method = RequestMethod.GET)
  public String dbaPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "dba";
  }

  @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
  public String accessDeniedPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "accessDenied";
  }

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String loginPage(ModelMap model) {
    //INSERTING THE Values into tables
    userService.basicInsert();
    return "login";
  }

  @RequestMapping(value = "/logout", method = RequestMethod.GET)
  public String logoutPage(HttpServletRequest request,
      HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext()
        .getAuthentication();
    if (auth != null) {
      new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    return "redirect:/login?logout";
  }

  private String getPrincipal() {
    String userName = null;
    Object principal = SecurityContextHolder.getContext()
        .getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
      userName = ((UserDetailsprincipal).getUsername();
    else {      
      userName = principal.toString();
    }
    return userName;
  }

  

}


This is AbstractDao.java file having the DAO logic to access the database information.


 

    
package com.cv.springsecurity.dao;

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 @author Chandra Vardhan
 */
public abstract class AbstractDao<PK extends Serializable, T> {
  
  private final Class<T> persistentClass;
  
  @SuppressWarnings("unchecked")
  public AbstractDao(){
    this.persistentClass =(Class<T>) ((ParameterizedTypethis.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
  }
  
  @Autowired
  private SessionFactory sessionFactory;

  protected Session getSession(){
    return sessionFactory.getCurrentSession();
  }

  @SuppressWarnings("unchecked")
  public T getByKey(PK key) {
    return (TgetSession().get(persistentClass, key);
  }

  public void persist(T entity) {
    getSession().persist(entity);
  }

  public void delete(T entity) {
    getSession().delete(entity);
  }
  
  protected Criteria createEntityCriteria(){
    return getSession().createCriteria(persistentClass);
  }

}


This is UserDao.java file having the DAO logic to access the database information.


 

    
package com.cv.springsecurity.dao;

import com.cv.springsecurity.model.User;
/**
 @author Chandra Vardhan
 */
public interface UserDao {

  User findById(int id);
  
  User findBySSO(String sso);

  void basicInsert();
  
}


This is UserDaoImpl.java file having the DAO logic to access the database information.


 

    
package com.cv.springsecurity.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.cv.springsecurity.model.User;
/**
 @author Chandra Vardhan
 */
@Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao {
  private final static Logger LOGGER = Logger.getLogger(UserDaoImpl.class);
  
  public User findById(int id) {
    return getByKey(id);
  }

  public User findBySSO(String sso) {
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("ssoId", sso));
    return (Usercrit.uniqueResult();
  }

  @Override
  public void basicInsert() {
    String query = "SELECT up.TYPE,au.SSO_ID,au.STATE,au.PASSWORD FROM user_profile up,app_user au,app_user_user_profile auup WHERE up.id = au.id AND auup.user_profile_id = au.id";

    Session session = getSession();
    SQLQuery createSQLQuery = session.createSQLQuery(query);
    List list = createSQLQuery.list();
    
    String pass="password";
    String ssoId="chandra";
    String type="ADMIN";
    
    if (list == null || list.size() <= 0) {  
      String q1 = "INSERT INTO app_user(id,email,first_name,last_name,PASSWORD,sso_id,state) VALUES (101,'cvardhan.k@gmail.com','"+ssoId+"','kodam','"+pass+"','nara','ACTIVE')";
      String q2 = "INSERT INTO app_user (id,TYPE) VALUES (101,'"+type+"')";
      String q3 = "INSERT INTO user_profile (id,TYPE) VALUES (101,'"+type+"')";
      SQLQuery sqlQuery1 =session.createSQLQuery(q1);
      SQLQuery sqlQuery2 =session.createSQLQuery(q2);
      SQLQuery sqlQuery3 =session.createSQLQuery(q3);
      sqlQuery1.executeUpdate();
      sqlQuery2.executeUpdate();
      sqlQuery3.executeUpdate();      
      LOGGER.info("Please login as username : "+ssoId +" and password : "+pass );
    }

  }
}


This is State.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.model;
/**
 @author Chandra Vardhan
 */
public enum State {

  ACTIVE("ACTIVE"),
  INACTIVE("Inactive"),
  DELETED("Deleted"),
  LOCKED("Locked");
  
  private String state;
  
  private State(final String state){
    this.state = state;
  }
  
  public String getState(){
    return this.state;
  }

  @Override
  public String toString(){
    return this.state;
  }

  public String getName(){
    return this.name();
  }


}


This is User.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
/**
 @author Chandra Vardhan
 */
@Entity
@Table(name="APP_USER")
public class User {

  @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;

  @Column(name="SSO_ID", unique=true, nullable=false)
  private String ssoId;
  
  @Column(name="PASSWORD", nullable=false)
  private String password;
    
  @Column(name="FIRST_NAME", nullable=false)
  private String firstName;

  @Column(name="LAST_NAME", nullable=false)
  private String lastName;

  @Column(name="EMAIL", nullable=false)
  private String email;

  @Column(name="STATE", nullable=false)
  private String state=State.ACTIVE.getState();

  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(name = "APP_USER_USER_PROFILE"
             joinColumns = @JoinColumn(name = "USER_ID") }
             inverseJoinColumns = @JoinColumn(name = "USER_PROFILE_ID") })
  private Set<UserProfile> userProfiles = new HashSet<UserProfile>();

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getSsoId() {
    return ssoId;
  }

  public void setSsoId(String ssoId) {
    this.ssoId = ssoId;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public Set<UserProfile> getUserProfiles() {
    return userProfiles;
  }

  public void setUserProfiles(Set<UserProfile> userProfiles) {
    this.userProfiles = userProfiles;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((ssoId == null: ssoId.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof User))
      return false;
    User other = (Userobj;
    if (id != other.id)
      return false;
    if (ssoId == null) {
      if (other.ssoId != null)
        return false;
    else if (!ssoId.equals(other.ssoId))
      return false;
    return true;
  }

  @Override
  public String toString() {
    return "User [id=" + id + ", ssoId=" + ssoId + ", password=" + password
        ", firstName=" + firstName + ", lastName=" + lastName
        ", email=" + email + ", state=" + state + ", userProfiles=" + userProfiles +"]";
  }

  
}


This is UserProfile.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 @author Chandra Vardhan
 */
@Entity
@Table(name="USER_PROFILE")
public class UserProfile {

  @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int id;  

  @Column(name="TYPE", length=15, unique=true, nullable=false)
  private String type = UserProfileType.USER.getUserProfileType();
  
  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }


  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((type == null: type.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof UserProfile))
      return false;
    UserProfile other = (UserProfileobj;
    if (id != other.id)
      return false;
    if (type == null) {
      if (other.type != null)
        return false;
    else if (!type.equals(other.type))
      return false;
    return true;
  }

  @Override
  public String toString() {
    return "UserProfile [id=" + id + ",  type=" + type  + "]";
  }
  

}


This is UserProfileType.java file having the source code to execute business logic.


 

    
package com.cv.springsecurity.model;
/**
 @author Chandra Vardhan
 */
public enum UserProfileType {
  USER("USER"),
  DBA("DBA"),
  ADMIN("ADMIN");
  
  String userProfileType;
  
  private UserProfileType(String userProfileType){
    this.userProfileType = userProfileType;
  }
  
  public String getUserProfileType(){
    return userProfileType;
  }
  
}


This is CustomUserDetailsService.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.springsecurity.service;

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

import org.apache.log4j.Logger;
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.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cv.springsecurity.model.User;
import com.cv.springsecurity.model.UserProfile;
/**
 @author Chandra Vardhan
 */
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

  private final static Logger LOGGER = Logger.getLogger(CustomUserDetailsService.class);
  
  
  @Autowired
  private UserService userService;

  @Transactional(readOnly = true)
  public UserDetails loadUserByUsername(String ssoId)
      throws UsernameNotFoundException {
    User user = userService.findBySso(ssoId);
    LOGGER.info("User : " + user);
    if (user == null) {
      LOGGER.info("User not found");
      throw new UsernameNotFoundException("Username not found");
    }
    return new org.springframework.security.core.userdetails.User(
        user.getSsoId(), user.getPassword(), user.getState()
            .equalsIgnoreCase("Active"), true, true, true,
        getGrantedAuthorities(user));
  }

  @Transactional(readOnly = true)
  public User loadUser(String ssoIdthrows UsernameNotFoundException {
    User user = userService.findBySso(ssoId);
    LOGGER.info("User : " + user);
    if (user == null) {
      LOGGER.info("User not found");
      throw new UsernameNotFoundException("Username not found");
    }
    return user;
  }

  private List<GrantedAuthority> getGrantedAuthorities(User user) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (UserProfile userProfile : user.getUserProfiles()) {
      LOGGER.info("UserProfile : " + userProfile);
      authorities.add(new SimpleGrantedAuthority("ROLE_"
          + userProfile.getType()));
    }
    System.out.print("authorities : " + authorities);
    return authorities;
  }

}


This is UserService.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.springsecurity.service;

import com.cv.springsecurity.model.User;
/**
 @author Chandra Vardhan
 */
public interface UserService {

  User findById(int id);
  
  User findBySso(String sso);
  
  void basicInsert();
  
}


This is UserServiceImpl.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.springsecurity.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cv.springsecurity.dao.UserDao;
import com.cv.springsecurity.model.User;
/**
 @author Chandra Vardhan
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService{

  @Autowired
  private UserDao dao;

  public User findById(int id) {
    return dao.findById(id);
  }

  public User findBySso(String sso) {
    return dao.findBySSO(sso);
  }
  
  public void basicInsert() {
     dao.basicInsert();
  }

}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.springsecurity</groupId> <artifactId>SpringSecurityRoleBasedLogin</artifactId> <version>1.0</version> <packaging>war</packaging> <name>SpringSecurityRoleBasedLogin</name> <properties> <springframework.version>4.2.0.RELEASE</springframework.version> <springsecurity.version>4.0.1.RELEASE</springsecurity.version> <log4j-version>1.2.16</log4j-version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${springsecurity.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <artifactId>hibernate-core</artifactId> <groupId>org.hibernate</groupId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.2.0.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>SpringSecurityRoleBasedLogin</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>SpringSecurityRoleBasedLogin</finalName> </build> </project>


This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment