第一步:加入security启动器依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
第二步:创建security的配置类:
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@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");
http.formLogin();
http.logout().logoutSuccessUrl("/");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("min").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("person").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
特别说明:
- 继承的WebSecurityConfigurerAdapter不要导错包了,否则会缺失方法
- 关于security配置中的方法都是链式编程的思想(简单上手)
- 使用到了AOP的知识,不需要修改源代码,相同的还有拦截器等
- configure(HttpSecurity http)该重写方法是依靠url地址来识别的
- 500服务器异常:在给用户密码的时候记得使用加密编码,否则高一点的Security会报500异常,这也是为了安全着想,否则反编译过来看到源码就危险了!
- 403权限不够异常
http.formLogin() 中体现了spring的约定大于配置,如,没有角色认证的用户在请求到权限网页时会自动跳转到login页面.看源码,有说明!- 登录与注销的跳转页面应为:/toLogin与/logout,在
http.logout() 中的源码有说明
public LogoutConfigurer<HttpSecurity> logout() throws Exception {
return getOrApply(new LogoutConfigurer<>());
}
|