SecurityContextHolder.getContext().getAuthentication().getPrincipal()
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
安全包括两个主要操作。
第一个被称为“认证”,是为用户建立一个他所声明的主题。主题一般式指用户,设备或可以在你系统中执行动作的其他系统。
第二个叫“授权”,指的是一个用户能否在你的应用中执行某个操作,在到达授权判断之前,身份的主题已经由身份验证过程建立。
1. 在web.xml文件中加入Filter声明
Xml代码
- <</span>filter>
- <</span>filter-name>springSecurityFilterChain</</span>filter-name>
- <</span>filter-class>org.springframework.web.filter.DelegatingFilterProxy</</span>filter-class>
- </</span>filter>
- <</span>filter-mapping>
- <</span>filter-name>springSecurityFilterChain</</span>filter-name>
- <</span>url-pattern>/*</</span>url-pattern>
- </</span>filter-mapping>
获得当前已认证的用户的名字(obtain the name of the currently authenticated user)
(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
官方案例如下:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
访问受保护的资源