Spring Security -- Database
<property name="jdbcUrl"
value="jdbc:mysql://localhost:3307/st?characterEncoding=UTF-8&characterSetResults=UTF-8" />
<property name="user" value="root" />
<property name="password" value="admin" />
<property name="maxPoolSize" value="100" />
<property name="minPoolSize" value="20" />
<property name="initialPoolSize" value="10" />
<property name="maxIdleTime" value="1800" />
<property name="acquireIncrement" value="10" />
<property name="idleConnectionTestPeriod" value="600" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="preferredTestQuery" value="SELECT NOW()" />
</bean>
?
<bean id="txManager"
ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
?
<bean id="jdbcTemplate" />
?
<sec:http pattern="/admin/css/**" security="none"/>
<sec:http pattern="/admin/img/**" security="none"/>
<sec:http pattern="/admin/js/**" security="none"/>
<sec:http pattern="/login.jsp**" security="none"/>
<sec:http auto-config="true" use-expressions="true">
<sec:form-login login-page="/login.jsp"
default-target-url="/home.spring" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login.jsp?e=1" always-use-default-target="true" />
<sec:logout logout-success-url="/login.jsp" />
<sec:intercept-url pattern="/**" access="hasRole('USER') OR hasRole('ADMIN')" />
<sec:intercept-url pattern="/admin/**" access="hasRole('ADMIN')" />
</sec:http>
?
? ? <sec:authentication-manager> ?
? ? ? ? <sec:authentication-provider ref="MyAuthenticationProvider" /> ?
? ? </sec:authentication-manager> ?
? ??
? ?<bean id="MyAuthenticationProvider" ref="jdbcTemplate" />
? ?</bean>
?
?2. Create mysql tables?
?
CREATE TABLE IF NOT EXISTS COM_PRO_USER (`ID` INT(11) NOT NULL AUTO_INCREMENT,`LOGINNAME` VARCHAR (50) NOT NULL,`PASSWORD` VARCHAR (50) NOT NULL,`USERNAME` VARCHAR (50) NOT NULL,PRIMARY KEY (`ID`)) COLLATE='utf8_bin' ENGINE=InnoDB AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS COM_PRO_ROLE (`ID` INT(11) NOT NULL AUTO_INCREMENT,`NAME` VARCHAR (50) NOT NULL,PRIMARY KEY (`ID`)) COLLATE='utf8_bin' ENGINE=InnoDB AUTO_INCREMENT=1;
INSERT INTO COM_PRO_ROLE VALUES(1, 'USER'),(2, 'ADMIN');
CREATE TABLE IF NOT EXISTS COM_PRO_USER_ROLE (`ID` INT(11) NOT NULL AUTO_INCREMENT,`USER_ID` INT (11) NOT NULL,`ROLE_ID` INT (11) NOT NULL,PRIMARY KEY (`ID`)) COLLATE='utf8_bin' ENGINE=InnoDB AUTO_INCREMENT=1;
3. Create class?MyAuthenticationProvider?:
?
package com.pro.security;
?
import java.util.List;
import java.util.Map;
?
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
?
public class MyAuthenticationProvider implements AuthenticationProvider {
?
private static final String QUERY_SQL_VALIDATE = "SELECT COUNT(1) FROM COM_PRO_USER WHERE LOGINNAME=? AND PASSWORD=?";
private static final String QUERY_SQL_GRANT = "SELECT A.USERNAME AS USER_NAME, B.NAME AS ROLE_NAME FROM COM_PRO_USER A, COM_PRO_ROLE B, COM_PRO_USER_ROLE C WHERE A.LOGINNAME=? AND A.ID = C.USER_ID AND B.ID = C.ROLE_ID";
private JdbcTemplate jdbcTemplate;
?
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
?
?
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
"Only UsernamePasswordAuthenticationToken is supported");
?
UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
?
String userName = userToken.getName();
?
if (!StringUtils.hasLength(userName)) {
throw new BadCredentialsException("Empty Username");
}
?
String password = (String) authentication.getCredentials();
if (this.jdbcTemplate.queryForInt(QUERY_SQL_VALIDATE, userName, password) < 1) {
throw new BadCredentialsException("Error name and password");
}?
MyUser userDetail = new MyUser();
try {
List<Map<String, Object>> rows = this.jdbcTemplate.queryForList(QUERY_SQL_GRANT, userName);
userDetail.setUserId(userName);
if (rows != null && rows.size() > 0) {
userDetail.setEnabled(true);
userDetail.setUsername((String)rows.get(0).get("USER_NAME"));
for(Map<String, Object> row:rows){
userDetail.addAuthoritie(new MyGrantedAuthority((String)row.get("ROLE_NAME")));
}
}
} catch (Exception e) {
throw new UsernameNotFoundException(userName);
}
UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(userDetail, password, userDetail.getAuthorities());
user.setDetails(userToken.getDetails());
return user;
}
?
@Override
public boolean supports(Class<?> arg0) {
return true;
}
?
}
?
4. Create class?MyUser:
package com.pro.security;
?
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
?
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
?
public class MyUser implements UserDetails{
?
private String password;
private String username;
private String userId;
private boolean enabled;
private boolean expired;
private boolean locked;
private boolean credentialsNonExpired;
?
private static final long serialVersionUID = 1L;
private Collection<MyGrantedAuthority> authorities;
?
public void addAuthoritie(MyGrantedAuthority authority) {
if (this.authorities == null) {
this.authorities = new ArrayList<MyGrantedAuthority>();
}
this.authorities.add(authority);
}
?
public void addAuthorities(List<MyGrantedAuthority> authorities) {
if (this.authorities == null) {
this.authorities = new ArrayList<MyGrantedAuthority>();
}
if (authorities != null)
this.authorities.addAll(authorities);
}
?
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
?
public String getPassword() {
return password;
}
?
public void setPassword(String password) {
this.password = password;
}
?
public String getUsername() {
return username;
}
?
public void setUsername(String username) {
this.username = username;
}
?
public String getUserId() {
return userId;
}
?
public void setUserId(String userId) {
this.userId = userId;
}
?
public boolean isEnabled() {
return enabled;
}
?
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
?
public boolean isAccountNonExpired() {
return expired;
}
?
public void setExpired(boolean expired) {
this.expired = expired;
}
?
public boolean isAccountNonLocked() {
return locked;
}
?
public void setLocked(boolean locked) {
this.locked = locked;
}
?
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
?
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
?
}
?
?5. Create class?MyGrantedAuthority:
package com.pro.security;
?
import org.springframework.security.core.GrantedAuthority;
?
public class MyGrantedAuthority implements GrantedAuthority {
?
private static final long serialVersionUID = -6503668106239819038L;
?
public MyGrantedAuthority() {
?
}
?
public MyGrantedAuthority(String role) {
this.role = role;
}
?
private String role;
?
@Override
public String getAuthority() {
?
return this.role;
}
?
public void setRole(String role) {
this.role = role;
}
?
}
6. 修改WEB.XML(Example)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
? <display-name>myhhr</display-name>
? ?<context-param> ?
? ? ? ? <param-name>webAppRootKey</param-name> ?
? ? ? ? <param-value>webapp.myhhr</param-value> ?
? ? </context-param>
? <welcome-file-list>
? ? <welcome-file>home.jsp</welcome-file>
? </welcome-file-list>
? <filter>
? <filter-name>CharacterEncoding</filter-name>
? <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
? <init-param>
? ?<param-name>encoding</param-name>
? ?<param-value>UTF-8</param-value>
? </init-param>
? <init-param>
? ?<param-name>forceEncoding</param-name>
? ?<param-value>true</param-value>
? </init-param>
?</filter>
<filter>
? <filter-name>springSecurityFilterChain</filter-name>
? <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
?</filter>
?<filter-mapping>
? <filter-name>CharacterEncoding</filter-name>
? <url-pattern>/*</url-pattern>
?</filter-mapping>
?<filter-mapping>
? <filter-name>springSecurityFilterChain</filter-name>
? <url-pattern>/*</url-pattern>
?</filter-mapping>
?
?<listener>
? <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
?</listener>
?<listener>
? <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
?</listener>
?<listener>
? <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
?</listener>
?<servlet>
? <servlet-name>dispatcher</servlet-name>
? <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
? <load-on-startup>1</load-on-startup>
?</servlet>
?<servlet-mapping>
? <servlet-name>dispatcher</servlet-name>
? <url-pattern>*.spring</url-pattern>
?</servlet-mapping>
</web-app>
?
7. login.jsp
?<form action="${pageContext.request.contextPath}/j_spring_security_check" method="post">
<fieldset>
<div title="Username" data-rel="tooltip">
<span name="j_username" id="username" type="text" value="admin" />
</div>
<div title="Password" data-rel="tooltip">
<span name="j_password" id="password" type="password" value="admin123456" />
</div>
<div contentType="text/html; charset=UTF-8"
? ? pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>我的合伙人 首页</title>
</head>
<body>
<sec:authorize access="hasRole('ADMIN')"><a href="${pageContext.request.contextPath}/admin/home.spring">管理员页面</a></sec:authorize>
</body>
</html>