├── src └── main │ ├── webapp │ ├── index.jsp │ └── WEB-INF │ │ ├── jsp │ │ ├── admin.jsp │ │ ├── denied.jsp │ │ ├── user.jsp │ │ ├── dashboard.jsp │ │ └── login.jsp │ │ ├── spring-security.xml │ │ ├── web.xml │ │ └── applicationContext.xml │ ├── java │ └── com │ │ └── exp │ │ └── dynamicroles │ │ ├── model │ │ ├── UrlRolesBean.java │ │ ├── UserRole.java │ │ ├── RoleAction.java │ │ ├── LoggedUser.java │ │ ├── Action.java │ │ ├── User.java │ │ └── Role.java │ │ ├── controllers │ │ └── AuthenticationController.java │ │ ├── service │ │ ├── AppService.java │ │ ├── UrlCache.java │ │ ├── AuthenticationService.java │ │ └── DbFilterInvocationSecurityMetadataSource.java │ │ └── dao │ │ └── AppDAO.java │ └── resources │ ├── ehcache.xml │ ├── properties │ ├── Constants.properties │ └── Constants.properties.bak │ └── log4j.properties ├── .gitignore ├── README.md ├── db.sql └── pom.xml /src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Click here for login

4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/UrlRolesBean.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | 3 | public class UrlRolesBean { 4 | 5 | private String url; 6 | private String role; 7 | 8 | public String getUrl() { 9 | return url; 10 | } 11 | public void setUrl(String url) { 12 | this.url = url; 13 | } 14 | public String getRole() { 15 | return role; 16 | } 17 | public void setRole(String role) { 18 | this.role = role; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/admin.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 |

Admin access.

11 | Logout 12 | 13 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/denied.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 |

Access denied..for your role.....

11 | Logout 12 | 13 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/user.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 |

This page is accessible for your role

11 | Logout 12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/ehcache.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/dashboard.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 |

DashBoard accessed for both USER and ADMIN roles.


11 |

Your role is :${roles}

12 | Logout 13 |
14 | ------------------------- 15 |
16 | Click here for user role
17 | 18 | Click here for admin role 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/main/resources/properties/Constants.properties: -------------------------------------------------------------------------------- 1 | #########DATABASE CONFIGURATIONS##### 2 | ##################################### 3 | jdbc.driverClassName=com.mysql.jdbc.Driver 4 | jdbc.url=jdbc:mysql://localhost:3306/security_test?useSSL=false 5 | jdbc.username=root 6 | jdbc.password=root 7 | 8 | hibernate.DialectClass=org.hibernate.dialect.MySQLDialect 9 | hibernate.show_sql=true 10 | hibernate.format_sql=true 11 | 12 | ########################## 13 | #####Connection Pool###### 14 | ########################## 15 | acquireIncrement=5 16 | minPoolSize=5 17 | maxPoolSize=50 18 | maxIdleTime=5000 19 | c3p0.initialPoolSize=5 20 | idleConnectionTestPeriod=200 21 | checkoutTimeout=0 22 | unreturnedConnectionTimeout=600 23 | maxStatements=100 24 | maxConnectionAge=3 25 | maxIdleTimeExcessConnections=1 26 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/jsp/login.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 | pageEncoding="ISO-8859-1"%> 3 | 4 | 5 | 6 | 7 | Insert title here 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
UserName :
password :
21 | 22 |
23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/properties/Constants.properties.bak: -------------------------------------------------------------------------------- 1 | #########DATABASE CONFIGURATIONS##### 2 | ###-------Help Desk---------######### 3 | ##################################### 4 | jdbc.driverClassName=com.mysql.jdbc.Driver 5 | jdbc.url=jdbc:mysql://localhost:3306/liquer 6 | jdbc.username=root 7 | jdbc.password=root 8 | 9 | hibernate.DialectClass=org.hibernate.dialect.MySQLDialect 10 | hibernate.show_sql=true 11 | hibernate.format_sql=true 12 | 13 | ########################## 14 | #####Connection Pool###### 15 | ########################## 16 | acquireIncrement=5 17 | minPoolSize=5 18 | maxPoolSize=50 19 | maxIdleTime=5000 20 | c3p0.initialPoolSize=5 21 | idleConnectionTestPeriod=200 22 | checkoutTimeout=0 23 | unreturnedConnectionTimeout=600 24 | maxStatements=100 25 | maxConnectionAge=3 26 | maxIdleTimeExcessConnections=1 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-security-dynamic-authorization-and-authentication 2 | Avoid intercept url pattern and access dynamically by using sql query in spring security. 3 | 4 | use sql query for retriving roles of the requested URL. Generally we use intercept tag in xml along with url and roles attributes. we can avoid this tag and we can retrive those information form db. 5 | 6 | you also found custom UserDetailsService implementaion for getting authentication. 7 | 8 | Steps 9 | 10 | 1) import db.sql file into to your db.
11 | 2) import thisp project into your fav editor (eclipse).
12 | 3) specify you db properties in Constants.properties file.
13 | 4) run the porject.
14 | 15 | Database having following tables 16 | 17 | 1) User
18 | 2) Roles
19 | 3) action
20 | 4) User_roles
21 | 5) roles_actions
22 | 23 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/controllers/AuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.controllers; 2 | 3 | import org.springframework.security.core.context.SecurityContextHolder; 4 | import org.springframework.stereotype.Controller; 5 | import org.springframework.ui.Model; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RequestParam; 8 | 9 | @Controller 10 | public class AuthenticationController { 11 | 12 | @RequestMapping(value = "/login") 13 | public String login() { 14 | return "login"; 15 | } 16 | 17 | @RequestMapping(value="/denied") 18 | public String denied(){ 19 | return "denied"; 20 | } 21 | 22 | @RequestMapping(value="/userPage") 23 | public String userPage(){ 24 | return "user"; 25 | } 26 | 27 | @RequestMapping(value="/adminPage") 28 | public String adminPage(){ 29 | return "user"; 30 | } 31 | 32 | @RequestMapping(value="/dashboard") 33 | public String dashboard(Model model){ 34 | model.addAttribute("roles", SecurityContextHolder.getContext().getAuthentication().getAuthorities()); 35 | return "dashboard"; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/service/AppService.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.service; 2 | 3 | import java.util.List; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import com.exp.dynamicroles.dao.AppDAO; 12 | import com.exp.dynamicroles.model.RoleAction; 13 | import com.exp.dynamicroles.model.UrlRolesBean; 14 | import com.exp.dynamicroles.model.User; 15 | 16 | @Service 17 | public class AppService { 18 | private static final Logger logger = LoggerFactory.getLogger(AppService.class); 19 | 20 | @Autowired 21 | private UrlCache urlCache; 22 | 23 | @Autowired 24 | private AppDAO appDAO; 25 | 26 | @Transactional(readOnly=true) 27 | public User getUser(String username){ 28 | return appDAO.getUser(username); 29 | } 30 | 31 | @Transactional(readOnly=true) 32 | public void getUrlRoles(){ 33 | List roleActions=appDAO.getUrlRoles(); 34 | for (UrlRolesBean urlRolesBean : roleActions) { 35 | logger.debug("Role Name "+urlRolesBean.getRole()); 36 | logger.debug("Action Name "+urlRolesBean.getUrl()); 37 | } 38 | urlCache.mapUrlToRole(roleActions); 39 | return ; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/dao/AppDAO.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.dao; 2 | 3 | import java.awt.datatransfer.Transferable; 4 | import java.util.List; 5 | 6 | import org.hibernate.Query; 7 | import org.hibernate.SessionFactory; 8 | import org.hibernate.transform.Transformers; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Repository; 11 | 12 | import com.exp.dynamicroles.model.RoleAction; 13 | import com.exp.dynamicroles.model.UrlRolesBean; 14 | import com.exp.dynamicroles.model.User; 15 | 16 | @Repository 17 | public class AppDAO { 18 | 19 | @Autowired 20 | private SessionFactory sessionFactory; 21 | 22 | public User getUser(String username){ 23 | Query query=sessionFactory.getCurrentSession().createQuery("from User u where u.username=:username"); 24 | query.setString("username", username); 25 | List users=query.list(); 26 | if (users.size()>0) { 27 | return users.get(0); 28 | 29 | } 30 | return null; 31 | } 32 | 33 | public List getUrlRoles(){ 34 | Query query=sessionFactory.getCurrentSession().createSQLQuery("SELECT a.`NAME` AS url ,r.`ROLE_NAME` AS role FROM role r JOIN role_action ra ON r.`ROLE_ID`=ra.`ROLE_ID` JOIN ACTION a ON a.`ID`=ra.`ACTION_ID`"); 35 | query.setResultTransformer(Transformers.aliasToBean(UrlRolesBean.class)); 36 | return query.list(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/service/UrlCache.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | import org.springframework.stereotype.Component; 8 | 9 | import com.exp.dynamicroles.model.UrlRolesBean; 10 | 11 | @Component 12 | public class UrlCache { 13 | 14 | HashMap> urlRoles=new HashMap>(); 15 | 16 | public HashMap> getUrlRoles() { 17 | return this.urlRoles; 18 | } 19 | 20 | public void setUrlRoles(HashMap> urlRoles) { 21 | this.urlRoles = urlRoles; 22 | } 23 | 24 | public List getUrlRoles(String key) { 25 | return urlRoles.get(key); 26 | } 27 | 28 | /** 29 | * 30 | * @param roleActions 31 | * Maps the Url as key and List as the value. 32 | */ 33 | public void mapUrlToRole(List roleActions){ 34 | String dbUrl=null; 35 | for (UrlRolesBean urlRolesBean : roleActions) { 36 | dbUrl=urlRolesBean.getUrl(); 37 | if(this.urlRoles.containsKey(dbUrl)){ 38 | List roles=this.urlRoles.get(dbUrl); 39 | roles.add(urlRolesBean.getRole()); 40 | 41 | }else{ 42 | List roles=new ArrayList(); 43 | roles.add(urlRolesBean.getRole()); 44 | this.urlRoles.put(dbUrl, roles); 45 | } 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | // Generated Aug 5, 2015 11:46:07 AM by Hibernate Tools 4.0.0 3 | 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.GeneratedValue; 8 | import static javax.persistence.GenerationType.IDENTITY; 9 | import javax.persistence.Id; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | import javax.persistence.Table; 13 | 14 | /** 15 | * UserRole generated by hbm2java 16 | */ 17 | @Entity 18 | @Table(name = "user_role") 19 | public class UserRole implements java.io.Serializable { 20 | 21 | private Integer id; 22 | private User user; 23 | private Role role; 24 | 25 | public UserRole() { 26 | } 27 | 28 | public UserRole(User user, Role role) { 29 | this.user = user; 30 | this.role = role; 31 | } 32 | 33 | @Id 34 | @GeneratedValue(strategy = IDENTITY) 35 | @Column(name = "ID", unique = true, nullable = false) 36 | public Integer getId() { 37 | return this.id; 38 | } 39 | 40 | public void setId(Integer id) { 41 | this.id = id; 42 | } 43 | 44 | @ManyToOne(fetch = FetchType.LAZY) 45 | @JoinColumn(name = "USER_ID") 46 | public User getUser() { 47 | return this.user; 48 | } 49 | 50 | public void setUser(User user) { 51 | this.user = user; 52 | } 53 | 54 | @ManyToOne(fetch = FetchType.LAZY) 55 | @JoinColumn(name = "USER_ROLE") 56 | public Role getRole() { 57 | return this.role; 58 | } 59 | 60 | public void setRole(Role role) { 61 | this.role = role; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/RoleAction.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | // Generated Aug 5, 2015 11:46:07 AM by Hibernate Tools 4.0.0 3 | 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.GeneratedValue; 8 | import static javax.persistence.GenerationType.IDENTITY; 9 | import javax.persistence.Id; 10 | import javax.persistence.JoinColumn; 11 | import javax.persistence.ManyToOne; 12 | import javax.persistence.Table; 13 | 14 | /** 15 | * RoleAction generated by hbm2java 16 | */ 17 | @Entity 18 | @Table(name = "role_action") 19 | public class RoleAction implements java.io.Serializable { 20 | 21 | private Integer id; 22 | private Role role; 23 | private Action action; 24 | 25 | public RoleAction() { 26 | } 27 | 28 | public RoleAction(Role role, Action action) { 29 | this.role = role; 30 | this.action = action; 31 | } 32 | 33 | @Id 34 | @GeneratedValue(strategy = IDENTITY) 35 | @Column(name = "ID", unique = true, nullable = false) 36 | public Integer getId() { 37 | return this.id; 38 | } 39 | 40 | public void setId(Integer id) { 41 | this.id = id; 42 | } 43 | 44 | @ManyToOne(fetch = FetchType.LAZY) 45 | @JoinColumn(name = "ROLE_ID") 46 | public Role getRole() { 47 | return this.role; 48 | } 49 | 50 | public void setRole(Role role) { 51 | this.role = role; 52 | } 53 | 54 | @ManyToOne(fetch = FetchType.LAZY) 55 | @JoinColumn(name = "ACTION_ID") 56 | public Action getAction() { 57 | return this.action; 58 | } 59 | 60 | public void setAction(Action action) { 61 | this.action = action; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/LoggedUser.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import org.springframework.security.core.GrantedAuthority; 8 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 9 | import org.springframework.security.core.userdetails.UserDetails; 10 | /** 11 | * 12 | * @author Srinivas Nalla 13 | * 14 | */ 15 | public class LoggedUser implements UserDetails{ 16 | 17 | private User user; 18 | private List roles; 19 | 20 | public LoggedUser(User user, List roles){ 21 | this.user=user; 22 | this.roles=roles; 23 | } 24 | 25 | 26 | 27 | public Collection getAuthorities() { 28 | List authorities=new ArrayList(); 29 | for (String role : roles) { 30 | authorities.add(new SimpleGrantedAuthority(role)); 31 | } 32 | return authorities; 33 | } 34 | 35 | public String getPassword() { 36 | return user.getPassword(); 37 | } 38 | 39 | public String getUsername() { 40 | // TODO Auto-generated method stub 41 | return user.getPassword(); 42 | } 43 | 44 | public boolean isAccountNonExpired() { 45 | // TODO Auto-generated method stub 46 | return true; 47 | } 48 | 49 | public boolean isAccountNonLocked() { 50 | // TODO Auto-generated method stub 51 | return true; 52 | } 53 | 54 | public boolean isCredentialsNonExpired() { 55 | // TODO Auto-generated method stub 56 | return true; 57 | } 58 | 59 | public boolean isEnabled() { 60 | // TODO Auto-generated method stub 61 | return true; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/Action.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | // Generated Aug 5, 2015 11:46:07 AM by Hibernate Tools 4.0.0 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.FetchType; 9 | import javax.persistence.GeneratedValue; 10 | import static javax.persistence.GenerationType.IDENTITY; 11 | import javax.persistence.Id; 12 | import javax.persistence.OneToMany; 13 | import javax.persistence.Table; 14 | 15 | /** 16 | * Action generated by hbm2java 17 | */ 18 | @Entity 19 | @Table(name = "action") 20 | public class Action implements java.io.Serializable { 21 | 22 | private Integer id; 23 | private String name; 24 | private Set roleActions = new HashSet(0); 25 | 26 | public Action() { 27 | } 28 | 29 | public Action(String name, Set roleActions) { 30 | this.name = name; 31 | this.roleActions = roleActions; 32 | } 33 | 34 | @Id 35 | @GeneratedValue(strategy = IDENTITY) 36 | @Column(name = "ID", unique = true, nullable = false) 37 | public Integer getId() { 38 | return this.id; 39 | } 40 | 41 | public void setId(Integer id) { 42 | this.id = id; 43 | } 44 | 45 | @Column(name = "NAME", length = 150) 46 | public String getName() { 47 | return this.name; 48 | } 49 | 50 | public void setName(String name) { 51 | this.name = name; 52 | } 53 | 54 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "action") 55 | public Set getRoleActions() { 56 | return this.roleActions; 57 | } 58 | 59 | public void setRoleActions(Set roleActions) { 60 | this.roleActions = roleActions; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Root logger option 2 | #log4j.rootLogger=debug, stdout 3 | # Direct log messages to stdout 4 | #log4j.appender.stdout=org.apache.log4j.ConsoleAppender 5 | #log4j.appender.stdout.Target=System.out 6 | #log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 7 | #log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 8 | 9 | #log4j.category.org.springframework = info 10 | #log4j.category.org.hibernate = info 11 | 12 | 13 | # Root logger option {file, stdout} 14 | log4j.rootLogger=DEBUG, RollingAppender, stdout 15 | 16 | # Direct log messages to a log file 17 | log4j.appender.RollingAppender=org.apache.log4j.DailyRollingFileAppender 18 | log4j.appender.RollingAppender.File=/home/apedpcl/app.log 19 | log4j.appender.RollingAppender.DatePattern='.'yyyy-MM-dd 20 | log4j.appender.RollingAppender.layout=org.apache.log4j.PatternLayout 21 | log4j.appender.RollingAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n 22 | 23 | # Direct log messages to stdout 24 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 25 | log4j.appender.stdout.Target=System.out 26 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 27 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 28 | 29 | log4j.category.org.springframework = info 30 | log4j.category.com.mchange=warn 31 | # logs the SQL statements 32 | #log4j.logger.org.hibernate.SQL=debug 33 | 34 | # Some more useful loggings 35 | # Logs SQL statements for id generation 36 | #log4j.logger.org.hibernate.id=info 37 | # Logs the JDBC-Parameter which are passed to a query (very verboose) 38 | #log4j.logger.org.hibernate.type=debug 39 | # Logs cache related activities 40 | #log4j.logger.org.hibernate.cache=debug 41 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/service/AuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.stereotype.Service; 14 | import org.springframework.transaction.annotation.Transactional; 15 | 16 | import com.exp.dynamicroles.model.LoggedUser; 17 | import com.exp.dynamicroles.model.User; 18 | import com.exp.dynamicroles.model.UserRole; 19 | /** 20 | * 21 | * @author Srinivas Nalla 22 | * 23 | */ 24 | @Service 25 | @Transactional 26 | public class AuthenticationService implements UserDetailsService{ 27 | private static final Logger logger = LoggerFactory.getLogger(AuthenticationService.class); 28 | 29 | @Autowired 30 | private AppService appService; 31 | 32 | public UserDetails loadUserByUsername(String username) 33 | throws UsernameNotFoundException { 34 | User user=appService.getUser(username); 35 | if(user==null){ 36 | throw new UsernameNotFoundException("User doesn`t exist"); 37 | } 38 | 39 | //Fetching User roles form DB. 40 | Set userRoles=user.getUserRoles(); 41 | List dbRoles=new ArrayList(); 42 | for (UserRole userRole : userRoles) { 43 | dbRoles.add(userRole.getRole().getRoleName()); 44 | } 45 | logger.debug("Roles of :"+username+" is "+dbRoles); 46 | 47 | // pass user object and roles to LoggedUser 48 | LoggedUser loggedUser=new LoggedUser(user, dbRoles); 49 | return loggedUser; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/spring-security.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/User.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | // Generated Aug 5, 2015 11:46:07 AM by Hibernate Tools 4.0.0 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.FetchType; 9 | import javax.persistence.GeneratedValue; 10 | import static javax.persistence.GenerationType.IDENTITY; 11 | import javax.persistence.Id; 12 | import javax.persistence.OneToMany; 13 | import javax.persistence.Table; 14 | import javax.persistence.UniqueConstraint; 15 | 16 | /** 17 | * User generated by hbm2java 18 | */ 19 | @Entity 20 | @Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "USERNAME")) 21 | public class User implements java.io.Serializable { 22 | 23 | private Integer id; 24 | private String username; 25 | private String password; 26 | private Set userRoles = new HashSet(0); 27 | 28 | public User() { 29 | } 30 | 31 | public User(String username, String password, Set userRoles) { 32 | this.username = username; 33 | this.password = password; 34 | this.userRoles = userRoles; 35 | } 36 | 37 | @Id 38 | @GeneratedValue(strategy = IDENTITY) 39 | @Column(name = "ID", unique = true, nullable = false) 40 | public Integer getId() { 41 | return this.id; 42 | } 43 | 44 | public void setId(Integer id) { 45 | this.id = id; 46 | } 47 | 48 | @Column(name = "USERNAME", unique = true, length = 50) 49 | public String getUsername() { 50 | return this.username; 51 | } 52 | 53 | public void setUsername(String username) { 54 | this.username = username; 55 | } 56 | 57 | @Column(name = "PASSWORD", length = 50) 58 | public String getPassword() { 59 | return this.password; 60 | } 61 | 62 | public void setPassword(String password) { 63 | this.password = password; 64 | } 65 | 66 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") 67 | public Set getUserRoles() { 68 | return this.userRoles; 69 | } 70 | 71 | public void setUserRoles(Set userRoles) { 72 | this.userRoles = userRoles; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.model; 2 | // Generated Aug 5, 2015 11:46:07 AM by Hibernate Tools 4.0.0 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.FetchType; 9 | import javax.persistence.GeneratedValue; 10 | import static javax.persistence.GenerationType.IDENTITY; 11 | import javax.persistence.Id; 12 | import javax.persistence.OneToMany; 13 | import javax.persistence.Table; 14 | 15 | /** 16 | * Role generated by hbm2java 17 | */ 18 | @Entity 19 | @Table(name = "role") 20 | public class Role implements java.io.Serializable { 21 | 22 | private Integer roleId; 23 | private String roleName; 24 | private Set userRoles = new HashSet(0); 25 | private Set roleActions = new HashSet(0); 26 | 27 | public Role() { 28 | } 29 | 30 | public Role(String roleName, Set userRoles, 31 | Set roleActions) { 32 | this.roleName = roleName; 33 | this.userRoles = userRoles; 34 | this.roleActions = roleActions; 35 | } 36 | 37 | @Id 38 | @GeneratedValue(strategy = IDENTITY) 39 | @Column(name = "ROLE_ID", unique = true, nullable = false) 40 | public Integer getRoleId() { 41 | return this.roleId; 42 | } 43 | 44 | public void setRoleId(Integer roleId) { 45 | this.roleId = roleId; 46 | } 47 | 48 | @Column(name = "ROLE_NAME", length = 20) 49 | public String getRoleName() { 50 | return this.roleName; 51 | } 52 | 53 | public void setRoleName(String roleName) { 54 | this.roleName = roleName; 55 | } 56 | 57 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "role") 58 | public Set getUserRoles() { 59 | return this.userRoles; 60 | } 61 | 62 | public void setUserRoles(Set userRoles) { 63 | this.userRoles = userRoles; 64 | } 65 | 66 | @OneToMany(fetch = FetchType.LAZY, mappedBy = "role") 67 | public Set getRoleActions() { 68 | return this.roleActions; 69 | } 70 | 71 | public void setRoleActions(Set roleActions) { 72 | this.roleActions = roleActions; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/exp/dynamicroles/service/DbFilterInvocationSecurityMetadataSource.java: -------------------------------------------------------------------------------- 1 | package com.exp.dynamicroles.service; 2 | 3 | import java.util.Collection; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.InitializingBean; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.security.access.ConfigAttribute; 12 | import org.springframework.security.access.SecurityConfig; 13 | import org.springframework.security.web.FilterInvocation; 14 | import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; 15 | import org.springframework.stereotype.Component; 16 | /** 17 | * 18 | * @author Srinivas Nalla 19 | * 20 | * 21 | */ 22 | @Component 23 | public class DbFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource, InitializingBean{ 24 | private static final Logger logger = LoggerFactory.getLogger(DbFilterInvocationSecurityMetadataSource.class); 25 | 26 | @Autowired 27 | private AppService appService; 28 | 29 | @Autowired 30 | private UrlCache urlCache; 31 | 32 | private HashMap> urlRoles; 33 | 34 | public Collection getAttributes(Object object) 35 | throws IllegalArgumentException { 36 | FilterInvocation fi=(FilterInvocation)object; 37 | String url=fi.getRequestUrl(); 38 | logger.debug("Request Url====>"+url); 39 | 40 | List roles_=urlRoles.get(url); 41 | logger.debug("Url Associated Roles :"+roles_); 42 | if(roles_==null){ 43 | return null; 44 | } 45 | logger.debug("------------------"); 46 | String[] stockArr = new String[roles_.size()]; 47 | stockArr = roles_.toArray(stockArr); 48 | 49 | return SecurityConfig.createList(stockArr); 50 | } 51 | 52 | public Collection getAllConfigAttributes() { 53 | return null; 54 | } 55 | 56 | public boolean supports(Class clazz) { 57 | return true; 58 | } 59 | 60 | public void afterPropertiesSet() throws Exception { 61 | 62 | appService.getUrlRoles(); 63 | this.urlRoles=urlCache.getUrlRoles(); 64 | logger.debug("Url Roles object :"+urlRoles); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | spring-dynamic-roles 4 | 5 | index.jsp 6 | 7 | 8 | 9 | contextConfigLocation 10 | /WEB-INF/applicationContext.xml,/WEB-INF/spring-security.xml 11 | 12 | 13 | org.springframework.web.context.ContextLoaderListener 14 | 15 | 16 | 17 | 18 | org.springframework.security.web.session.HttpSessionEventPublisher 19 | 20 | 21 | springSecurityFilterChain 22 | 23 | org.springframework.web.filter.DelegatingFilterProxy 24 | 25 | 26 | 27 | springSecurityFilterChain 28 | /* 29 | 30 | 31 | 32 | login 33 | 34 | org.springframework.web.servlet.DispatcherServlet 35 | 36 | contextConfigLocation 37 | 38 | 39 | 40 | 1 41 | 42 | 43 | 44 | login 45 | / 46 | 47 | 48 | 49 | 50 | OpenSessionInViewFilter 51 | org.springframework.orm.hibernate4.support.OpenSessionInViewFilter 52 | 53 | 54 | 55 | OpenSessionInViewFilter 56 | /* 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /db.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SQLyog Ultimate v10.00 Beta1 3 | MySQL - 5.5.29 : Database - security_test 4 | ********************************************************************* 5 | */ 6 | 7 | /*!40101 SET NAMES utf8 */; 8 | 9 | /*!40101 SET SQL_MODE=''*/; 10 | 11 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 12 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 13 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 14 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 15 | CREATE DATABASE /*!32312 IF NOT EXISTS*/`security_test` /*!40100 DEFAULT CHARACTER SET latin1 */; 16 | 17 | USE `security_test`; 18 | 19 | /*Table structure for table `action` */ 20 | 21 | CREATE TABLE `action` ( 22 | `ID` int(11) NOT NULL AUTO_INCREMENT, 23 | `NAME` varchar(150) DEFAULT NULL, 24 | PRIMARY KEY (`ID`) 25 | ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; 26 | 27 | /*Data for the table `action` */ 28 | 29 | insert into `action`(`ID`,`NAME`) values (1,'/userPage'); 30 | insert into `action`(`ID`,`NAME`) values (2,'/adminPage'); 31 | insert into `action`(`ID`,`NAME`) values (3,'/dashboard'); 32 | 33 | /*Table structure for table `role` */ 34 | 35 | CREATE TABLE `role` ( 36 | `ROLE_ID` int(11) NOT NULL AUTO_INCREMENT, 37 | `ROLE_NAME` varchar(20) DEFAULT NULL, 38 | PRIMARY KEY (`ROLE_ID`) 39 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; 40 | 41 | /*Data for the table `role` */ 42 | 43 | insert into `role`(`ROLE_ID`,`ROLE_NAME`) values (1,'ROLE_ADMIN'); 44 | insert into `role`(`ROLE_ID`,`ROLE_NAME`) values (2,'ROLE_USER'); 45 | 46 | /*Table structure for table `role_action` */ 47 | 48 | CREATE TABLE `role_action` ( 49 | `ID` int(11) NOT NULL AUTO_INCREMENT, 50 | `ROLE_ID` int(11) DEFAULT NULL, 51 | `ACTION_ID` int(11) DEFAULT NULL, 52 | PRIMARY KEY (`ID`), 53 | KEY `ROLE_ID` (`ROLE_ID`), 54 | KEY `ACTION_ID` (`ACTION_ID`), 55 | CONSTRAINT `role_action_ibfk_1` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ROLE_ID`), 56 | CONSTRAINT `role_action_ibfk_2` FOREIGN KEY (`ACTION_ID`) REFERENCES `action` (`ID`) 57 | ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1; 58 | 59 | /*Data for the table `role_action` */ 60 | 61 | insert into `role_action`(`ID`,`ROLE_ID`,`ACTION_ID`) values (1,1,2); 62 | insert into `role_action`(`ID`,`ROLE_ID`,`ACTION_ID`) values (2,2,1); 63 | insert into `role_action`(`ID`,`ROLE_ID`,`ACTION_ID`) values (3,1,3); 64 | insert into `role_action`(`ID`,`ROLE_ID`,`ACTION_ID`) values (7,2,3); 65 | 66 | /*Table structure for table `user` */ 67 | 68 | CREATE TABLE `user` ( 69 | `ID` int(11) NOT NULL AUTO_INCREMENT, 70 | `USERNAME` varchar(50) DEFAULT NULL, 71 | `PASSWORD` varchar(50) DEFAULT NULL, 72 | PRIMARY KEY (`ID`), 73 | UNIQUE KEY `USERNAME` (`USERNAME`) 74 | ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; 75 | 76 | /*Data for the table `user` */ 77 | 78 | insert into `user`(`ID`,`USERNAME`,`PASSWORD`) values (1,'srinivas','srinivas'); 79 | insert into `user`(`ID`,`USERNAME`,`PASSWORD`) values (2,'rajesh','rajesh'); 80 | insert into `user`(`ID`,`USERNAME`,`PASSWORD`) values (4,'ben','ben'); 81 | 82 | /*Table structure for table `user_role` */ 83 | 84 | CREATE TABLE `user_role` ( 85 | `ID` int(11) NOT NULL AUTO_INCREMENT, 86 | `USER_ID` int(11) DEFAULT NULL, 87 | `USER_ROLE` int(11) DEFAULT NULL, 88 | PRIMARY KEY (`ID`), 89 | KEY `USER_ID` (`USER_ID`), 90 | KEY `USER_ROLE` (`USER_ROLE`), 91 | CONSTRAINT `user_role_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`), 92 | CONSTRAINT `user_role_ibfk_2` FOREIGN KEY (`USER_ROLE`) REFERENCES `role` (`ROLE_ID`) 93 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; 94 | 95 | /*Data for the table `user_role` */ 96 | 97 | insert into `user_role`(`ID`,`USER_ID`,`USER_ROLE`) values (1,1,1); 98 | insert into `user_role`(`ID`,`USER_ID`,`USER_ROLE`) values (2,2,2); 99 | 100 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 101 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 102 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 103 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 104 | -------------------------------------------------------------------------------- /src/main/webapp/WEB-INF/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 42 | 43 | 44 | classpath:properties/Constants.properties 45 | 46 | 47 | 48 | 49 | 50 | 52 | 53 | 54 | 55 | 56 | 57 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | ${hibernate.DialectClass} 83 | ${hibernate.show_sql} 84 | ${hibernate.format_sql} 85 | true 86 | 10 87 | true 88 | true 89 | org.hibernate.cache.ehcache.EhCacheRegionFactory 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.exp.dynamicrole 5 | spring-dynamic-role 6 | war 7 | 0.0.1-SNAPSHOT 8 | spring-dynamic-role Maven Webapp 9 | http://maven.apache.org 10 | 11 | UTF-8 12 | 4.2.11.Final 13 | 14 | 15 | 16 | junit 17 | junit 18 | 3.8.1 19 | test 20 | 21 | 22 | 23 | javax.servlet 24 | servlet-api 25 | 2.5 26 | provided 27 | 28 | 29 | 30 | javax.servlet.jsp 31 | javax.servlet.jsp-api 32 | 2.3.1 33 | 34 | 35 | 36 | javax.servlet 37 | jstl 38 | 1.2 39 | 40 | 41 | org.hibernate 42 | hibernate-entitymanager 43 | ${hibernate.version} 44 | 45 | 46 | 47 | org.hibernate 48 | hibernate-ehcache 49 | ${hibernate.version} 50 | 51 | 52 | 53 | 54 | org.springframework 55 | spring-orm 56 | 4.0.3.RELEASE 57 | 58 | 59 | 60 | org.springframework 61 | spring-webmvc 62 | 6.1.13 63 | 64 | 65 | 66 | org.springframework 67 | spring-aop 68 | 4.0.3.RELEASE 69 | 70 | 71 | 72 | 73 | org.springframework.security 74 | spring-security-core 75 | 3.2.5.RELEASE 76 | 77 | 78 | org.springframework.security 79 | spring-security-config 80 | 3.2.5.RELEASE 81 | 82 | 83 | org.springframework.security 84 | spring-security-web 85 | 3.2.5.RELEASE 86 | 87 | 88 | org.springframework.security 89 | spring-security-acl 90 | 3.2.5.RELEASE 91 | 92 | 93 | org.springframework.ws 94 | spring-oxm 95 | 1.5.10 96 | 97 | 98 | 99 | 100 | org.codehaus.jackson 101 | jackson-mapper-asl 102 | 1.9.13 103 | 104 | 105 | 106 | org.aspectj 107 | aspectjweaver 108 | 1.7.4 109 | 110 | 111 | 112 | log4j 113 | log4j 114 | 1.2.17 115 | 116 | 117 | org.slf4j 118 | slf4j-log4j12 119 | 1.7.8 120 | 121 | 122 | 123 | 124 | c3p0 125 | c3p0 126 | 0.9.1.2 127 | 128 | 129 | com.googlecode.json-simple 130 | json-simple 131 | 1.1 132 | 133 | 134 | 135 | 136 | spring-dynamic-role 137 | 138 | 139 | --------------------------------------------------------------------------------