Spring Security提供了一个实现了可以缓存UserDetails的UserDetailsService实现类,CachingUserDetailsService。该类的构造接收一个用于真正加载UserDetails的UserDetailsService实现类。当需要加载UserDetails时,其首先会从缓存中获取,如果缓存中没有对应的UserDetails存在,则使用持有的UserDetailsService实现类进行加载,然后将加载后的结果存放在缓存中。UserDetails与缓存的交互是通过UserCache接口来实现的。CachingUserDetailsService默认拥有UserCache的一个空实现引用,NullUserCache。以下是CachingUserDetailsService的类定义。

public class CachingUserDetailsService implements UserDetailsService {

private UserCache userCache = new NullUserCache();

private final UserDetailsService delegate;

CachingUserDetailsService(UserDetailsService delegate) {

this.delegate = delegate;

}

public UserCache getUserCache() {

return userCache;

}

public void setUserCache(UserCache userCache) {

this.userCache = userCache;

}

public UserDetails loadUserByUsername(String username) {

UserDetails user = userCache.getUserFromCache(username);

if (user == null) {

user = delegate.loadUserByUsername(username);

}

Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". " +

"This is an interface contract violation");

userCache.putUserInCache(user);

return user;

}

}

我们可以看到当缓存中不存在对应的UserDetails时将使用引用的UserDetailsService类型的delegate进行加载。加载后再把它存放到Cache中并进行返回。除了NullUserCache之外,Spring Security还为我们提供了一个基于Ehcache的UserCache实现类,EhCacheBasedUserCache,其源码如下所示。

public class EhCacheBasedUserCache implements UserCache, InitializingBean {

private static final Log logger = LogFactory.getLog(EhCacheBasedUserCache.class);

private Ehcache cache;

public void afterPropertiesSet() throws Exception {

Assert.notNull(cache, "cache mandatory");

}

public Ehcache getCache() {

returncache;

}

public UserDetails getUserFromCache(String username) {

Element element = cache.get(username);

if (logger.isDebugEnabled()) {

logger.debug("Cache hit: " + (element != null) + "; username: " + username);

}

if (element == null) {

returnnull;

else {

return (UserDetails) element.getValue();

}

}

public void putUserInCache(UserDetails user) {

Element element = new Element(user.getUsername(), user);

if (logger.isDebugEnabled()) {

logger.debug("Cache put: " + element.getKey());

}

cache.put(element);

}

public void removeUserFromCache(UserDetails user) {

if (logger.isDebugEnabled()) {

logger.debug("Cache remove: " + user.getUsername());

}

this.removeUserFromCache(user.getUsername());

}

public void removeUserFromCache(String username) {

cache.remove(username);

}

public void setCache(Ehcache cache) {

this.cache = cache;

}

}

从上述源码我们可以看到EhCacheBasedUserCache所引用的Ehcache是空的,所以,当我们需要对UserDetails进行缓存时,我们只需要定义一个Ehcache实例,然后把它注入给EhCacheBasedUserCache就可以了。接下来我们来看一下定义一个支持缓存UserDetails的CachingUserDetailsService的示例。

<security:authentication-manager alias="authenticationManager">

<!-- 使用可以缓存UserDetails的CachingUserDetailsService -->

<security:authentication-provider

user-service-ref="cachingUserDetailsService" />

</security:authentication-manager>

<!-- 可以缓存UserDetails的UserDetailsService -->

<bean id="cachingUserDetailsService"class="org.springframework.security.config.authentication.CachingUserDetailsService">

<!-- 真正加载UserDetails的UserDetailsService -->

<constructor-arg ref="userDetailsService"/>

<!-- 缓存UserDetails的UserCache -->

<property name="userCache">

<beanclass="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache">

<!-- 用于真正缓存的Ehcache对象 -->

<property name="cache" ref="ehcache4UserDetails"/>

</bean>

</property>

</bean>

<!-- 将使用默认的CacheManager创建一个名为ehcache4UserDetails的Ehcache对象 -->

<bean id="ehcache4UserDetails"class="org.springframework.cache.ehcache.EhCacheFactoryBean"/>

<!-- 从数据库加载UserDetails的UserDetailsService -->

<bean id="userDetailsService"

class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">

<property name="dataSource" ref="dataSource" />

</bean>

在上面的配置中,我们通过EhcacheFactoryBean定义的Ehcache bean对象采用的是默认配置,其将使用默认的CacheManager,即直接通过CacheManager.getInstance()获取当前已经存在的CacheManager对象,如不存在则使用默认配置自动创建一个,当然这可以通过cacheManager属性指定我们需要使用的CacheManager,CacheManager可以通过EhCacheManagerFactoryBean进行定义。此外,如果没有指定对应缓存的名称,默认将使用beanName,在上述配置中即为ehcache4UserDetails,可以通过cacheName属性进行指定。此外,缓存的配置信息也都是使用的默认的。更多关于Spring使用Ehcache的信息可以参考我的另一篇文章《Spring使用Cache》。

(注:本文是基于Spring Security3.1.6所写)

Spring Security(07)——缓存UserDetails的更多相关文章

