https://www.jianshu.com/p/defa75b65a46
只是这里需要改下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.csrf().disable() //关闭CSRF
.formLogin().loginPage("/login")
.loginProcessingUrl("/form")
.defaultSuccessUrl("/index") //成功登陆后跳转页面
.failureUrl("/loginError").permitAll();
}
}
基于注解的权限控制
需要在security配置类上加上注解@EnableGlobalMethodSecurity(prePostEnabled = true)
/**
* 为了浏览器直接调用,使用get请求
* @return
*/
@GetMapping("/add")
@PreAuthorize("hasAuthority('sys:user:add')")
public String addUser(){
return "success";
}
/**
* 为了浏览器直接调用,使用get请求
*/
@GetMapping("/put")
@PreAuthorize("hasAuthority('sys:user:put')")
public String putUser(){
return "success";
}
/**
* 为了浏览器直接调用,使用get请求
*/
@GetMapping("/get")
@PreAuthorize("hasAuthority('sys:user:get')")
public UserDao queryUser(){
UserDao userDao=new UserDao();
userDao.setUsername("lisi");
userDao.setPassword(new BCryptPasswordEncoder().encode("123456"));
userDao.setEmail("123@163.com");
return userDao;
}
/**
* 为了浏览器直接调用,使用get请求
*/
@GetMapping("/del")
@PreAuthorize("hasAuthority('sys:user:del')")
public String delUser(){
return "success";
}
常见的表达式
Spring Security可用表达式对象的基类是SecurityExpressionRoot。
表达式 描述
hasRole([role]) 用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去除参考Remove the ROLE_
hasAnyRole([role1,role2]) 用户拥有任意一个制定的角色时返回true
hasAuthority([authority]) 等同于hasRole,但不会带有ROLE_前缀
hasAnyAuthority([auth1,auth2]) 等同于hasAnyRole
permitAll 永远返回true
denyAll 永远返回false
anonymous 当前用户是anonymous时返回true
rememberMe 当前勇士是rememberMe用户返回true
authentication 当前登录用户的authentication对象
fullAuthenticated 当前用户既不是anonymous也不是rememberMe用户时返回true
hasIpAddress(‘192.168.1.0/24’)) 请求发送的IP匹配时返回true