美文网首页Spring SecuritySpring-Boot
Spring-Security-教程(四)--权限动态修改

Spring-Security-教程(四)--权限动态修改

作者: 老亚瑟程序猿 | 来源:发表于2019-04-03 12:12 被阅读0次

前言

本篇pom.xml与上篇文章 Spring Security 入门教程(三)- 基于登录认证记住我实例 相同。

项目代码:https://github.com/Bootcap/spring-security-study-session

一、新建VipController.java

package com.bootcap.session.security.controller;

/**
 * 动态权限修改Controller
 * 2018-12-15 14:16
 */
@Controller
@ResponseBody
public class VipController {

    @RequestMapping(value = "/vip/index",method = RequestMethod.GET)
    public String vipPage(){
        return "只有VIP用户可观看";
    }

    @RequestMapping(value = "/getVIP",method = RequestMethod.GET)
    public String getVip(){
        // 获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<GrantedAuthority> update = new ArrayList<>(authentication.getAuthorities());
        // 添加VIP授权
        update.add(new SimpleGrantedAuthority("ROLE_VIP"));
        // 生成新的认证信息
        Authentication newAuth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), update);
        SecurityContextHolder.getContext().setAuthentication(newAuth);
        return "ok";
    }
}

二、修改WebSecurityConfig.java

package com.bootcap.session.security.configuration;

/**
 * 2018-12-10 11:03
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/getVIP").permitAll()
                .antMatchers("/vip/index").hasRole("VIP");
    }

}

三、启动测试

3.1 假设当前你的权限只有 ROLE_USER的时候访问:localhost:8080/vip/index 时页面会提示403,同时控制台也会抛出“Access is denied 无权限”异常(提示:若没有异常可以在application.yml下修改:org.springframework.security: debug)。


3.2 开启另外窗口,访问:localhost:8080/getVIP 地址,返回了"ok",再刷新页面即可正常访问;


上一篇: Spring Security 入门教程(三)- 基于登录认证记住我实例
上一篇: Spring Security (五) - 实现QQ授权登录

相关文章

网友评论

    本文标题:Spring-Security-教程(四)--权限动态修改

    本文链接:https://www.haomeiwen.com/subject/spbabqtx.html