- 环境搭建:导入依赖,完成跳转的设置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency>
- 用户认证和授权:
//首页所有人都可以访问,功能页只能有对应权限的人才能访问 //请求授权的规则 http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); //没有权限默认会到登录页面 //定制登录页 http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
//这些数据正常应该从数据库中获取 认证 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3") .and() .withUser("2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
- 注销和权限控制
//注销 开启了注销功能,跳到首页 //防止网站攻击: get post http.csrf().disable();//关闭csrf(跨站请求攻击功能)登出失败的可能原因 http.logout().logoutSuccessUrl("/");
<!--登录注销--> <div class="right menu"> <!--如果未登录--> <div sec:authorize="!isAuthenticated()"> <a class="item" th:href="@{/toLogin}"> <i class="address card icon"></i> 登录 </a> </div> <!--如果已登录:用户名、注销--> <!--注销--> <div sec:authorize="isAuthenticated()"> <a class="item" > 用户名:<span sec:authentication="name"></span> 角色:<span sec:authentication="authorities"></span> </a> </div> <div sec:authorize="isAuthenticated()"> <a class="item" th:href="@{/logout}"> <i class="sign-out icon"></i>注销 </a> </div> </div>
<div class="column" sec:authorize="hasRole('vip1')"> <div class="ui raised segment"> <div class="ui"> <div class="content"> <h5 class="content">Level 1</h5> <hr> <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div> <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div> <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div> </div> </div> </div> </div>
- 记住我功能
//login.html <div class="field"> <input type="checkbox" name="remember"> 记住我 </div>
//开启记住我功能 cookie 默认是两周 //自定义接收前端的参数 http.rememberMe().rememberMeParameter("remember");