环境
操作系统:
Windows 10 x64
集成开发环境:
Spring Tool Suite 4
Version: 4.12.1.RELEASE
Build Id: 202110260750
浏览器(客户端):
Google Chrome
版本 97.0.4692.71(正式版本) (64 位)
# 项目结构
新建 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 会先要求我们登录,登录成功之后就可以看到服务器返回用户的信息: