spring-security入门8---获取用户对象信息

本文详细介绍了在Spring Security框架下,如何通过三种不同的方法在控制器中获取当前登录用户的认证信息。第一种方法是从SecurityContextHolder中直接获取Authentication对象;第二种方法是通过方法参数注入Authentication对象;第三种方法是通过@AuthenticationPrincipal注解获取UserDetails对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目源码地址https://github.com/nieandsun/security

前面文章讲过 SecurityContextPersistenceFilter 请求进来时,会检查session,如果有SecurityContext(可以直接认为已经认证的对象)则拿出来放到线程里即SecurityContextHolder中,返回时校验SecurityContextHolder中是否有securityContext,有则放入session,从而实现认证信息在多个请求中共享。

从这里我们也可以知道在请求中可以从SecurityContextHolder里拿到用户信息。
代码如下:

    @GetMapping("/me1")
    public Object getCurrentUser1() {
        //方式1,直接从SecurityContextHolder中拿到Authentication对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }

    @GetMapping("/me2")
    public Object getCurrentUser2(Authentication authentication) {
        //方式2---方式1的简写版
        return authentication;
    }

    @GetMapping("/me3")
    public Object getCurrentUser3(@AuthenticationPrincipal UserDetails user) {
        //方式3,只获取User对象
        return user;
    }

其中方式1,2获取的对象信息(Authentication对象)和方式3获取的对象信息如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nrsc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值