`
seaboycs
  • 浏览: 127957 次
  • 性别: Icon_minigender_1
  • 来自: 南通
社区版块
存档分类
最新评论

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>

  • 大小: 48.9 KB
分享到:
评论
2 楼 seaboycs 2013-12-25  
wengeldouble 写道
鬼斧之作啊,膜拜,小辈们的楷模~

1 楼 wengeldouble 2013-12-25  
鬼斧之作啊,膜拜,小辈们的楷模~

相关推荐

    spring-security-login-form-database-xml.zip_java security

    标题 "spring-security-login-form-database-xml.zip_java security" 提示我们关注的是一个关于Spring Security的登录应用程序,其中涉及到数据库和XML配置。Spring Security是Java应用程序中广泛使用的安全框架,它...

    spring-security-jdbc

    在本文中,我们将深入探讨其与JDBC(Java Database Connectivity)的集成,即Spring Security JDBC,它是Spring Security实现用户认证和授权的一种常见方式。 首先,让我们理解Spring Security的基本架构。Spring ...

    Getting started with Spring Framework: covers Spring 5(epub)

    Database interaction using Spring and Hibernate/JPA- Spring Data JPA- Spring Data MongoDB- Messaging, emailing and caching support- Spring Web MVC- Developing RESTful web services using Spring Web ...

    spring-security-react-ant-design-polls-app:使用Spring Boot,Spring Security,JWT,React和Ant Design构建的全栈轮询应用程序

    使用Spring Boot,Spring Security,JWT,React和Ant Design构建类似于Twitter民意测验的Full Stack Polls应用程序 讲解 我在CalliCoder博客上为此应用程序编写了完整的教程系列- 设置Spring Boot Back end app...

    spring security 数据库存储资源信息 记住我 支持AJAX

    在提供的压缩包文件"springsecurity_database"中,可能包含了示例代码、配置文件和其他相关资源,可以帮助你理解和实现上述功能。在实际项目中,你需要根据自己的需求调整和扩展这些示例,以构建一个符合业务场景的...

    cas4-spring-security3-Demo:cas-server-4和spring-security-3,使用数据库登录验证的sso案例

    【标题】"cas4-spring-security3-Demo"是一个基于CAS Server 4和Spring Security 3的单点登录(SSO)示例项目,它展示了如何利用这两种技术实现在多个应用间共享用户认证的机制。 【描述】这个项目的核心在于使用...

    spring-boot-reference.pdf

    Spring Boot Documentation 1. About the Documentation 2. Getting Help 3. First Steps 4. Working with Spring Boot 5. Learning about Spring Boot Features 6. Moving to Production 7. Advanced Topics II. ...

    spring-security-config:可以访问H2数据库控制台的基本Spring Security配置

    Spring Security是Java领域中一个强大的安全框架,用于保护基于Spring的应用程序。在本文中,我们将深入探讨如何配置Spring Security以允许安全地访问H2数据库控制台。H2是一个轻量级、高性能的关系型数据库,常用于...

    spirng框架之spring security(一)和spirng框架之spring security(二)的示例代码

    Spring Security 是一个强大的安全框架,用于为Java应用提供身份验证和授权服务。在这个示例代码中,我们将深入探讨如何在Spring框架中集成Spring Security来实现用户登录认证与授权功能,以及如何利用RBAC(Role-...

    spring-framework-5.3.zip

    6. **Spring Security 更新**:Spring Security 5.x 在 Spring Framework 5.3 中得到了更新,强化了 OAuth2、JWT 支持,并且提供了更强大的安全防护功能。 7. **错误处理改进**:Spring MVC 和 WebFlux 提供了更...

    keycloak-spring-demo:演示如何使用 Keycloak Spring Security 适配器的示例

    customer-app使用 OAuth2 浏览器进行远程登录的 Spring Boot 应用程序,通过身份验证服务器重定向product-app使用 OAuth2 浏览器进行远程登录的 Spring Boot 应用程序,通过身份验证服务器重定向database-service仅...

    spring-security-jwt-mysql:在spring引导中构建rest api,使用数据库mysql在spring security jwt中进行授权认证

    Spring Boot(Maven)-Spring Security(注释)-JWT / MySql(授权,认证) 入门 需要JDK,弹簧靴,工作机。 先决条件 安装Spring Boot。 在环境变量中配置Java。 它是什么? 使用Spring Boot项目,Spring安全性。 ...

    spring security项目示例下载

    spring security配置项目下载,里面前台使用了easyui。 我的项目是用maven搭建的,如果你配置了maven,那么就会可以很轻松的运行起项目来了, 步骤: 1、在我的项目下找到database文件夹,把里面的union_ssh.sql文件...

    spring-security-login-database

    按着这些次序: 设置mysql数据库 执行mysql.sql脚本 使用 Maven 设置 Eclipse 导入maven项目 构建项目:mvn clean install 将 war 部署到应用服务器(tomcat) 访问:

    spring-reference-中文pdf清晰版

    Spring Security - **作用**:提供了一套强大的安全性解决方案,用于实现认证和授权。 - **主要特性**: - 认证管理 - 授权控制 - 记住我功能 - CSRF保护 #### 8. Spring Boot - **简介**:Spring Boot简化了...

    spring-boot-security-jpa:Spring Boot的初始设置

    spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC spring.datasource.username=your_username spring.datasource.password=your_password spring.jpa....

    Spring Data JDBC与JDBC的区别

    集成Spring Data JDBC可以减少代码量,提高可维护性,并且由于Spring的其他模块(如Spring MVC和Spring Security)与之良好集成,可以构建更复杂的Web应用。例如,Spring MVC提供了模型-视图-控制器架构,使业务逻辑...

    springSecurity总结及示例代码

    Spring Security 是一个强大的和高度可定制的身份验证和访问控制框架,用于保护基于Java的应用程序。它为Web应用程序和企业级应用提供了全面的安全解决方案,包括用户认证、授权、CSRF(跨站请求伪造)防护以及会话...

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    Getting started with Spring Framework is a hands-on guide to begin developing applications using Spring Framework. This book is meant for Java ...Chapter 14 – Securing applications using Spring Security

    springsecurity

    在“spring security use database and xml”的描述中,我们可以理解为Spring Security通过XML配置与数据库协同工作来实现安全控制。以下将详细解释这一过程: 1. **数据库集成**:Spring Security可以与任何支持...

Global site tag (gtag.js) - Google Analytics