SpringSecurity是一种基于Spring应用提供的声明式的安全保护性的框架,它可以在web请求级别的和方法调用级别处理身份和授权。
首先需要在Maven中导包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
因为SpringSecurity是基于Spring的安全性框架,所以可以完美契合SpringBoot,导完包就可以直接使用了,与SpringBoot扩展配置MVC一样,也需要先建一个SecurityConfig配置类。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}
这个SecurityConfig
配置类需要继承WebSecurityConfigurerAdapter
。然后配置注解@EnableWebSecurity
将其由Spring托管。
然后就是简单的用户认证和授权功能,只需要重写两个方法。
@Override
protected void configure(HttpSecurity http) throws Exception {
/**授权:*/
/*首页所有人可以访问,功能页只有对应有权限(vip)的人才能访问*/
http.authorizeRequests().antMatchers("/index").permitAll()
.antMatchers("/Dashboard/**").hasRole("vip");
/*没有权限进入登录界面 默认跳转地址:/login Security默认页面*/
http.formLogin()
.loginPage("无权限跳转的页面地址");
/*注销登录 :/logout 删除cookie*/
http.logout()
.logoutUrl("自定义登出页面的地址")
/*要删除的cookie 的key*/
.deleteCookies("JSESSIONID")
/*清空session*/
.invalidateHttpSession(true);
}
然后就是用户认证,给符合条件的对应用户添加权限。
@Autowired
private LoginMapper loginMapper;
/**用户认证,并对用户密码进行加密--BCryptPasswordEncoder*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
for (int i = 0; i < loginMapper.queryUser().size();i++){
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser(loginMapper.queryUser().get(i).getUsername())
.password(new BCryptPasswordEncoder().encode(loginMapper.queryUser().get(i).getPassword()))
.roles("vip");
}
}
这里我用的是从内存读取数据,inMemoryAuthentication()
,当然也可以选择连接数据库从数据库中直接读取,那么只要使用jdbcAuthentication()
以及对应方法即可。还要装配数据源的bean。
@Autowired
private DataSource dataSource;
这里为了数据安全,还要对用户密码进行加密,使用.passwordEncoder(new BCryptPasswordEncoder())
方法new BCryptPasswordEncoder().encode()
即可将用户密码进行密文传递,保证安全性。