使用shiro的SecurityUtils.getSubject().getPrincipal()获取当前登录用户信息遇到的问题总结一下
1.检查配置是否正确
(1)设置配置AuthorizationAttributeSourceAdvisor 在整个类的最前面,至少在shiroFilterFactoryBean的前面
/**
* 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions)
* @return
* DefaultAdvisorAutoProxyCreator的顺序必须在shiroFilterFactoryBean之前,不然SecurityUtils.getSubject().getPrincipal()获取不到参数
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
advisorAutoProxyCreator.setUsePrefix(true);
return advisorAutoProxyCreator;
}
/**
* 开启aop注解支持
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
(2)开启advisorAutoProxyCreator.setUsePrefix(true);
2.自己要获取的用户信息在代码是否设置过
Q:SecurityUtils.getSubject().getPrincipal()获取的用户信息是在哪里设置的?
自定义realm类--》doGetAuthenticationInfo()方法--》SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), byteSourceSalt, getName());
方法第一个参数user,这里设置的就是SecurityUtils.getSubject().getPrincipal()获取的值,还可以可以设置String和对象等类型。
3.访问的接口需要在ShiroFilterFactoryBean里面配置拦截规则,没有配置过的也不生效。
比如:filterChainDefinitionMap.put("/static/**", "anon");