SpringBoot中使用Spring Security实现权限控制

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值