整合spring security
java web工程常用的安全框架:shiro、spring security
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型。
安全框架主要功能:
• “认证”(Authentication) ->通过用户名和密码登录,验证登录的人是谁;
• “授权”(Authorization) ->当前用户能干什么;
1.创建工程
新建一个工程,使用thymeleaf做模板引擎;
controller:
@Controller public class KungfuController { private final String PREFIX = "pages/"; /** * 欢迎页 * @return */ @GetMapping("/") public String index() { return "welcome"; } /** * 登陆页 * @return */ @GetMapping("/userlogin") public String loginPage() { return PREFIX+"login"; } /** * level1页面映射 * @param path * @return */ @GetMapping("/level1/{path}") public String level1(@PathVariable("path")String path) { return PREFIX+"level1/"+path; } /** * level2页面映射 * @param path * @return */ @GetMapping("/level2/{path}") public String level2(@PathVariable("path")String path) { return PREFIX+"level2/"+path; } /** * level3页面映射 * @param path * @return */ @GetMapping("/level3/{path}") public String level3(@PathVariable("path")String path) { return PREFIX+"level3/"+path; } }
启动工程:
没有加安全框架,所有的接口都能访问;
2.整合Spring Security
1)引入依赖
pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2)定制授权规则
大体是说:
WebSecurityConfigurerAdapter中有个configure方法,想自己定制http安全规则需要重写这个方法;
1】定制授权规则
新建一个配置类,继承WebSecurityConfigurerAdapter,重写configure(HttpSecurity http)方法;
使用@EnableWebSecurity开启web安全模式;
@EnableWebSecurity //开启web安全模式,这个注解已经包含了@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //定制http授权规则 @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() //认证请求 .antMatchers("/").permitAll() //请求路径"/"允许所有人访问 .antMatchers("/level1/**").hasRole("VIP1") //请求路径带"/level1"的只允许角色"VIP1"访问 .antMatchers("/level2/**").hasRole("VIP2") .antMatchers("/level3/**").hasRole("VIP3"); } }
测试:
重新启动工程,一些接口无法访问,报403无权限;
2】开启登录功能
为了能访问定制了安全规则的接口,需要开启登录功能,然后给登录的角色授权;
例如: .antMatchers("/level1/**").hasRole("VIP1"),表示登录的角色为“VIP1”才能访问/level1的接口;
步骤:configure(HttpSecurity http)方法中加上
http.formLogin();
作用:
接口“/login”对应默认登录页,(接口“/login”和默认登录页都是由SpringSecurity提供);
如果登录失败重定向到“/login?error”;
可以定制登录规则;
测试:
在浏览器中请求没有权限的:/level/1
结果:如果没有权限,自动跳到登录页
3】注销
在configure(HttpSecurity http)中加上:
http.logout().logoutSuccessUrl("/"); //开启注销功能,注销成功后跳到首页
作用:
访问“/logout”时清空session;
4】记住我功能
在configure(HttpSecurity http)中加上:
http.rememberMe();
作用:
默认登录页中多了一个remember勾选框,勾选后下次登录是会记住密码
登录成功后,会给浏览器添加一个cookie,名为remember-me
请求/logout注销时,会删除cookie
3)定制认证规则
用来给特定的登录用户授权,以便于访问需要权限的接口;
在配置类中重写configure(AuthenticationManagerBuilder auth)方法;
//定制认证规则 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() //在内存中的认证,也可以在数据库中认证,这里为了简单采用这种方式 .withUser("wst").password("123456").roles("VIP1", "VIP2") //给wst权限VIP1和VIP2 .and() .withUser("zgcf").password("123456").roles("VIP1", "VIP2", "VIP3"); }
踩坑:
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
原因:
Spring security 5.0中新增了多种加密方式,也改变了密码的格式
密码格式:{id}encodedPassword
现如今Spring Security中密码的存储格式是“{id}…………”
前面的id是加密方式,id可以是bcrypt、sha256等,后面跟着的是加密后的密码。
也就是说,程序拿到传过来的密码的时候,会首先查找被“{”和“}”包括起来的id,来确定后面的密码是被怎么样加密的,如果找不到就认为id是null。
解决:
我们要将前端传过来的密码进行某种方式加密,spring security 官方推荐的是使用bcrypt加密方式。
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("wst").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2");
测试:使用wst登录,wst有权限“VIP1、VIP2”
可访问:
不可访问:
3.thymeleaf模板中的安全属性
有时需要实现一些功能:
根据登录用户的权限不同,在页面上可见的内容不同;
pom依赖:
在thymeleaf中使用springsecurity标签需要:thymeleaf-extras-springsecurity
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency>
thymeleaf模板页面:
在<html>标签中加上:xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity
在需要的地方html标签中加上sec:属性;
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity"> <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()"> <h2><span sec:authentication="name"></span>,您好,您的角色有: <span sec:authentication="principal.authorities"></span></h2> <form th:action="@{/logout}" method="post"> <input type="submit" 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>
测试:
安全标签生效了;
4.定制登录页
SpringSecurity提供了默认的登录页,通过接口“/login”来请求;
也可定制自己的登陆页面,需要修改配置类;
配置类:
@EnableWebSecurity //开启web安全模式,这个注解已经包含了@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { //定制http授权规则 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //认证请求 .antMatchers("/").permitAll() //请求路径"/"允许所有人访问 .antMatchers("/level1/**").hasRole("VIP1") //请求路径带"/level1"的只允许角色"VIP1"访问 .antMatchers("/level2/**").hasRole("VIP2") .antMatchers("/level3/**").hasRole("VIP3"); //开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面 http.formLogin().usernameParameter("user").passwordParameter("pwd") .loginPage("/userlogin"); //1、/login来到登陆页 //2、重定向到/login?error表示登陆失败 //3、更多详细规定 //4、默认post形式的 /login代表处理登陆 //5、一但定制loginPage;那么 loginPage的post请求就是登陆 //开启自动配置的注销功能。 http.logout().logoutSuccessUrl("/");//注销成功以后来到首页 //1、访问 /logout 表示用户注销,清空session //2、注销成功会返回 /login?logout 页面; //开启记住我功能 http.rememberMe().rememberMeParameter("remember"); //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录 //点击注销会删除cookie } //定制认证规则 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() //在内存中的认证,也可以在数据库中认证,这里为了简单采用这种方式 .passwordEncoder(new BCryptPasswordEncoder()).withUser("wst").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2") //给wst权限VIP1和VIP2 .and() .passwordEncoder(new BCryptPasswordEncoder()).withUser("zgkm").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP2", "VIP3"); } }
登录页:
登录页的form表单要发post请求;
action请求的接口要与配置类中的一致;
用户名、密码的name属性要与配置类中的一致;
记住我的name属性要与配置类中指定的一致;
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1 align="center">欢迎登陆武林秘籍管理系统</h1> <hr> <div align="center"> <form th:action="@{/userlogin}" method="post"> 用户名:<input name="user"/> 密码:<input name="pwd"><br/> <input type="checkbox" name="remember">记住我<br/> <input type="submit" value="登陆"> </form> </div> </body> </html>