SpringSecurity匿名用户访问权限
在SpringSecurity中定义一个匿名访问权限,实现未登录用户可以访问默写页面
1 <http use-expressions="false" entry-point-ref="casProcessingFilterEntryPoint"> 2 <intercept-url pattern="/cart/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/> 3 <intercept-url pattern="/**" access="ROLE_USER"/> 4 <custom-filter position="CAS_FILTER" ref="casAuthenticationFilter" /> 5 <custom-filter ref="requestSingleLogoutFilter" before="LOGOUT_FILTER"/> 6 <custom-filter ref="singleLogoutFilter" before="CAS_FILTER"/> 7 </http>
就是在第2行添加的内容。此处的意思是所有的/cart/**目录下的都可以访问,并且用户名统一为annonymousUser
结合SpringSecurity的匿名用户未登录访问和登录访问的判断
下方代码目的是用来获取当前用户的访问用户名
1、如果已登录返回用户的登录id
2、未登录为当前用户创建一个UUID存入Cookie中并返回该Cookie的UUID
/** * 准备方法获取cookie中的uuid,如果cookie中没有uuid生成uuid并保存到cookie中 */ public String getUuid(){ String uuid = CookieUtil.getCookieValue(request, "uuid","utf-8"); //从cookie中获取的uuid为null或者有具体的值 if(uuid == null || uuid.equals("")){ uuid = UUID.randomUUID().toString(); //XXXX-XXXX-XXXXXXXXX //将生成的uuid存入cookie中 CookieUtil.setCookie(request, response, "uuid", uuid,48*60*60, "utf-8"); } return uuid; } public String getUserID{ String userId = SecurityContextHolder.getContext().getAuthentication().getName(); //从springSecurity获取当前用户 //判断是否登录,如果未登录,返回UUID,如果已登录返回用户登录名 if("anonymousUser".equals(userId)){ userId = getUuid(); //cookie中获取uuid作为唯一key值 } return userId; }