Spring Security -- Database

我的一个项目中用到的Spring Security来验证用户合法性,公司里面是连接到LDAP server做验证的,自己又写了一套基于数据库的测试项目,给新手分享一下,也供日后自己回顾。

 

Spring 版本:3.1.0.RELEASE.jar

相关架包可以到官网下载,我用到了下面的架包(LIBS.JPG),有些可能不需要.

 

1. Spring 配置文件中添加:

 

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close">

<property name="driverClass" value="com.mysql.jdbc.Driver" />

<property name="jdbcUrl"

value="jdbc:mysql://localhost:3307/st?characterEncoding=UTF-8&amp;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"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource" />

</bean>

<tx:annotation-driven transaction-manager="txManager" />

 

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<constructor-arg ref="dataSource"></constructor-arg>

</bean>

 

<bean id="namedParameterJdbcTemplate"

class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">

<constructor-arg ref="dataSource"></constructor-arg>

</bean>

 

<bean id="webexpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler" />

 

<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" class="com.pro.security.MyAuthenticationProvider">

    <property name="jdbcTemplate" 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 class="form-horizontal" action="${pageContext.request.contextPath}/j_spring_security_check" method="post">

<fieldset>

<div class="input-prepend" title="Username" data-rel="tooltip">

<span class="add-on"><i class="icon-user"></i></span><input autofocus class="input-large span10" name="j_username" id="username" type="text" value="admin" />

</div>

<div class="clearfix"></div>

 

<div class="input-prepend" title="Password" data-rel="tooltip">

<span class="add-on"><i class="icon-lock"></i></span><input class="input-large span10" name="j_password" id="password" type="password" value="admin123456" />

</div>

<div class="clearfix"></div>

 

<div class="input-prepend">

<a href="register.jsp">Register</a>

</div>

<div class="clearfix"></div>

 

<p class="center span5">

<button type="submit" class="btn btn-primary">Login</button>

</p>

</fieldset>

</form>

 8. JSP 权限控制标签:

     <%@ page language="java" 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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值