最近有个服务要搞个Java版本,以前很少接触呀,更别说什么SpringBoot、MyBatis、SpringSecurity之类的了。
一通捣鼓,哎呀,各种折腾,终于做了个Demo(源码见源码福利章节,或文末)。
在此要感谢各位大牛,你们的博客和代码对我帮助很大。咳咳,言归正传。
本篇文章意在标出各种坑和关键点。拒绝类同和废话连篇。
项目说明
关于创建SpringBoot项目,使用MyBatis,请自行解决。主要是应用SpringSecurity。
项目截图如下:
要点讲解
- 自定义的WebSecurityConfigurerAdapter一定要添加@EnableWebSecurity注解。
- 同上,自定义的WebSecurityConfigurerAdapter至少要重写configure ( HttpSecurity http)和 configure ( AuthenticationManagerBuilder auth) 函数!不然自定义的认证和鉴权都不起作用。
- 自定义的UserDetailsService要添加@Service注解,并且重载UserDetails loadUserByUsername (String username)函数
- 自定义Controller与WebMvcConfigurerAdapter目的都是页面跳转,而前者可以包含相关的业务操作
- 自定义Controller权限控制到方法级别时,一定要在自定义的WebSecurityConfigurerAdapter中添加注解
- 方法权限控制有三种方式,都需要前一条讲解相结合
- 对页面标签权限的支持,需要在pom.xml中添加spring-security-taglibs类库的支持
- 权限访问失败处理一定要在configure(HttpSecurity http)中定义好,不管是页面显示,还是Handler处理,不然直接炮异常。
编译运行
如何跑起来
发现这必须要弄个小章节,像我这种小白真的不会怎么启动,羞羞捂脸~
- 项目右键->Run As -> Maven Clean;
- Run As -> Maven Install;
- Spring Boot App;OK,服务算是跑起来了。
- 打开浏览器,输入网址:http://127.0.0.1:18089。开始玩耍吧。
运行截图
默认首页
输入http://127.0.0.1:18089。
或http://127.0.0.1:18089/home亦可,因为我们在代码中做了转换:
登陆界面
目前创建了两个用户,分别是admin和user(相关数据见后面“源码福利”章节),我们先用admin登陆。
共用页管理员登陆
使用管理员级别的admin用户登陆,进入共用Hello页。
在此页中,定义了具有两个权限的标签。管理员都可查看到。
共用页普通用户登陆
普通用户登陆,对比可发现,ROLE_ADMIN级别的标签信息不可见。
管理员权限页
管理员用户admin登陆后,点击进入admin page的按钮,则进入管理员可访问的页面。
访问权限限制页
普通用户user登陆后,点击进入admin page的按钮,则弹出访问限制的提示页。
源码福利
哈哈,源码是一定要给的,项目源码下载地址:请点击我吧~~~
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.SpringBootMyBatisSpringSecurity</groupId>
<artifactId>SpringBootMyBatisSpringSecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootMyBatisSpringSecurity</name>
<description>SpringBootMyBatisSpringSecurity</description>
<!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 模板引擎jar包, 已经包括了spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Boot Test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 用于thymeleaf中使用security的标签 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>com.oracle.ojdbc6</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<verbose>true</verbose>
<fork>true</fork>
<executable>${JAVA8_HOME}/bin/javac</executable>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=18089
server.address=127.0.0.1
server.contextPath=/
spring.datasource.url=jdbc:oracle:thin:@10.10.83.134:1521:HS2008
spring.datasource.username=RM
spring.datasource.password=123456
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.session.store-type=none
mybatis.type-aliases-package: com.tw.entity
mybatis.mapper-locations: - classpath:mapping/*.xml
WebSecurityConfig.java
package com.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
/*
* 配置类:
* 重写它的方法来设置一些web安全的细节,如配置security的登录页面和传递的参数,公共路径权限属性等
*/
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true) //控制权限到请求方法级别
//@EnableGlobalMethodSecurity(prePostEnabled = true)//方法调用前鉴权
@EnableWebSecurity //禁用Boot的默认Security配置,配合@Configuration启用自定义配置(需要扩展WebSecurityConfigurerAdapter)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//自定义认证对象
@Autowired
private UserDetailInfo urlUserService;
//HTTP请求安全处理
@Override
protected void configure(HttpSecurity http) throws Exception {
//请求权限配置
http.authorizeRequests()
//指定了/和/home不需要任何认证就可以访问,
.antMatchers("/", "/home").permitAll()
//任何请求,登录后方可访问。
.anyRequest().authenticated()
//登陆界面参数
.and().formLogin().defaultSuccessUrl("/hello")/*.loginPage("/login").usernameParameter("username").passwordParameter("password")*/.permitAll()
//设置注销成功后跳转页面,默认是跳转到登录页面
.and().logout().logoutSuccessUrl("/home").permitAll()
//权限访问失败界面,关键,如果不定义的话会抛出异常
.and().exceptionHandling().accessDeniedPage("/denied")
;
http.csrf().disable();
}
/*
* 身份验证管理生成器。一定要重载!!!不然自定义的登陆校验不生效
* */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(urlUserService)
/*.passwordEncoder(new PasswordEncoder() {
//可以自己定义密码匹配规则
@Override
public String encode(CharSequence rawPassword) {
return (String)rawPassword;//MD5Util.encode((String) rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
System.out.println(encodedPassword + "---" + (String)rawPassword);
return encodedPassword.equals((String) rawPassword);
}
})*/;
}
}
UserDetailInfo.java
package com.demo;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/*
* 自定义用户名密码校验实现,一定要@Service注解,然后在配置类中加载(重载configure)
*/
@Service
public class UserDetailInfo implements UserDetailsService{
//数据库操作
@Autowired
private DataMapper dbDataMapper;
//必须重写,自己来实现登陆验证
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("user["+username+"] is logining...");
DbUser dbUser = dbDataMapper.getUserLoginInfo(username);
if(dbUser==null)
{
System.out.println("user["+username+"] is not exist!");
throw new UsernameNotFoundException(username + " do not exist!");
}
System.out.println("Get user info from db: "+ dbUser.toString());
UserDetails user = new User(dbUser.getUsername(), dbUser.getPassword(), true, true, true, true,
getAuthorities(dbUser.getAccess_level()));
return user;
}
/**
* 获得访问角色权限
*/
public Collection<GrantedAuthority> getAuthorities(Integer access) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
//所有的用户默认拥有ROLE_USER权限
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
if (access.compareTo(0) == 0) {
// 如果参数access为0.则拥有ROLE_ADMIN权限
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
return authorities;
}
}
MvcConfig.java
package com.demo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Component
public class MvcConfig extends WebMvcConfigurerAdapter {
//直接页面跳转,不经过Controller,这样在没有任何处理业务的时候,快捷的页面转向定义会节省好多代码
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
//registry.addViewController("/hello").setViewName("hello");
//registry.addViewController("/login").setViewName("login");
//registry.addViewController("/denied").setViewName("denied");
//registry.addViewController("/admin").setViewName("admin");
}
}
HelloController.java
package com.demo;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/*
* 网络控制层:返回数据的controller。这里映射到resources目录下的templates的html页面。 *
*/
@Controller
public class HelloController {
@RequestMapping("/")
public String index() {
return "home";
}
@RequestMapping("/home")
public String home() {
return "home";
}
/*当我们访问这个URL的时候,Spring Security会帮我们验证当前用户是否有权限访问该地址。
*官方推荐的鉴权注解方式,控制权限到请求方法级别。可通过三种方式的注解:
*注解方式1:@Secured, spring自带的注解方法:securedEnabled = true
*注解方式2:@PreAuthorize,方法调用前注解:securedEnabled = true
*注解方式2:@RolesAllowed,非spring框架: jsr250Enabled = true
*注意1:角色要填全名!
*注意2:一定要在自定义的WebSecurityConfigurerAdapter中添加注解。@EnableGlobalMethodSecurity(axx=bxx)!axx/bxx见上
*/
@Secured({"ROLE_ADMIN","ROLE_USER"})
@RequestMapping("/hello")
//@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
public String hello(){
return "hello";
}
@RequestMapping(value = "/login")
public String login() {
return "login";
}
@RequestMapping(value = "/logout")
public String logout() {
return "home";
}
@RequestMapping(value = "/denied")
public String denied() {
return "denied";
}
@Secured("ROLE_ADMIN")
@RequestMapping(value = "/admin")
//@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public String admin() {
return "admin";
}
}
DemoApplication.java
package com.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//这个表示mybatis自动扫描dao接口的包名,
@MapperScan("com.demo")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
DbUser.java
package com.demo;
/*
* 测试用户对象
*/
public class DbUser {
private String username;
private String password;
private Integer access_level;
private String description;
public Integer getAccess_level() {
return access_level;
}
public void setAccess_level(Integer access_level) {
this.access_level = access_level;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
if(access_level==0)
{
return "username["+username+"], password["+password+"], access_level[role_admin], description["+description+"]";
}
return "username["+username+"], password["+password+"], access_level[role_user], description["+description+"]";
}
}
DataSourceConfig.java
package com.demo;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
/*
* 数据库相关配置
*/
@Configuration
@MapperScan(basePackages = "com.demo", sqlSessionFactoryRef = "dbDataSqlSessionFactory")
public class DataSourceConfig {
@Bean(name = "dbDataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dbDataSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("dbDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/dbMapper.xml"));
return bean.getObject();
}
@Bean(name = "dbDataTransactionManager")
public DataSourceTransactionManager transactionManager(@Qualifier("dbDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "rmdataSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(
@Qualifier("dbDataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
DataMapper.java
package com.demo;
/*
* Mybatis数据映射,数据库sql见: resource/mybatis/db.sql
*/
public interface DataMapper {
DbUser getUserLoginInfo(String username);
}
db.sql
drop table demo_security_user ;
create table RM.demo_security_user(
EID NUMBER(18) not null,
EITIME DATE default sysdate ,
EUTIME DATE default sysdate ,
username VARCHAR2(16) default '' not null,
password VARCHAR2(16) default ''not null,
access_level NUMBER(2) default 2 not null,
description VARCHAR2(64) default ''
);
comment on table RM.demo_security_user is 'springsecurity测试表';
comment on column RM.demo_security_user.EID is '系统物理主键';
comment on column RM.demo_security_user.EITIME is '数据入库时间';
comment on column RM.demo_security_user.EUTIME is '数据修改时间';
comment on column RM.demo_security_user.username is '用户名';
comment on column RM.demo_security_user.password is '用户密码';
comment on column RM.demo_security_user.access_level is '用户权限';
comment on column RM.demo_security_user.description is '用户说明';
alter table RM.demo_security_user add constraint PK_EMHK_RM_demo_security_user primary key(EID) using index tablespace tbs_unvidx;
grant insert,update,delete on RM.demo_security_user to RM;
select username, password, access_level,description from rm.demo_security_user t
where 1=1;
insert into RM.demo_security_user(eid,eitime,eutime,username,password,access_level,description)
values(RM.SEQ_EID.nextval,sysdate,sysdate,'username1','password1',0,'description1');
insert into RM.demo_security_user(EID,EITIME,EUTIME,username,password,access_level,description)
values(RM.SEQ_EID.nextval,sysdate,sysdate,'username2','password2',1,'description2');
insert into RM.demo_security_user(EID,EITIME,EUTIME,username,password,access_level,description)
values(RM.SEQ_EID.nextval,sysdate,sysdate,'username3','password3',1,'description3');
insert into RM.demo_security_user(EID,EITIME,EUTIME,username,password,access_level,description)
values(RM.SEQ_EID.nextval,sysdate,sysdate,'admin','admin',0,'admin');
insert into RM.demo_security_user(EID,EITIME,EUTIME,username,password,access_level,description)
values(RM.SEQ_EID.nextval,sysdate,sysdate,'user','user',1,'user');
dbMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.demo.DataMapper" >
<resultMap id="UserLoginInfo" type="com.demo.DbUser">
<id column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="access_level" property="access_level" jdbcType="FLOAT"/>
<result column="description" property="description" jdbcType="VARCHAR"/>
</resultMap>
<select id="getUserLoginInfo" resultMap ="UserLoginInfo" >
select username, password, access_level,description from rm.demo_security_user t
where 1=1 and t.username= #{username,jdbcType=VARCHAR}
</select>
</mapper>
admin.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Admin Page</title>
</head>
<body>
<h1>Admin Page!</h1>
<p>This is logged page. every ROLE_ADMIN can be visited.</p>
<p>
Click <a th:href="@{/hello}">here</a> to hello page
</p>
<p>
Click <a th:href="@{/logout}">here</a> to logout.
</p>
</body>
</html>
denied.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Denied visit page!</title>
</head>
<body>
<h1>Your access is denied</h1>
<p>This is a visit denied page.</p>
<p>
Click <a th:href="@{/hello}">here</a> to hello page
</p>
<p>
Click <a th:href="@{/logout}">here</a> to logout.
</p>
</body>
</html>
hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
<p>This is logged page. every body can be visited.</p>
<div sec:authorize="hasRole('ROLE_ADMIN')">
<p>This is massage only ROLE_ADMIN can be visited.</p>
</div>
<!-- 通过标签鉴权,对应不同角色显示不同信息 -->
<div sec:authorize="hasRole('ROLE_USER')">
<p>This is massage only ROLE_USER can be visited.</p>
</div>
<p>
Click <a th:href="@{/logout}">here</a> to logout.
</p>
<p>
Click <a th:href="@{/admin}">here</a> to admin page.
</p>
</body>
</html>
home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome the home page!</h1>
<p>
Click <a th:href="@{/hello}">here</a> to login.
</p>
</body>
</html>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<div th:if="${param.error}">Invalid username and password.</div>
<div th:if="${param.logout}">You have been logged out.</div>
<h2>使用账号密码登录</h2>
<form th:action="@{/login}" method="post">
<div>
<label> User Name : <input type="text" name="username" />
</label>
</div>
<div>
<label> Password: <input type="password" name="password" />
</label>
</div>
<div>
<input type="submit" value="Sign In" />
</div>
</form>
</body>
</html>
额,要吐槽一下很多博主了,说的很详细,可是不留源码,对于我等小白真的是痛苦不堪,嘿嘿。
所以最后,再贴一遍源码地址:https://github.com/deargo/SpringBootMyBatisSpringSecurity