前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Security - 02 从 SecurityContextHolder 中获取用户信息

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

原创
作者头像
用户6619361
发布2022-04-20 17:00:34
2K0
发布2022-04-20 17:00:34
举报
文章被收录于专栏:Spring Security

@toc

环境

操作系统:

代码语言:txt
复制
Windows 10 x64

集成开发环境:

代码语言:txt
复制
Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750

浏览器(客户端):

代码语言:txt
复制
Google Chrome
版本 97.0.4692.71(正式版本) (64 位)

项目结构

参考:Spring Security - 01 新建项目

在这里插入图片描述
在这里插入图片描述

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

代码语言:java
复制
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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 环境
  • 项目结构
  • 测试
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档