spring security tutorial
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
|
||||
<persistence-unit-metadata>
|
||||
<persistence-unit-defaults>
|
||||
</persistence-unit-defaults>
|
||||
</persistence-unit-metadata>
|
||||
</entity-mappings>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
|
||||
<persistence-unit name="hibernatePersistenceUnit" transaction-type="RESOURCE_LOCAL">
|
||||
<properties>
|
||||
<property name="hibernate.hbm2ddl.auto" value="update" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
|
||||
</properties>
|
||||
<mapping-file>META-INF/orm.xml</mapping-file>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.krams.aop;
|
||||
|
||||
import org.aopalliance.intercept.MethodInvocation;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.aop.interceptor.CustomizableTraceInterceptor;
|
||||
|
||||
/**
|
||||
* Extends {@link CustomizableTraceInterceptor} to provide custom logging levels
|
||||
*/
|
||||
public class TraceInterceptor extends CustomizableTraceInterceptor {
|
||||
|
||||
private static final long serialVersionUID = 287162721460370957L;
|
||||
protected static Logger logger4J = Logger.getLogger("aop");
|
||||
|
||||
@Override
|
||||
protected void writeToLog(Log logger, String message, Throwable ex) {
|
||||
if (ex != null) {
|
||||
logger4J.debug(message, ex);
|
||||
} else {
|
||||
logger4J.debug(message);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isInterceptorEnabled(MethodInvocation invocation, Log logger) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.krams.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
@Controller
|
||||
@RequestMapping
|
||||
public class AccessController {
|
||||
|
||||
@RequestMapping("/login")
|
||||
public String login(Model model, @RequestParam(required=false) String message) {
|
||||
model.addAttribute("message", message);
|
||||
return "access/login";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/denied")
|
||||
public String denied() {
|
||||
return "access/denied";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/login/failure")
|
||||
public String loginFailure() {
|
||||
String message = "Login Failure!";
|
||||
return "redirect:/login?message="+message;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/logout/success")
|
||||
public String logoutSuccess() {
|
||||
String message = "Logout Success!";
|
||||
return "redirect:/login?message="+message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.krams.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping("/")
|
||||
public class MediatorController {
|
||||
|
||||
@RequestMapping
|
||||
public String getHomePage() {
|
||||
return "home";
|
||||
}
|
||||
|
||||
@RequestMapping(value="/user")
|
||||
public String getUserPage() {
|
||||
return "user";
|
||||
}
|
||||
|
||||
@RequestMapping(value="/admin")
|
||||
public String getAdminPage() {
|
||||
return "admin";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.krams.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity(name="role")
|
||||
public class Role {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
@OneToOne
|
||||
private User user;
|
||||
private Integer role;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
public Integer getRole() {
|
||||
return role;
|
||||
}
|
||||
public void setRole(Integer role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package org.krams.domain;
|
||||
|
||||
import javax.persistence.CascadeType;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToOne;
|
||||
|
||||
@Entity(name="user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
@Column(unique=true)
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
@OneToOne(mappedBy="user", cascade={CascadeType.ALL})
|
||||
private Role role;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long 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 getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Role getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Role role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.krams.repository;
|
||||
|
||||
import org.krams.domain.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
User findByUsername(String username);
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package org.krams.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.krams.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* A custom {@link UserDetailsService} where user information
|
||||
* is retrieved from a JPA repository
|
||||
*/
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
/**
|
||||
* Returns a populated {@link UserDetails} object.
|
||||
* The username is first retrieved from the database and then mapped to
|
||||
* a {@link UserDetails} object.
|
||||
*/
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
try {
|
||||
org.krams.domain.User domainUser = userRepository.findByUsername(username);
|
||||
|
||||
boolean enabled = true;
|
||||
boolean accountNonExpired = true;
|
||||
boolean credentialsNonExpired = true;
|
||||
boolean accountNonLocked = true;
|
||||
|
||||
return new User(
|
||||
domainUser.getUsername(),
|
||||
domainUser.getPassword().toLowerCase(),
|
||||
enabled,
|
||||
accountNonExpired,
|
||||
credentialsNonExpired,
|
||||
accountNonLocked,
|
||||
getAuthorities(domainUser.getRole().getRole()));
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a collection of {@link GrantedAuthority} based on a numerical role
|
||||
* @param role the numerical role
|
||||
* @return a collection of {@link GrantedAuthority
|
||||
*/
|
||||
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
|
||||
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
|
||||
return authList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a numerical role to an equivalent list of roles
|
||||
* @param role the numerical role
|
||||
* @return list of roles as as a list of {@link String}
|
||||
*/
|
||||
public List<String> getRoles(Integer role) {
|
||||
List<String> roles = new ArrayList<String>();
|
||||
|
||||
if (role.intValue() == 1) {
|
||||
roles.add("ROLE_USER");
|
||||
roles.add("ROLE_ADMIN");
|
||||
|
||||
} else if (role.intValue() == 2) {
|
||||
roles.add("ROLE_USER");
|
||||
}
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps {@link String} roles to {@link SimpleGrantedAuthority} objects
|
||||
* @param roles {@link String} of roles
|
||||
* @return list of granted authorities
|
||||
*/
|
||||
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
|
||||
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
|
||||
for (String role : roles) {
|
||||
authorities.add(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
return authorities;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
log4j.rootLogger=DEBUG,console
|
||||
|
||||
#Console Appender
|
||||
log4j.appender.console=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.console.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.console.layout.ConversionPattern=[%5p] [%t %d{hh:mm:ss}] (%F:%M:%L) %m%n
|
||||
|
||||
#Custom assignments
|
||||
log4j.logger.controller=DEBUG,console
|
||||
log4j.logger.service=DEBUG,console
|
||||
|
||||
#Disable additivity
|
||||
log4j.additivity.controller=false
|
||||
log4j.additivity.service=false
|
||||
@@ -0,0 +1,76 @@
|
||||
-- phpMyAdmin SQL Dump
|
||||
-- version 3.3.9
|
||||
-- http://www.phpmyadmin.net
|
||||
--
|
||||
-- Host: localhost
|
||||
-- Generation Time: Jan 09, 2012 at 06:08 PM
|
||||
-- Server version: 5.5.8
|
||||
-- PHP Version: 5.3.5
|
||||
|
||||
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
|
||||
|
||||
|
||||
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
|
||||
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
|
||||
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
|
||||
/*!40101 SET NAMES utf8 */;
|
||||
|
||||
--
|
||||
-- Database: `spring_security_tutorial`
|
||||
--
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Table structure for table `role`
|
||||
--
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `role` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`role` int(11) DEFAULT NULL,
|
||||
`user_id` bigint(20) DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `FK3580769128426C` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
|
||||
|
||||
--
|
||||
-- Dumping data for table `role`
|
||||
--
|
||||
|
||||
INSERT INTO `role` (`id`, `role`, `user_id`) VALUES
|
||||
(1, 1, 1),
|
||||
(2, 2, 2);
|
||||
|
||||
-- --------------------------------------------------------
|
||||
|
||||
--
|
||||
-- Table structure for table `user`
|
||||
--
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `user` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`firstName` varchar(255) DEFAULT NULL,
|
||||
`lastName` varchar(255) DEFAULT NULL,
|
||||
`password` varchar(255) DEFAULT NULL,
|
||||
`username` varchar(255) DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `username` (`username`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
|
||||
|
||||
--
|
||||
-- Dumping data for table `user`
|
||||
--
|
||||
|
||||
INSERT INTO `user` (`id`, `firstName`, `lastName`, `password`, `username`) VALUES
|
||||
(1, 'John', 'Smith', '21232f297a57a5a743894a0e4a801fc3', 'john'),
|
||||
(2, 'Jane', 'Adams', 'ee11cbb19052e40b07aac0ca060c23ee', 'jane');
|
||||
|
||||
--
|
||||
-- Constraints for dumped tables
|
||||
--
|
||||
|
||||
--
|
||||
-- Constraints for table `role`
|
||||
--
|
||||
ALTER TABLE `role`
|
||||
ADD CONSTRAINT `FK3580769128426C` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);
|
||||
@@ -0,0 +1,3 @@
|
||||
Manifest-Version: 1.0
|
||||
Class-Path:
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:mvc="http://www.springframework.org/schema/mvc"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context-3.1.xsd
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
|
||||
|
||||
<context:property-placeholder properties-ref="deployProperties" />
|
||||
|
||||
<!-- Activates various annotations to be detected in bean classes -->
|
||||
<context:annotation-config />
|
||||
|
||||
<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans.
|
||||
For example @Controller and @Service. Make sure to set the correct base-package -->
|
||||
<context:component-scan base-package="org.krams" />
|
||||
|
||||
<!-- Configures the annotation-driven Spring MVC Controller programming model.
|
||||
Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
|
||||
<mvc:annotation-driven />
|
||||
|
||||
<mvc:resources mapping="/resources/**" location="/resources/" />
|
||||
|
||||
<!-- Imports logging configuration -->
|
||||
<import resource="trace-context.xml"/>
|
||||
|
||||
<!-- Imports datasource configuration -->
|
||||
<import resource="spring-data.xml"/>
|
||||
|
||||
<bean id="deployProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
|
||||
p:location="/WEB-INF/spring.properties" />
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,16 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ page import="org.springframework.security.core.context.SecurityContextHolder" %>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="resources/css/style.css"/>
|
||||
<title>Home</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<jsp:include page="../menu.jsp" />
|
||||
<h1 id="banner">Unauthorized</h1>
|
||||
<hr/>
|
||||
|
||||
<p class="message">Access denied!</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
|
||||
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="resources/css/style.css"/>
|
||||
<title>Login</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<form class="login-form" action="j_spring_security_check" method="post" >
|
||||
<fieldset>
|
||||
<legend>Login Here</legend>
|
||||
|
||||
<p>
|
||||
<label for="j_username">Username</label>:
|
||||
<input id="j_username" name="j_username" size="20" maxlength="50" type="text"/>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<label for="j_password">Password</label>:
|
||||
<input id="j_password" name="j_password" size="20" maxlength="50" type="password"/>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<input id="_spring_security_remember_me" name="_spring_security_remember_me" type="checkbox" checked="checked"/>
|
||||
<label for="_spring_security_remember_me">Remember Me?</label>
|
||||
</p>
|
||||
<p>
|
||||
<input type="submit" value="Login"/>
|
||||
</p>
|
||||
</fieldset>
|
||||
</form>
|
||||
<p class="message">${message}</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,25 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="resources/css/style.css"/>
|
||||
<title>Admin</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<jsp:include page="menu.jsp" />
|
||||
<h1 id="banner">Admin</h1>
|
||||
<hr/>
|
||||
|
||||
<p>Only admins can see this page</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et velit et sem
|
||||
fermentum viverra. Duis fringilla consequat lectus, et rhoncus mauris porta ut. Cum
|
||||
sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
|
||||
Donec commodo lorem sed felis iaculis pretium. Cras vel scelerisque ipsum.
|
||||
Donec a lacus lectus, ac dignissim dui. Duis vel dui et lacus dapibus lacinia. Mauris
|
||||
lacus metus, semper in varius vitae, ornare at augue. Nam enim elit, iaculis iaculis
|
||||
viverra at, blandit quis turpis. Nulla turpis quam, suscipit sed pellentesque sit amet,
|
||||
fermentum nec mauris. In non urna ornare sem cursus luctus. Pellentesque sed leo
|
||||
elit. Duis ut felis dui, et mollis nibh. Suspendisse faucibus molestie feugiat. Pellentesque
|
||||
non velit blandit ipsum auctor tempor placerat a eros. Quisque nec porttitor velit.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,26 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ page import="org.springframework.security.core.context.SecurityContextHolder" %>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="resources/css/style.css"/>
|
||||
<title>Home</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<jsp:include page="menu.jsp" />
|
||||
<h1 id="banner">Home</h1>
|
||||
<hr/>
|
||||
|
||||
<p>Welcome <span id="username"><%=SecurityContextHolder.getContext().getAuthentication().getName()%></span>!</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et velit et sem
|
||||
fermentum viverra. Duis fringilla consequat lectus, et rhoncus mauris porta ut. Cum
|
||||
sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
|
||||
Donec commodo lorem sed felis iaculis pretium. Cras vel scelerisque ipsum.
|
||||
Donec a lacus lectus, ac dignissim dui. Duis vel dui et lacus dapibus lacinia. Mauris
|
||||
lacus metus, semper in varius vitae, ornare at augue. Nam enim elit, iaculis iaculis
|
||||
viverra at, blandit quis turpis. Nulla turpis quam, suscipit sed pellentesque sit amet,
|
||||
fermentum nec mauris. In non urna ornare sem cursus luctus. Pellentesque sed leo
|
||||
elit. Duis ut felis dui, et mollis nibh. Suspendisse faucibus molestie feugiat. Pellentesque
|
||||
non velit blandit ipsum auctor tempor placerat a eros. Quisque nec porttitor velit.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
|
||||
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
|
||||
<%@ page import="org.springframework.security.core.context.SecurityContextHolder" %>
|
||||
|
||||
<c:url value="/" var="homeUrl"/>
|
||||
<c:url value="user" var="userUrl"/>
|
||||
<c:url value="admin" var="adminUrl"/>
|
||||
<c:url value="logout" var="logoutUrl"/>
|
||||
|
||||
<div class="menu">
|
||||
<ul>
|
||||
<li><a href="${homeUrl}">Home</a></li>
|
||||
<li><a href="${userUrl}">User</a></li>
|
||||
|
||||
<sec:authorize access="hasRole('ROLE_ADMIN')">
|
||||
<li><a href="${adminUrl}">Admin</a></li>
|
||||
</sec:authorize>
|
||||
|
||||
<li><a href="${logoutUrl}">Logout</a></li>
|
||||
</ul>
|
||||
<span id="menu-username"><%=SecurityContextHolder.getContext().getAuthentication().getName()%></span>
|
||||
<br style="clear:left"/>
|
||||
</div>
|
||||
@@ -0,0 +1,25 @@
|
||||
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="resources/css/style.css"/>
|
||||
<title>User</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<jsp:include page="menu.jsp" />
|
||||
<h1 id="banner">User</h1>
|
||||
<hr/>
|
||||
|
||||
<p>All users can see this page</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et velit et sem
|
||||
fermentum viverra. Duis fringilla consequat lectus, et rhoncus mauris porta ut. Cum
|
||||
sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
|
||||
Donec commodo lorem sed felis iaculis pretium. Cras vel scelerisque ipsum.
|
||||
Donec a lacus lectus, ac dignissim dui. Duis vel dui et lacus dapibus lacinia. Mauris
|
||||
lacus metus, semper in varius vitae, ornare at augue. Nam enim elit, iaculis iaculis
|
||||
viverra at, blandit quis turpis. Nulla turpis quam, suscipit sed pellentesque sit amet,
|
||||
fermentum nec mauris. In non urna ornare sem cursus luctus. Pellentesque sed leo
|
||||
elit. Duis ut felis dui, et mollis nibh. Suspendisse faucibus molestie feugiat. Pellentesque
|
||||
non velit blandit ipsum auctor tempor placerat a eros. Quisque nec porttitor velit.</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
|
||||
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://www.springframework.org/schema/tx
|
||||
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context-3.1.xsd
|
||||
http://www.springframework.org/schema/jdbc
|
||||
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
|
||||
http://www.springframework.org/schema/data/jpa
|
||||
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
|
||||
http://www.springframework.org/schema/util
|
||||
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
|
||||
|
||||
<context:property-placeholder properties-ref="deployProperties" />
|
||||
|
||||
<tx:annotation-driven transaction-manager="transactionManager" />
|
||||
|
||||
<!-- Activate Spring Data JPA repository support -->
|
||||
<jpa:repositories base-package="org.krams.repository" />
|
||||
|
||||
<!-- Declare a datasource that has pooling capabilities-->
|
||||
<bean id="jpaDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
|
||||
destroy-method="close"
|
||||
p:driverClass="${app.jdbc.driverClassName}"
|
||||
p:jdbcUrl="${app.jdbc.url}"
|
||||
p:user="${app.jdbc.username}"
|
||||
p:password="${app.jdbc.password}"
|
||||
p:acquireIncrement="5"
|
||||
p:idleConnectionTestPeriod="60"
|
||||
p:maxPoolSize="100"
|
||||
p:maxStatements="50"
|
||||
p:minPoolSize="10" />
|
||||
|
||||
<!-- Declare a JPA entityManagerFactory -->
|
||||
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
|
||||
p:persistenceXmlLocation="classpath*:META-INF/persistence.xml"
|
||||
p:persistenceUnitName="hibernatePersistenceUnit"
|
||||
p:dataSource-ref="jpaDataSource"
|
||||
p:jpaVendorAdapter-ref="hibernateVendor"/>
|
||||
|
||||
<!-- Specify our ORM vendor -->
|
||||
<bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
|
||||
p:showSql="false"/>
|
||||
|
||||
<!-- Declare a transaction manager-->
|
||||
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
|
||||
p:entityManagerFactory-ref="entityManagerFactory"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans:beans xmlns="http://www.springframework.org/schema/security"
|
||||
xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:util="http://www.springframework.org/schema/util"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security-3.1.xsd
|
||||
http://www.springframework.org/schema/util
|
||||
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
|
||||
|
||||
<http pattern="/resources" security="none" />
|
||||
|
||||
<http auto-config="true" use-expressions="true">
|
||||
<intercept-url pattern="/login" access="permitAll"/>
|
||||
<intercept-url pattern="/logout" access="permitAll"/>
|
||||
<intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
|
||||
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
|
||||
<intercept-url pattern="/user" access="hasRole('ROLE_USER')"/>
|
||||
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>
|
||||
|
||||
<form-login login-page="/login"
|
||||
authentication-failure-url="/login/failure"
|
||||
default-target-url="/"/>
|
||||
<!--
|
||||
login-page 用户自定义的登录页面
|
||||
authentication-failure-url 认证失败时的页面
|
||||
default-target-url 登录成功后的页面
|
||||
-->
|
||||
|
||||
<access-denied-handler error-page="/denied"/>
|
||||
<!--
|
||||
error-page 访问拒绝时的页面
|
||||
-->
|
||||
|
||||
<logout invalidate-session="true"
|
||||
logout-success-url="/logout/success"
|
||||
logout-url="/logout"/>
|
||||
<!--
|
||||
logout-success-url 退出系统后转向的URL
|
||||
logout-url 退出系统请求的URL
|
||||
-->
|
||||
|
||||
<remember-me key="spring-security-tutorial"/>
|
||||
<!--
|
||||
添加remember-me功能 对应login.jsp页面的配置 _spring_security_remember_me
|
||||
-->
|
||||
</http>
|
||||
|
||||
<authentication-manager>
|
||||
<authentication-provider user-service-ref="customUserDetailsService">
|
||||
<password-encoder hash="md5"/>
|
||||
</authentication-provider>
|
||||
</authentication-manager>
|
||||
</beans:beans>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
|
||||
|
||||
<!-- Declare a view resolver -->
|
||||
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
|
||||
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,5 @@
|
||||
# database properties
|
||||
app.jdbc.driverClassName=com.mysql.jdbc.Driver
|
||||
app.jdbc.url=jdbc\:mysql\://localhost/spring_security_tutorial
|
||||
app.jdbc.username=root
|
||||
app.jdbc.password=
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:p="http://www.springframework.org/schema/p"
|
||||
xmlns:aop="http://www.springframework.org/schema/aop"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
|
||||
http://www.springframework.org/schema/aop
|
||||
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
|
||||
|
||||
<!-- For parsing classes with @Aspect annotation -->
|
||||
<aop:aspectj-autoproxy/>
|
||||
|
||||
<bean id="customizableTraceInterceptor" class="org.krams.aop.TraceInterceptor"
|
||||
p:enterMessage="Entering $[targetClassShortName].$[methodName]($[arguments])"
|
||||
p:exitMessage="Leaving $[targetClassShortName].$[methodName](): $[returnValue]"/>
|
||||
|
||||
<aop:config>
|
||||
<aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * org.krams.service..*(..))"/>
|
||||
<aop:advisor advice-ref="customizableTraceInterceptor" pointcut="execution(public * org.krams.controller..*(..))"/>
|
||||
</aop:config>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
|
||||
<display-name>Spring Security Tutorial</display-name>
|
||||
|
||||
<filter>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
|
||||
</filter>
|
||||
|
||||
<filter-mapping>
|
||||
<filter-name>springSecurityFilterChain</filter-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</filter-mapping>
|
||||
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>
|
||||
/WEB-INF/spring-security.xml
|
||||
/WEB-INF/applicationContext.xml
|
||||
</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
|
||||
</listener>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>spring</servlet-name>
|
||||
<url-pattern>/</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
</web-app>
|
||||
@@ -0,0 +1,98 @@
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
width: 500px;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
h1, hr {
|
||||
margin: 0px;
|
||||
padding: 0px;
|
||||
}
|
||||
|
||||
#banner {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#username {
|
||||
color: red;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#menu-username {
|
||||
color: red;
|
||||
float: right;
|
||||
margin-top: 10px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.message {
|
||||
color: red;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-form {
|
||||
background-color: #333;
|
||||
color: white;
|
||||
padding: 5px;
|
||||
width: 300px;
|
||||
height: 220px;
|
||||
margin: auto;
|
||||
text-align: center;
|
||||
margin-top: 100px;
|
||||
}
|
||||
|
||||
.login-form fieldset {
|
||||
border: 1px solid gray;
|
||||
}
|
||||
|
||||
.login-form legend {
|
||||
margin: 0px;
|
||||
padding: 0px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.login-form hr {
|
||||
height: 1px;
|
||||
border: 0px;
|
||||
border-top: 1px solid black;
|
||||
}
|
||||
|
||||
.login-form input {
|
||||
/*float: right;*/
|
||||
}
|
||||
|
||||
/**
|
||||
* Menu based on James Owers' Horizontal CSS List Menu
|
||||
* @see http://jamesowers.co.uk/css-tutorials/50/horizontal-css-list-menu/
|
||||
*/
|
||||
.menu {
|
||||
width: 100%;
|
||||
background-color: #333;
|
||||
}
|
||||
|
||||
.menu ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
float: left;
|
||||
}
|
||||
|
||||
.menu ul li {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.menu ul li a {
|
||||
float: left;
|
||||
text-decoration: none;
|
||||
color: white;
|
||||
padding: 10.5px 11px;
|
||||
background-color: #333;
|
||||
}
|
||||
|
||||
.menu ul li a:visited {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.menu ul li a:hover, .menu ul li .current {
|
||||
color: #fff;
|
||||
background-color:#0b75b2;
|
||||
}
|
||||
Reference in New Issue
Block a user