SecurityContextHolder.getContext().getAuthentication()显示anonymousUser匿名用户问题

项目场景:在使用Spring security做用户认证从SecurityContextHolder中获取用户信息时,遇见如下问题:

分析原因:获取不到登录时储存的用户信息,猜测可能是在执行完某些操作之后将用户信息替换或者直接清空了。查看SecurityContextHolder的api发现里面有个clearContext()方法,通过debug模式发现当执行完org.springframework.security.web.context.SecurityContextPersistenceFilter和org.springframework.security.web.FilterChainProxy过滤器时会调用SecurityContextHolder.clearContext()方法把SecurityContextHolder清空,所以获取不到存储的用户信息。

解决方案:找到了问题所在就好解决了,可以自定义过滤器重新保存用户认证信息,如代码中自定义的MyAuthenticationTokenGenericFilter

改进之后的结果如下:

需要注意的是,如果需要用到权限认证,还需保存用户的权限信息,我这里暂时不用,所以没保留,只需要替换成这个构造函数就可以new UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities)

posted @ 2020-06-01 15:49  聚散彡流沙  阅读(13350)  评论(4编辑  收藏  举报