ITeye博客

Spring Security3源码分析-SecurityContextHolderAwareRequestFilter分析

Dead_knight · 2012-05-07 10:34 · Spring Security · 企业架构 · Spring · Security · securitycontextholderawarerequestfilter · Markdown

SecurityContextHolderAwareRequestFilter过滤器对应的类路径为 org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter 从类名称可以猜出这个过滤器主要是包装请求对象request的,看源码 [code="java"] public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { chain.doFilter(new SecurityContextHolderAwareRequestWrapper((HttpServletRequest) req, rolePrefix), res); } [/code] SecurityContextHolderAwareRequestWrapper类对request包装的目的主要是实现servlet api的一些接口方法isUserInRole、getRemoteUser [code="java"] //从SecurityContext中获取认证实体Authentication private Authentication getAuthentication() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!authenticationTrustResolver.isAnonymous(auth)) { return auth; } return null; } //实现getRemoteUser方法。首先获取认证实体,再从认证实体中获取登录账号 @Override public String getRemoteUser() { Authentication auth = getAuthentication(); if ((auth == null) || (auth.getPrincipal() == null)) { return null; } if (auth.getPrincipal() instanceof UserDetails) { return ((UserDetails) auth.getPrincipal()).getUsername(); } return auth.getPrincipal().toString(); } //实现getUserPrincipal方法 @Override public Principal getUserPrincipal() { Authentication auth = getAuthentication(); if ((auth == null) || (auth.getPrincipal() == null)) { return null; } return auth; } //判断是否授权。这里注意一下rolePrefix,就是角色的前缀 private boolean isGranted(String role) { Authentication auth = getAuthentication(); if( rolePrefix != null ) { role = rolePrefix + role; } if ((auth == null) || (auth.getPrincipal() == null)) { return false; } Collection authorities = auth.getAuthorities(); if (authorities == null) { return false; } for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) { return true; } } return false; } //实现isUserInRole @Override public boolean isUserInRole(String role) { return isGranted(role); } [/code] 这个过滤器看起来很简单。目的仅仅是实现java ee中servlet api一些接口方法。 一些应用中直接使用getRemoteUser方法、isUserInRole方法,在使用spring security时其实就是通过这个过滤器来实现的。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。