Spring Security探究之路之开始

前言

Spring Security介绍中,我们分析到了根据请求获取匹配的SecurityFilterChain,这个类中包含了一组Filter

接下来我们从这些Filter开始探究之旅

Spring Security Filter简介

AuthenticationFilter中的attemptAuthentication方法调用AuthenticationManager(interface)的authenticate方法,AuthenticationManager的实际是现实ProvideManager

ProviderManager 有一个配置好的认证提供者列表(AuthenticationProvider), ProviderManager 会把收到的 UsernamePasswordAuthenticationToken 对象传递给列表中的每一个 AuthenticationProvider 进行认证.

认证过程

AuthenticationProvider接口

public interface AuthenticationProvider {
    // ~ Methods
    // ========================================================================================================

    /**
     * Performs authentication with the same contract as
     * {@link org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}
     * .
     *
     * @param authentication the authentication request object.
     *
     * @return a fully authenticated object including credentials. May return
     * <code>null</code> if the <code>AuthenticationProvider</code> is unable to support
     * authentication of the passed <code>Authentication</code> object. In such a case,
     * the next <code>AuthenticationProvider</code> that supports the presented
     * <code>Authentication</code> class will be tried.
     *
     * @throws AuthenticationException if authentication fails.
     */
    Authentication authenticate(Authentication authentication)
            throws AuthenticationException;

    /**
     * Returns <code>true</code> if this <Code>AuthenticationProvider</code> supports the
     * indicated <Code>Authentication</code> object.
     * <p>
     * Returning <code>true</code> does not guarantee an
     * <code>AuthenticationProvider</code> will be able to authenticate the presented
     * instance of the <code>Authentication</code> class. It simply indicates it can
     * support closer evaluation of it. An <code>AuthenticationProvider</code> can still
     * return <code>null</code> from the {@link #authenticate(Authentication)} method to
     * indicate another <code>AuthenticationProvider</code> should be tried.
     * </p>
     * <p>
     * Selection of an <code>AuthenticationProvider</code> capable of performing
     * authentication is conducted at runtime the <code>ProviderManager</code>.
     * </p>
     *
     * @param authentication
     *
     * @return <code>true</code> if the implementation can more closely evaluate the
     * <code>Authentication</code> class presented
     */
    // 支持的Authentication(interface)
    /**
    |-Authentication
      |--UsernamePassowrdAuthentication
      |--CasAuthentication
      |-- ...........

    **/

    boolean supports(Class<?> authentication);
}

ProviderManager的authencate方法:

// 依次调用AuthencationProvider
public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        Class<? extends Authentication> toTest = authentication.getClass();
        AuthenticationException lastException = null;
        Authentication result = null;
        boolean debug = logger.isDebugEnabled();

        // 遍历 AuthenticationProvider
        for (AuthenticationProvider provider : getProviders()) {
            // 当前的AuthenticationProvider是否支持Authentication
            if (!provider.supports(toTest)) {
                continue;
            }

            if (debug) {
                logger.debug("Authentication attempt using "
                        + provider.getClass().getName());
            }

            try {
                result = provider.authenticate(authentication);

                // 认证结果中如果不为null(验证成功),则遍历结束,拷贝认证后的结果到authentication对象
                if (result != null) {
                    copyDetails(authentication, result);
                    break;
                }
            }
            catch (AccountStatusException e) {
                prepareException(e, authentication);
                // SEC-546: Avoid polling additional providers if auth failure is due to
                // invalid account status
                throw e;
            }
            catch (InternalAuthenticationServiceException e) {
                prepareException(e, authentication);
                throw e;
            }
            catch (AuthenticationException e) {
                lastException = e;
            }
        }

        if (result == null && parent != null) {
            // Allow the parent to try.
            try {
                result = parent.authenticate(authentication);
            }
            catch (ProviderNotFoundException e) {
                // ignore as we will throw below if no other exception occurred prior to
                // calling parent and the parent
                // may throw ProviderNotFound even though a provider in the child already
                // handled the request
            }
            catch (AuthenticationException e) {
                lastException = e;
            }
        }

        if (result != null) {
            if (eraseCredentialsAfterAuthentication
                    && (result instanceof CredentialsContainer)) {
                // Authentication is complete. Remove credentials and other secret data
                // from authentication
                ((CredentialsContainer) result).eraseCredentials();
            }

            eventPublisher.publishAuthenticationSuccess(result);
            return result;
        }

        // Parent was null, or didn't authenticate (or throw an exception).

        if (lastException == null) {
            lastException = new ProviderNotFoundException(messages.getMessage(
                    "ProviderManager.providerNotFound",
                    new Object[] { toTest.getName() },
                    "No AuthenticationProvider found for {0}"));
        }

        prepareException(lastException, authentication);

        throw lastException;
    }

授权

前面有filter处理了登录问题,接下来是否可访问指定资源的问题就由FilterSecurityInterceptor来处理了。而FilterSecurityInterceptor是用了AccessDecisionManager来进行鉴权。

来看看他干了什么

/**
     * Method that is actually called by the filter chain. Simply delegates to the
     * {@link #invoke(FilterInvocation)} method.
     *
     * @param request the servlet request
     * @param response the servlet response
     * @param chain the filter chain
     *
     * @throws IOException if the filter chain fails
     * @throws ServletException if the filter chain fails
     */
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    FilterInvocation fi = new FilterInvocation(request, response, chain);
    invoke(fi);
}

