在SpringBoot中简单使用Spring Security(随笔)
-
导入相关依赖 ;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
-
定义一个Spring Security配置类继承自WebSecurityConfigurerAdapter类,在此类上加@EnableWebSecurity注解;并在此类中进行一些简单的配置。
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"); //formLogin()当用户没有权限进入相应页面时他会跳转到spring security自己的登陆页面; //loginPage("跳转到登陆页面的请求")会重定向到用户相应的登录页面,; //需要提交登录请求到loginProcessingUrl("登录请求"),请求方式为必须Post, http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); //防止跨站请求伪造攻击 http.csrf().disable(); //将登录用户信息保存到Cookie http.rememberMe(); //Spring Security注销方法logout(),logoutSuccessUrl("指定路径")注销成功后到指定页面 http.logout().logoutSuccessUrl("/"); } //认证 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //在内存中获取用户信息,对对应的用户可以访问的权限进行授权, //指定相应的用户的密码时需被加密, auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("xiaoguo") .password(new BCryptPasswordEncoder() .encode("123456")).roles("vip1","vip2") .and() .withUser("root") .password(new BCryptPasswordEncoder() .encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("guest") .password(new BCryptPasswordEncoder() .encode("123456")).roles("vip1"); } }