之前有用 shiro,这里采用spring security做权限区分。不用的角色登陆展示不同的页面。包含记住账号密码的功能(这个登陆后关闭浏览器,下次打开浏览器还是处于登陆状态)
1.pom引入依赖
这里额外加的thymeleaf是为了方便写页面。而springsecurity5是因为我喜欢用springboot2.x版本,如果是springboot1.x版本的话是引入springsecurity4。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId></dependency>
2.编写配置类
如果是采用springboot2.x版本的话,需要在WebSecurityConfig的认证规则额外加.passwordEncoder(new MyPasswordEncoder())的设置。
MyPasswordEncoder是自己新建的
public class MyPasswordEncoder implements PasswordEncoder {@Overridepublic String encode(CharSequence charSequence) {return charSequence.toString();}@Overridepublic boolean matches(CharSequence charSequence, String s) {return s.equals(charSequence.toString());}}
WebSecurityConfig写法: ```java
@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Overrideprotected void configure(HttpSecurity http) throws Exception {//定制请求的授权规则http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("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("remeber");//登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录//点击注销会删除cookie}//定义认证规则@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//super.configure(auth);auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("zhangsan").password("123456").roles("VIP1","VIP2").and().withUser("lisi").password("123456").roles("VIP2","VIP3").and().withUser("wangwu").password("123456").roles("VIP1","VIP3");}
}
<a name="cAzMq"></a># 3.页面代码1. 首页1. sec标签有点类似jsp里的c标签;sec:authorize类似c:if```html<html xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"><!--没有登陆的时候--><div sec:authorize="!isAuthenticated()"></div><!--登陆后--><div sec:authorize="isAuthenticated()"></div><!--角色是vip1的时候--><div sec:authorize="hasRole('VIP1')"></div>
登录页
<form th:action="@{/userlogin}" method="post">用户名:<input name="user"/><br>密码:<input name="pwd"><br/><input type="checkbox" name="remeber"> 记住我<br/><input type="submit" value="登陆"></form>
4.效果展示
首页游客

- 登陆页
 
这里设置成了自己的登录页,没用security默认登陆页
- 拥有VIP1和VIP2的zhangsan登陆
 

- 拥有VIP2和VIP3的lisi登陆
 
5.相关代码
链接:https://pan.baidu.com/s/1eVRwqs21GvpS8SreowoGaA 
提取码:j39b