public void invoke(FilterInvocation fi) throws IOException, ServletException {
    if ((fi.getRequest() != null)
        && (fi.getRequest().getAttribute(FILTER_APPLIED) != null)
        && observeOncePerRequest) {
        // filter already applied to this request and user wants us to observe
        // once-per-request handling, so don't re-do security checking
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
    }
    else {
        // first time this request being called, so perform security checking
        if (fi.getRequest() != null && observeOncePerRequest) {
            fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);
        }

        // 调用前

        // 该过程中会调用 AccessDecisionManager 来验证当前已认证成功的用户是否有权限访问该资源
        InterceptorStatusToken token = super.beforeInvocation(fi);

        try {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        }
        finally {
            super.finallyInvocation(token);
        }

        // 调用后
        super.afterInvocation(token, null);
    }
}

原文地址:https://www.cnblogs.com/watertreestar/p/11780320.html

时间: 2024-07-29 04:57:13

Spring Security探究之路之开始的相关文章

【OAuth2学习之路】Spring Security OAuth官网文档翻译

现将开发文档翻译出来,因为看英文实在是比较吃力的. 首先看下官方的指南Developers Guide,OAuth的两个版都都有.本文看的是OAuth2的开发指南. 翻译如下: Spring Security OAuth2开发指南(OAuth 2 Developers Guide) 1.入门(Introduction) 2.OAuth2.0提供程序(OAuth 2.0 Provider) 3.OAuth2.0提供程序的实现(OAuth 2.0 Provider Implementation) 4

Spring Security 之身份认证

Spring Security可以运行在不同的身份认证环境中,当我们推荐用户使用Spring Security进行身份认证但并不推荐集成到容器管理的身份认证中时,但当你集成到自己的身份认证系统时,它依然是支持的. 1. Spring Security中的身份认证是什么? 现在让我们考虑一下每个人都熟悉的标准身份认证场景: (1)用户打算使用用户名和密码登陆系统 (2)系统验证用户名和密码合法 (3)得到用户信息的上下文(角色等信息) (4)为用户建立一个安全上下文 (5)用户接下来可能执行一些权

Spring Security 实现身份认证

Spring Security可以运行在不同的身份认证环境中,当我们推荐用户使用Spring Security进行身份认证但并不推荐集成到容器管理的身份认证中时,但当你集成到自己的身份认证系统时,它依然是支持的. 1. Spring Security中的身份认证是什么? 现在让我们考虑一下每个人都熟悉的标准身份认证场景: (1)用户打算使用用户名和密码登陆系统 (2)系统验证用户名和密码合法 (3)得到用户信息的上下文(角色等信息) (4)为用户建立一个安全上下文 (5)用户接下来可能执行一些权

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

Spring Security缓存的应用之登陆后跳转到登录前源地址 什么意思? 用户访问网站,打开了一个链接:(origin url)起源链接 请求发送给服务器,服务器判断用户请求了受保护的资源. 由于用户没有登录,服务器重定向到登录页面:/login 填写表单,点击登录 浏览器将用户名密码以表单形式发送给服务器 服务器验证用户名密码.成功,进入到下一步.否则要求用户重新认证(第三步) 服务器对用户拥有的权限(角色)判定.有权限,重定向到origin url; 权限不足,返回状态码403( "禁

spring security使用和原理简析(1)

主要参考:https://blog.csdn.net/u012373815/article/details/55225079 源码参考:https://github.com/527515025/springBoot 项目需求 1:实现了用户.角色.权限的动态管理,可以管控到接口地址,已经访问方式(get,post) 2:自定义登录接口 3:结合spring-session,来保存用户登录信息 表结构说明 method来控制相同方法名的不同访问方式(get,post,put等) 项目结构 废话不多

spring security使用和原理简析(2)

转自https://pjmike.github.io/2018/10/12/%E6%B5%85%E6%9E%90Spring-Security-%E6%A0%B8%E5%BF%83%E7%BB%84%E4%BB%B6/ 上一篇我们主要讲述了如何搭项目,这里我们就来简单探究一下原理 Spring Security的核心类 Spring Security的核心类主要包括以下几个: SecurityContextHolder: 存放身份信息的容器 Authentication: 身份信息的抽象接口 A

Spring Security入门Demo

一.spring Security简介 SpringSecurity,这是一种基于Spring AOP和Servlet过滤器的安全框架.它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理身份确认和授权.在Spring Framework基础上,Spring Security充分利用了依赖注入(DI,Dependency Injection)和面向切面技术. 二.建立工程 参考http://blog.csdn.net/haishu_zheng/article/details/51490

CAS 与 Spring Security 3整合配置详解

一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分.用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统.用户授权指的是验证某个用户是否有权限执行某个操作.在一个系统中,不同用户所具有的权限是不同的.比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改.一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限. 对于上面提到的两种应用情景,Spring Security 框

spring security+mybatis+springMVC构建一个简单的项目

1.引用 spring security ,这是一种基于spring AOP和Servlet的过滤安全框架.它提供全面的安全性解决方案,同时在web请求级和方法的调用级处理身份确认和授权.在spring framework基础上,spring security充分利用了依赖注入(DI,Dependency Injection)和AOP技术. 下面就让我们用一个小的晓得项目来出初步了解Spring Security 的强大功能吧. 2.项目实战    1)项目的技术架构:maven+spring