欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Security3源码分析-SecurityContextHolderAwareRequestFilter分析

程序员文章站 2022-03-02 11:01:48
...
SecurityContextHolderAwareRequestFilter过滤器对应的类路径为
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter

从类名称可以猜出这个过滤器主要是包装请求对象request的,看源码
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(new SecurityContextHolderAwareRequestWrapper((HttpServletRequest) req, rolePrefix), res);
    }


SecurityContextHolderAwareRequestWrapper类对request包装的目的主要是实现servlet api的一些接口方法isUserInRole、getRemoteUser
    //从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<GrantedAuthority> 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);
    }


这个过滤器看起来很简单。目的仅仅是实现java ee中servlet api一些接口方法。
一些应用中直接使用getRemoteUser方法、isUserInRole方法,在使用spring security时其实就是通过这个过滤器来实现的。