pom.xml引入SpringSecurity包
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>
可以拓展WebSecurityConfigurerAdapter方式做全局的权限控制
权限控制可能使用的时JPA,而非Ibatis等,这种方式直接设置全局的,并不需要If/else等判断逻辑。
这里以user/123456为例 ,但是注意现实使用时不要使用弱口令。
新版SpringBoot更新,要求使用BCryptPasswordEncoder这些来先加密。
import org.springframework.context.annotation.Configuration;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;@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter {/**定义认证用户信息获取来源,密码校验规则等*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//inMemoryAuthentication 从内存中获取auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");//jdbcAuthentication从数据库中获取,但是默认是以security提供的表结构//usersByUsernameQuery 指定查询用户SQL//authoritiesByUsernameQuery 指定查询权限SQL//auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(query).authoritiesByUsernameQuery(query);//注入userDetailsService,需要实现userDetailsService接口//auth.userDetailsService(userDetailsService);}/**定义安全策略*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()//配置安全策略.antMatchers("/","/hello").permitAll()//定义/请求不需要验证.anyRequest().authenticated()//其余的所有请求都需要验证.and().logout().permitAll()//定义logout不需要验证.and().formLogin();//使用form表单登录}}
参考逻辑表如下