  1. Spring Boot Oauth2缓存UserDetails到Ehcache

    在Spring中有一个类CachingUserDetailsService实现了UserDetailsService接口,该类使用静态代理模式为UserDetailsService提供缓存功能.该类源 ...

  2. 深入Spring Security魔幻山谷-获取认证机制核心原理讲解(新版)

    文/朱季谦 本文基于Springboot+Vue+Spring Security框架而写的原创学习笔记,demo代码参考<Spring Boot+Spring Cloud+Vue+Element ...

  3. 「快学springboot」集成Spring Security实现鉴权功能

    Spring Security介绍 Spring Security是Spring全家桶中的处理身份和权限问题的一员.Spring Security可以根据使用者的需要定制相关的角色身份和身份所具有的权 ...

  4. 4-11 Spring Security及SSO

    1. 关于用户身份认证与授权 Spring Security是用于解决认证与授权的框架. 在根项目下创建新的csmall-passport子模块,最基础的依赖项包括spring-boot-starte ...

  5. spring security 控制用户信息用户加密 缓存用户信息

    1. MD5加密 任何一个正式的企业应用中,都不会在数据库中使用明文来保存密码的,我们在之前的章节中都是为了方便起见没有对数据库中的用户密码进行加密,这在实际应用中是极为幼稚的做法.可以想象一下,只要 ...

  6. Ajax登陆,使用Spring Security缓存跳转到登陆前的链接

    Spring Security缓存的应用之登陆后跳转到登录前源地址 什么意思? 用户访问网站,打开了一个链接:(origin url)起源链接 请求发送给服务器,服务器判断用户请求了受保护的资源. 由 ...

  7. Spring Boot整合实战Spring Security JWT权限鉴权系统

    目前流行的前后端分离让Java程序员可以更加专注的做好后台业务逻辑的功能实现,提供如返回Json格式的数据接口就可以.像以前做项目的安全认证基于 session 的登录拦截,属于后端全栈式的开发的模式 ...

  8. Spring Security 教程 大牛的教程

    https://www.iteye.com/blog/elim-2247073 Spring Security 教程 Spring Security(20)——整合Cas Spring Securit ...

  9. Spring Security Architecture and Implementation(架构和实现)学习笔记

    Spring Security 关于spring-security的官网文档学习笔记,主要是第8章 Architecture and Implementation(架构和实现)内容 参考: https ...

随机推荐

  1. 使用java连接MySql,中文乱码解决的方法

    排查MySql中文乱码的问题 1.在cmd中启动MySql. 打开命令提示符cmd,输入"mysql -uusername -ppassword",回车,就可以连接到数据库. 如输 ...

  2. 【NOIP2014】Day1题解+代码

    Day1 T1 签到题,模拟一下随便写就能过. 不过小心像我一样表打错傻逼的调了10min. #include <algorithm> #include <iostream> ...

  3. kworker

    通过 ps 命令查看进程状态时,可以查看到kworker相关, 大部分格式都是  kworker /u2:0 或者  kworker /0:0H, 查看资料得知: 内核中有很多kworker,有绑定c ...

  4. 实战ASP.NET访问共享文件夹(含详细操作步骤)

    博客园找找看(http://zzk.cnblogs.com)的索引文件占用空间太大,需要移至另外一台服务器,所以要解决"在ASP.NET中通过共享文件夹访问索引文件"的问题. 假设 ...

  5. flume 以 kafka 为channel 的配置

    #此配置以kafka的一个topic为channel,相比其他channel类型 file和cache 兼并了快和安全的要求!# Define a kafka channel a1.channels. ...

  6. MySQL连接无法解析HOST主机名

    #1042 - Can't get hostname for your address 使用IP链接或域名链接都可能遇到这个问题 解决办法: my.ini 或 my.cnf 末尾添加 skip-nam ...

  7. Linux下服务器环境的搭建和配置之一——Apache篇

    最近一个多月(2016-06-20开始至今),一直在忙海外广告平台FAQ系统的开发,既要负责服务器环境的搭建,又要写前端,还要写后台和数据库,甚至还要考虑产品需求和设计.所以是一个很大的挑战,对自身也 ...

  8. 5.Struts2的OGNL表达式

    1.创建javaweb项目Struts2_Part4_OGNL并在WebRoot下的WEB-INF下的lib文件夹下添加如下jar文件 commons.jar commons.jar freemark ...

  9. redis写shell与ssh免密码登陆

     redis-cli参数:-h :指定要连接的主机IP或域名-p :指定连接的端口-a :指定密码-r :执行指定的命令-n :数据库名-x :将最后一个参数输出为value redis写shell- ...

  10. js获取计算的样式(非行间样式)

    function getStyle(obj, attr){ if(obj.currentStyle){ style = obj.currentStyle[attr]; //兼容IE8以下 }else{ ...