SpringSecurity入门学习(二)

前言

上篇文章我们完成了一个最基本的spring-security的入门小demo,但有些朋友就觉得把用户信息放在配置文件中不好,这章我们就说说如何通过数据库获取用户信息

源码下载

git地址: https://github.com/kevinlu98/SpringSecurity

git push https://github.com/kevinlu98/SpringSecurity.git
git reset --hard  8b4a10a

在 pom.xml 加入连接MySQL的依赖


<dependency>
<groupId>mysqlgroupId>
	<artifactId>mysql-connector-javaartifactId>
	<version>5.1.21version>
dependency>
<dependency>
	<groupId>c3p0groupId>
	<artifactId>c3p0artifactId>
	<version>0.9.1.2version>
dependency>

定义数据库c3p0连接信息

在spring-security的配置文件中加入c3p0数据源


<beans:bean id="dataSource"
	class="com.mchange.v2.c3p0.ComboPooledDataSource"
	destroy-method="close">
	
	<beans:property name="driverClass"
		value="com.mysql.jdbc.Driver" />

	<beans:property name="jdbcUrl"
		value="jdbc:mysql://localhost:3306/springsecuritydemo" />
	<beans:property name="user" value="root" />
	<beans:property name="password" value="root" />
	<beans:property name="maxPoolSize" value="50">beans:property>
	<beans:property name="minPoolSize" value="10">beans:property>
	<beans:property name="initialPoolSize" value="10">beans:property>
	<beans:property name="maxIdleTime" value="25000">beans:property>
	<beans:property name="acquireIncrement" value="1">beans:property>
	<beans:property name="acquireRetryAttempts" value="30">beans:property>
	<beans:property name="acquireRetryDelay" value="1000">beans:property>
	<beans:property name="testConnectionOnCheckin"
		value="true">beans:property>
	<beans:property name="idleConnectionTestPeriod"
		value="18000">beans:property>
	<beans:property name="checkoutTimeout" value="5000">beans:property>
	<beans:property name="automaticTestTable"
		value="t_c3p0">beans:property>
beans:bean>

修改authentication-provider指向数据库


<authentication-manager>
	<authentication-provider>
		<jdbc-user-service data-source-ref="dataSource" />
	authentication-provider>
authentication-manager>

为spring-security准备数据库表,建表语句

-- 用户表
create table users(
    username varchar(50) not null primary key,
    password varchar(50) not null,
    enabled boolean not null
);

-- 权限表
create table authorities (
    username varchar(50) not null,
    authority varchar(50) not null,
    constraint fk_authorities_users foreign key(username) references users(username)
);

create unique index ix_auth_username on authorities (username,authority);

插入数据

-- 这里的数据和之前我们在配置文件中写的数据一样
insert into users(username,password,enabled) values('admin','admin',true);
insert into users(username,password,enabled) values('user','user',true);

insert into authorities(username,authority) values('admin','ROLE_ADMIN');
insert into authorities(username,authority) values('admin','ROLE_USER');
insert into authorities(username,authority) values('user','ROLE_USER');

致此,所有配置已经完成,直接运行即可,运行结果同上次

你可能感兴趣的:(spring,spring-security,Java)