http://blog.csdn.net/jeofey/article/details/73849241
spring 结合mybatis,以及Spring Security实现用户认证(Authentication)和授权(Authorization)功能.Spring Security是专门针对基于Spring项目的
安全框架,充分利用依赖注入和AOP来实现安全功能。Spring Boot针对Spring Security 的自动配置主要是靠SecurityAutoConfigation和SecurityProperties来
完成。页面模板Thymeleaf为我们提供了Spring Security的标签。
新建项目
新建Spring Boot的gradle项目,引入MySQL,spring-mybatis,springboot-security,thymeleaf相关依赖。
dependencies {compile('org.springframework.boot:spring-boot-starter-web')compile('org.springframework.boot:spring-boot-starter-security')//视图依赖compile('org.springframework.boot:spring-boot-starter-thymeleaf')//thymeleaf的Spring Security支持依赖compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4')// spring-jdbccompile "org.springframework:spring-jdbc:4.2.3.RELEASE"//A high-performance JDBC connection pool.compile "com.zaxxer:HikariCP"// mysqlcompile "mysql:mysql-connector-java"//mybatis依赖compile "org.mybatis:mybatis:3.3.1"compile "org.mybatis:mybatis-spring:1.2.4"compile "org.mybatis.generator:mybatis-generator-core:1.3.2"//分页插件compile "com.github.pagehelper:pagehelper:4.1.0" }
application.yml文件
server: port: 8081spring: datasource: driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456thymeleaf: cache: falsemybatis: mapperLocations: classpath:mapper/**.xmlconfig: mybatis-config.xmlrows_per_transaction: 500logging: level: org: springframework: security: debug
配置数据库
首先创建一个Config配置文件,用来配置HikariCP连接池,项目暂不使用读写分离,如果需要分别创建read和write的DataSource bean.
@Configuration public class MyBatisDataSourceConfig implements EnvironmentAware {private RelaxedPropertyResolver propertyResolver;private static Logger log = LoggerFactory.getLogger(MyBatisDataSourceConfig.class);@Overridepublic void setEnvironment(Environment env) {this.propertyResolver = new RelaxedPropertyResolver(env, "spring.dataSource.");}@Bean(name = "dataSource")@Primarypublic DataSource dataSource() {log.debug("Configruing Write DataSource");HikariConfig datasource = new HikariConfig();datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));datasource.setJdbcUrl(propertyResolver.getProperty("url"));datasource.setUsername(propertyResolver.getProperty("username"));datasource.setPassword(propertyResolver.getProperty("password"));datasource.setPoolName("dataSourcePool");datasource.setAutoCommit(false);return new HikariDataSource(datasource);} }
然后创建了一个SqlSessionFactory,为了支持注解事务,增加了@EnableTransactionManagement,并且反回了一个PlatformTransactionManagerBean。
@Configuration @AutoConfigureAfter({MyBatisDataSourceConfig.class}) @EnableTransactionManagement public class MyBatisSessionFactoryConfig implements EnvironmentAware,TransactionManagementConfigurer {private static Logger logger = LoggerFactory.getLogger(MyBatisSessionFactoryConfig.class);private RelaxedPropertyResolver propertyResolver;@Resource(name = "dataSource")private DataSource dataSource;@Overridepublic void setEnvironment(Environment environment) {this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");}@Bean(name="sqlSessionFactory")@Primarypublic SqlSessionFactory sqlSessionFactory() {try {SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();sqlSessionFactory.setDataSource(dataSource);sqlSessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(propertyResolver.getProperty("config")));sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(propertyResolver.getProperty("mapperLocations")));return sqlSessionFactory.getObject();} catch (Exception e) {logger.error("Could not confiure mybatis session factory",e);return null;}}@Bean@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {logger.info("数据库事务开启~~~~~~~~~~~~~~~~~~~~~~~~~~");return new DataSourceTransactionManager(dataSource);} }
另外,为了扫描MyBatis的Mapper接口,我们就需要配置MapperScannerConfigurer这个类,这个配置我们需要单独放到一个类中。
@Configuration //TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解 @AutoConfigureAfter({MyBatisSessionFactoryConfig.class}) public class MyBatisMapperScannerConfig {private static Logger logger = LoggerFactory.getLogger(MyBatisMapperScannerConfig.class);@Bean(name="mapperScannerConfigurer")public MapperScannerConfigurer mapperScannerConfigurer() {logger.info("Database Scanner File ~~~~~~~~~~~~~~~~~~~");MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");mapperScannerConfigurer.setBasePackage(BaseMapper.class.getPackage().getName());mapperScannerConfigurer.setMarkerInterface(BaseMapper.class);return mapperScannerConfigurer;} }
创建mapper接口,所有mapper接口都继承该接口。
package com.xjj.mapper;public interface BaseMapper { }
定义用户和角色实体类
用户类:实现了UserDetails接口,我们的用户实体即为Srping Security所使用的用户。重写getAuthorities方法,将用户的角色作为权限。
public class SysUser implements UserDetails {private static final long serialVersionUID = -7071429258899138676L;private Long id;private String username;private String password;private List<SysRole> roles;@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {List<GrantedAuthority> auths = new ArrayList<>();List<SysRole> roles = this.getRoles();for (SysRole role:roles) {auths.add(new SimpleGrantedAuthority(role.getName()));}return auths;}@Overridepublic String getPassword() {return password;}@Overridepublic String getUsername() {return username;}@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic boolean isEnabled() {return true;} //省略getset方法
角色:
public class SysRole {private Long id;private String name; }//省略getset方法
定义好数据结构,创建表,并进行初始化。
用户表:sys_user
角色表:sys_role
用户角色关系表:sys_user_roles(用户与角色是多对多的关系)
初始化数据
insert into `sys_role`(`id`,`name`) values (1,'ROLE_ADMIN'),(2,'ROLE_USER');
insert into `sys_user`(`id`,`password`,`username`) values (1,'xjj','xjj'),(2,'xianjj','xianjj');
insert into `sys_user_roles`(`sys_user_id`,`roles_id`) values (1,1),(2,2),(1,2);
具体sql语句见项目resource下的sql.sql
定义传值实体
根据角色不同,页面显示不同内容。
public class Msg {private String title;private String content;private String etraInfo;public Msg(String title, String content, String etraInfo) {super();this.content = content;this.etraInfo = etraInfo;this.title = title;}//省略get set 方法 }
数据查询
自定义接口需要实现UserDetailsService接口,重写loadUserByUsername方法,查询用户信息。我们当前的用户实现了UserDetails接口,可直接返回给Spring Security使用。
public class CustomUserSevice implements UserDetailsService {@AutowiredSysUserMapper sysUserMapper;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {SysUser user = sysUserMapper.findByUsername(username);if (user == null){throw new UsernameNotFoundException("用户名不存在");}return user;} }
public interface SysUserMapper extends BaseMapper {SysUser findByUsername(String username);List<SysRole> findRolesByUsername(String username); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xjj.mapper.SysUserMapper"><resultMap id="sysUserMap" type="com.xjj.domain.SysUser" ><id column="id" property="id" jdbcType="INTEGER" /><result column="id" property="id" jdbcType="VARCHAR" /><result column="username" property="username" jdbcType="VARCHAR" /><result column="password" property="password" jdbcType="VARCHAR" /><collection property="roles" column="username" select="findRolesByUsername" /></resultMap><select id="findByUsername" resultMap="sysUserMap">SELECT * from sys_user WHERE username = #{0}</select><select id="findRolesByUsername" resultType="com.xjj.domain.SysRole">SELECTsysrole.id,sysrole.nameFROMsys_user_roles rolesINNER JOIN sys_role sysroleON roles.roles_id = sysrole.idINNER JOIN sys_user sysuserON sysuser.id = roles.sys_user_idWHERE sysuser.username = #{0}</select> </mapper>
配置
Spring MVC配置,注册访问/login转向login.html页面
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/login").setViewName("login");} }
Spring Security配置
扩展Spring Security配置,需要继承WebSecurityConfigurerAdapter类,添加自定义的UserDetailsService认证,重写configure方法。
前台页面
登录页面login.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head><meta content="text/html;charset=UTF-8"/><title>登录页面</title><link rel="stylesheet" th:href="@{css/bootstrap.min.css}" /><style>body{padding-top: 50px;}.starter-template{padding: 40px 15px;text-align: center;}</style> </head> <body><nav class="narbar navbar-inverse navbar-fixed-top"><div class="container"><div class="navbar-header"><a class="navbar-brand" href="#">Spring Security 演示</a></div><div id="navbar" class="collapse navbar-collapse"><ul class="nav navbar-nav"><li><a th:href="@{/}">首页</a></li></ul></div></div></nav><div class="container"><div class="starter-template"><p th:if="${param.logout}" class="bg-warning">已成功注销</p><p th:if="${param.error}" class="bg-danger">有错误请重试</p><h2>使用账号密码登录</h2><form name="form" th:action="@{/login}" action="/login" method="post"><div class="form-group"><label for="username">账号</label><input type="text" class="form-control" name="username" value="" placeholder="账号"/></div><div class="form-group"><label for="password">密码</label><input type="password" class="form-control" name="password" placeholder="密码"/></div><input type="submit" id="login" value="Login" class="btn btn-primary"/></form></div></div> </body> </html>
首页
登录成功后跳转到首页
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head><meta content="text/html;charset=UTF-8"/><title sec:authentication="name"></title><link rel="stylesheet" th:href="@{css/bootstrap.min.css}" /><style>body{padding-top: 50px;}.starter-template{padding: 40px 15px;text-align: center;}</style> </head> <body><nav class="narbar navbar-inverse navbar-fixed-top"><div class="container"><div class="navbar-header"><a class="navbar-brand" href="#">Spring Security 演示</a></div><div id="navbar" class="collapse navbar-collapse"><ul class="nav navbar-nav"><li><a th:href="@{/}">首页</a></li></ul></div></div></nav><div class="container"><div class="starter-template"><h1 th:text="${msg.title}"></h1><p class="bg-primary" th:text="${msg.content}"></p><div sec:authorize="hasRole('ROLE_ADMIN')" ><p class="bg-info" th:text="${msg.etraInfo}"></p></div><div sec:authorize="hasRole('ROLE_USER')" ><p class="bg-info">无更多信息显示</p></div><form th:action="@{/logout}" method="post"><input type="submit" class="btn btn-primary" value="注销"/></form></div></div> </body> </html>
控制器
为首页准备显示数据
@Controller public class HomeController {@RequestMapping("/")public String index(Model model){Msg msg = new Msg("测试标题", "测试内容", "额外信息,只对管理员显示");model.addAttribute(msg);return "index";} }
运行结果
http://127.0.0.1:8081/
分别用管理员和普通用户登录,观察页面回显结果;
登录成功后点击注销,返回到登录页面;
用户名或密码不正确时,校验失败;
csdn源码下载:http://download.csdn.net/detail/jeofey/9883194
github下载:https://github.com/jeofey/SpringBootDemo