文章目录
SpringSecurity
springsecurity是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
springsecurity是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring安全性的真正威力在于它可以很容易地扩展以满足定制需求。
简单使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
创建boot项目,导入security依赖,编写一个主页controller,启动项目后访问,发现跳到一个登录页面。
于是猜想是security提供的登录页面,查看properties,找到了用户名为user,密码为随机生成的uuid,并且打印在了控制台,于是登录成功。
既然是配置类,当然就可以配置密码等。
spring.security.user.password=123456
简单的授权及认证
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//请求授权规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认跳到security的login登录页,loginpage设置请求自己的login页面
http.formLogin().loginPage("/toLogin");
//开启注销,security的logout
http.csrf().disable();
http.logout().logoutSuccessUrl("/");
//开启记住我,cookies实现
http.rememberMe().rememberMeParameter("remember");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//基于内存用户认证
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("yao")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("vip2","vip3")
.and()
.withUser("root")
.password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
}
}
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
thymeleaf和security有很好的支持,通过一些标签语法可以实现前端的认证。
判断权限
<div class="column" sec:authorize="hasRole('vip2')">
是否登录
<div sec:authorize="isAuthenticated()">
读取用户名和权限
<a class="item">
用户名: <span sec:authentication="name"></span>
角色: <span sec:authentication="principal.authorities"></span>
</a>
等等
总结
security的核心思想是aop,在没有改变源代码的情况下,通过javaconfig形式的配置文件,就能对于认证和授权进行配置。更多配置形式可以参照源码上的注释以及官方文档。