Spring Security - 02 从 SecurityContextHolder 中获取用户信息

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750

浏览器(客户端):

Google Chrome
版本 97.0.4692.71(正式版本) (64 位)

# 项目结构

参考:Spring Security - 01 新建项目

在这里插入图片描述

新建 HelloController 控制器类,我们可以通过 SecurityContextHolder 获取用户信息(第 17 ~ 19 行):

package com.mk.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @RequestMapping(method = RequestMethod.GET, path = "principal")
    @ResponseBody
    public Object principal() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        return principal;
    }
}

测试

启动项目,打开浏览器,访问 http://localhost:8080/principal,由于我们没有通过身份认证,Spring Security 会先要求我们登录,登录成功之后就可以看到服务器返回用户的信息:

在这里插入图片描述

参考

Spring Security - 01 新建项目

Spring Security / Servlet Applications / Authentication / Authentication Architecture / Servlet Authentication Architecture / SecurityContextHolder

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值