其他分享
首页 > 其他分享> > Spring Boot+Spring Security:页面白名单和获取登录信息

Spring Boot+Spring Security:页面白名单和获取登录信息

作者:互联网

说明

(1)JDK版本:1.8

(2)Spring Boot 2.0.6

(3)Spring Security 5.0.9

(4)Spring Data JPA 2.0.11.RELEASE

(5)hibernate5.2.17.Final

(6)MySQLDriver 5.1.47

(7)MySQL 8.0.12

 

需求缘起

       在有些场景下我们要对一些url要设置白名单,比如注册页面,忘记密码,官网页面,那么怎么操作呐?还有我们登录成功之后,需要显示当前登录者的账号信息,那么这个又要怎么操作呐?

一、设置白名单

       设置白名单比较简单,这个在之前也有使用过了:

 

.antMatchers("/login").permitAll()

 

1.1 单个文件

比如这里允许/index为白名单:

 

http.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
            .antMatchers("/login").permitAll()// 设置所有人都可以访问登录页面
            .antMatchers("/","/index").permitAll()

 

 

1.2 目录下所有文件

       比如所有/test/下的所有文件都为白名单:

 

http.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
            .antMatchers("/login").permitAll()// 设置所有人都可以访问登录页面
            .antMatchers("/","/index").permitAll()
            .antMatchers("/test/**","/test1/**").permitAll()

 

 

1.3 目录下指定类型

       比如要把/res/的所有.js,html设置为白名单:

 

http.authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
            .antMatchers("/login").permitAll()// 设置所有人都可以访问登录页面
            .antMatchers("/","/index").permitAll()
            .antMatchers("/test/**","/test1/**").permitAll()
            .antMatchers("/res/**/*.{js,html}").permitAll()

 

 

二、获取登录信息

2.1 获取登录信息的方式

       主要是通过SecurityContextHolder获取到上下文SecurityContext,通过SecurityContext获取到权限信息Authentication,最后通过Authentication获取到当前的登录信息:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

 

2.2 返回当前的账号信息

       在HelloController中加入返回账号信息:

    @GetMapping({"","/","/index"})
    public String index(Model model) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)) {
            model.addAttribute("name","anonymous");
        }else {
            User user = (User)principal;
            model.addAttribute("name",user.getUsername());
        }
        return "/index";
    }

 

2.3 在首页显示当前账号信息

       修改index.html,显示name:

      <h1>欢迎使用Spring Security!
            当前登录账号:<label th:text="${name}"></label>
        </h1>

       访问效果如下:

标签:index,登录,Spring,permitAll,Boot,antMatchers,白名单
来源: https://blog.csdn.net/weixin_45863786/article/details/104903586