spring+security+method+level+security+annotation+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 perform this action.
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>
|
This is allusers.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>User's List</title>
<style>
tr:first-child{
font-weight: bold;
background-color: #C6C9C4;
}
</style>
</head>
<body>
<h2>List of Users</h2>
<table>
<tr>
<td>id</td><td>First Name</td><td>Last Name</td><td>Type</td><td></td><td></td>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.type}</td>
<td><a href="<c:url value='/edit-user-${user.id}' />">edit</a></td>
<td><a href="<c:url value='/delete-user-${user.id}' />">delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<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>
<p align="center"><font color="white">Please enter username as dba and password as root123!!! This is for success scenario, perform all operations</font></p>
<p align="center"><font color="white">Please enter username as admin and password as root123!!! This is for success scenario</font></p>
<p align="center"><font color="white">Please enter username as bill and password as abc123!!! This is for success scenario</font></p>
<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 registration.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="form" uri="http://www.springframework.org/tags/form"%>
<%@ 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>User Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>User Registration Form</h2>
<form:form method="POST" modelAttribute="user">
<table>
<tr>
<td><label for="id">ID: </label> </td>
<td><form:input path="id" id="id"/></td>
</tr>
<tr>
<td><label for="firstName">First Name: </label> </td>
<td><form:input path="firstName" id="firstName"/></td>
</tr>
<tr>
<td><label for="lastName">Last Name: </label> </td>
<td><form:input path="lastName" id="lastName"/></td>
</tr>
<tr>
<td><label for="type">Type: </label> </td>
<td><form:input path="type" id="type"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update"/>
</c:when>
<c:otherwise>
<input type="submit" value="Register"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to <a href="<c:url value='/list' />">List of All Users</a>
<a href="<c:url value='/logout' />">Logout</a>
</body>
</html>
|
This is success.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>Registration Confirmation Page</title>
</head>
<body>
message : ${success}
<br/>
<br/>
Go back to <a href="<c:url value='/list' />">List of All Users</a>
<a href="<c:url value='/logout' />">Logout</a>
</body>
</html>
|
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 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.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
/**
* @author Chandra Vardhan
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
.and().formLogin().loginPage("/login")
.usernameParameter("ssoId").passwordParameter("password")
.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 java.util.List;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cv.springsecurity.model.User;
import com.cv.springsecurity.service.UserService;
/**
* @author Chandra Vardhan
*/
@Controller
public class HelloWorldController {
@Autowired
UserService service;
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listAllUsers(ModelMap model) {
List<User> users = service.findAllUsers();
model.addAttribute("users", users);
return "allusers";
}
@RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.GET)
public String editUser(@PathVariable int id, ModelMap model) {
User user = service.findById(id);
model.addAttribute("user", user);
model.addAttribute("edit", true);
return "registration";
}
@RequestMapping(value = { "/edit-user-{id}" }, method = RequestMethod.POST)
public String updateUser(User user, ModelMap model, @PathVariable int id) {
service.updateUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " updated successfully");
return "success";
}
@RequestMapping(value = { "/delete-user-{id}" }, method = RequestMethod.GET)
public String deleteUser(@PathVariable int id) {
service.deleteUser(id);
return "redirect:/list";
}
@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() {
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 = ((UserDetails)principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
} |
This is User.java file having the source code to execute business logic.
package com.cv.springsecurity.model;
/**
* @author Chandra Vardhan
*/
public class User {
private int id;
private String firstName;
private String lastName;
private String type;
public User(){
}
public User(int id, String firstName, String lastName, String type){
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 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
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.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 = (User) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id != other.id)
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", type=" + type + "]";
}
} |
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 java.util.List;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import com.cv.springsecurity.model.User;
/**
* @author Chandra Vardhan
*/
public interface UserService {
List<User> findAllUsers();
@PostAuthorize ("returnObject.type == authentication.name")
User findById(int id);
@PreAuthorize("hasRole('ADMIN')")
void updateUser(User user);
@PreAuthorize("hasRole('ADMIN') AND hasRole('DBA')")
void deleteUser(int id);
} |
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 java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.cv.springsecurity.model.User;
/**
* @author Chandra Vardhan
*/
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService{
private final static Logger LOGGER = Logger.getLogger(UserServiceImpl.class);
static List<User> users = new ArrayList<User>();
static{
users = populateUser();
}
public List<User> findAllUsers(){
return users;
}
public User findById(int id){
for(User u : users){
if(u.getId()==id){
return u;
}
}
return null;
}
public void updateUser(User user) {
LOGGER.info("Only an Admin can Update a User");
User u = findById(user.getId());
users.remove(u);
u.setFirstName(user.getFirstName());
u.setLastName(user.getLastName());
u.setType(user.getType());
users.add(u);
}
public void deleteUser(int id){
User u = findById(id);
users.remove(u);
}
private static List<User> populateUser(){
List<User> users = new ArrayList<User>();
users.add(new User(1,"Sam","Disilva","admin"));
users.add(new User(2,"Kevin","Brayn","admin"));
users.add(new User(3,"Nina","Conor","dba"));
users.add(new User(4,"Tito","Menz","dba"));
return users;
}
} |
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>SpringSecurityMethodLevelSecurityAnnotation</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringSecurityMethodLevelSecurityAnnotation</name>
<properties>
<springframework.version>4.1.6.RELEASE</springframework.version>
<springsecurity.version>4.0.1.RELEASE</springsecurity.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>
</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>SpringSecurityMethodLevelSecurityAnnotation</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>SpringSecurityMethodLevelSecurityAnnotation</finalName>
</build>
</project> |
This is employee.hbm.xml file having the spring configuration properties.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.cv.spring.mvc.hibernate.model.Employee" table="Employee_new22"> <id name="empId" column="empId" type="java.lang.Long"> <generator class="identity" /> </id> <property name="empName" column="empName" type="java.lang.String" /> <property name="empAddress" column="empAddress" type="java.lang.String" /> <property name="salary" column="salary" type="java.lang.Long" /> <property name="empAge" column="empAge" type="java.lang.Long" /> </class> </hibernate-mapping>
|
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