1.导包
SpringSecurity以及整合包
springsecurity5
<!--thymeleaf整合SpringSecurity-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.编写AOP横切思想的SpringSecurity
@EnableWebSecurity开启
extends WebSecurityConfigurerAdapter集成自
编写授权和认证
//Aop横切
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
//链式编程
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//登录页面和首页都可以访问,设置支出页面需要权限
//请求授权的规则
http.authorizeHttpRequests()
.antMatchers("/").permitAll()
.antMatchers("/selPanyMoney.do").permitAll()
.antMatchers("/index").hasRole("user")
.antMatchers("/zhichu").hasRole("kuaiji");
//初始默认会报错,跳到登录页面
http.formLogin().loginPage("/tologin").usernameParameter("uname").passwordParameter("password").loginProcessingUrl("/login");
//注销
//Springboot默认开启防止网络攻击post加密或者关闭
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
//开启记住我
//默认两周
//自定义
http.rememberMe().rememberMeParameter("remenmber");
}
//认证
//密码需要加密编码
//在SpringSecurity5.0+新增了很多加密方式
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//应该从数据库读取
//这个是仿写的数据
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("sheep").password(new BCryptPasswordEncoder().encode("5519")).roles("user","kuaiji")
.and()
.withUser("user").password(new BCryptPasswordEncoder().encode("5519")).roles("user");
}
}
http.formLogin().loginPage("/tologin").usernameParameter("uname").passwordParameter("password").loginProcessingUrl("/login");
与前端对应
loginPage("/tologin")指向我们登录界面如果没有那么就是默认的没有样式非常难看
usernameParameter("uname").passwordParameter("password")提交账号密码与角色去进行验证
loginProcessingUrl("/login")自带的验证方式不是自己编写的类
3.绑定前端
1.引入xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
<form class="m-t" role="form" method="post" th:action="@{/login}">
<div class="form-group">
<input type="text" class="form-control" th:placeholder="#{login.username}" name="uname" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" th:placeholder="#{login.password}" name="password" required="required">
</div>
<p class="text-muted text-center">
<input type="checkbox" name="remember">记住我
</p>
</form>
以下都必须对应版本好新版本必须5
判断角色权限如果有则给与显示 sec:authorize="hasRole('kuaiji')"
取出当前登录的用户名字 sec:authentication="name"
注意事项:
1. http.csrf().disable();关闭否则自己写的AJAX请求会403
2.springsecurity5版本才可以
3.账号密码一定要对应好