springboot底层是用spring security作为安全框架的。
总的来说就两部分:授权+认证。
一、Security使用
1)利用idea向导创建项目
启动完项目后,我们访问localhost:8080发现访问被拦截,需要登录,效果图如下;
2)编写配置类
extends WebSecurityConfigurerAdapter
1.先定义先定义请求的授权规则
@EnableWebSecurity(底层点开是@Configuration,所以无需加配置类注解)
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
//先定义请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
}
}
效果图:
这个时候我们发现,除了首页是可以访问的,其他页面访问都会被拒绝,因为没有角色;
这个时候我们可以对没有访问权限的页面利用http.formLogin()方法,让其跳转到默认的登录页面
用户名密码输入错误的效果图
说明:
http.formLogin() 开启springboot security自动配置的登录功能;
1.可通过/login路径直接访问springboot Security该默认登录页面
2.重定向到/login?error表示登录失败
2.定义认证规则
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
//先定义请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
http.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
auth.inMemoryAuthentication().withUser("zhangsan").password("123").roles("VIP1","VIP2")
.and().withUser("lisi").password("123").roles("VIP2","VIP3")
.and().withUser("wangwu").password("123").roles("VIP1","VIP3");
}
}
我们再来看看效果:
控制台报错,问题不大。
这是因为Spring boot 2.0.3引用的security 依赖是 spring security 5.X版本,此版本需要提供一个PasswordEncorder的实例,否则后台汇报错误:
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
再改一下我们原来的代码,用上这个PasswordEncorder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("zhangsan").password("123").roles("VIP1","VIP2")
.and().withUser("lisi").password("123").roles("VIP2","VIP3")
.and().withUser("wangwu").password("123").roles("VIP1","VIP3");
}
这个时候我们用zhangsan账号登录,发现VIP1和VIP2的两块我们是能访问的,VIP3我们还是无权限访问,这样就对了,效果图:
3.加上注销功能
http.logout(); 开启springboot security自动配置的注销功能;
1.访问/logout 表示注销用户,清空session
2.注销成功会返回 /login?logout
所以我们可以手动设置 注销成功后返回的页面
http.logout().logoutSuccessUrl("/"); //返回到首页
对应前台:
注意这边的/logout 为post请求,要加上!
<div sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>,您好,您的角色有
<span sec:authentication="principal.authorities"></span>
<form th:action="@{/logout}" method="post">
<input type="submit" th:value="注销">
</form>
</div>
在前台html代码加上注销的功能:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
<form th:action="@{/logout}">
<input type="submit" th:value="注销">
</form>
<hr>
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</body>
</html>
效果图:
4.用security显示用户和角色
1.去maven respository 查找thymeleaf对spring security的支持
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
2.引入名称空间
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
1)demo是否认证:
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
<form th:action="@{/logout}">
<input type="submit" th:value="注销">
</form>
</div>
2)名称和角色
<div sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>,您好,您的角色有
<span sec:authentication="principal.authorities"></span>
<form th:action="@{/logout}">
<input type="submit" th:value="注销">
</form>
</div>
这个时候 可能会出现sec名称不起作用的问题,这时候需要将 上方的依赖修改一下,pom文件里面的springsecurity4改成springsecurity5,如下
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
3)根据角色权限显隐
<div sec:authorize="hasRole('VIP1')">
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
</div>
4)自带的默认记住我功能
http.rememberMe(); 开启记住我功能
登录成功后,将cookie发给浏览器缓存, 以后访问页面带上这个cookie,只要通过检查就可以免登录;
点击注销会删除cookie;
我们f12查看浏览器,可以发现有一个cookie,有效期14天,如下图:
5)自定义登录页面,不用springboot security默认的登录页面
指定登录页面
http.formLogin().loginPage("/userlogin");
第一个注意点:springSecurity默认的登录请求是post请求的/login访问,所以在自定义登录界面可直接写默认登录路径:/login;
第二个注意点:下面是对于loginPage()这个方法的解释
解释:
默认登录:
/login 是get请求方式,则会跳到 默认的登录页面
/login 是post请求方式,则会执行登录
自定义的登录:
/xxx 是get请求方式,则会跳到 自定义的登录页面
/xxx 是post请求方式,则会执行登录
所以在自定义的登录页面,比如下面的,是/userlogin是get请求页面:
则在html页面上,post请求登录也需要填写/userlogin,并需要绑定参数名称
这是get请求页面
/**
* 登陆页
* @return
*/
@GetMapping("/userlogin")
public String loginPage() {
return PREFIX+"login";
}
后台绑定参数:
http.formLogin().usernameParameter("username").passwordParameter("pwd").loginPage("/userlogin");
登录请求也需要用/userlogin,只不过这边是post请求
<form th:action="@{/userlogin}" method="post">
用户名:<input th:name="username"/><br>
密码:<input th:name="pwd"><br/>
<input type="submit" value="登陆">
</form>
最终的html页面代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>,您好,您的角色有
<span sec:authentication="principal.authorities"></span>
<form th:action="@{/logout}" method="post">
<input type="submit" th:value="注销">
</form>
</div>
<hr>
<div sec:authorize="hasRole('VIP1')">
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP2')">
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP3')">
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</div>
</body>
</html>
6)自定义记住我功能
前台代码加上勾选框
<div align="center">
<form th:action="@{/userlogin}" method="post">
用户名:<input th:name="username"/><br>
密码:<input th:name="pwd"><br/>
<input type="checkbox" name="remember">记住我<br>
<input type="submit" value="登陆">
</form>
</div>
后台加上参数绑定
http.rememberMe().rememberMeParameter("remember");