如何继承 OAuth2AuthenticationProcessingFilter 或添加自定义过滤器

How to inherit OAuth2AuthenticationProcessingFilter or add custom filter

我在基于休息的 API 中使用 OAuth2 令牌。我想重写 OAuth2AuthenticationProcessingFilter,这样如果 header 属性中没有提供者,我可以提取令牌作为授权(这可以作为 header 中的 accessToken 属性提供,长话短说,不要问为什么)。 或者 如果没有那么谁能告诉我如何在 OAuth2AuthenticationProcessingFilter 之后添加另一个过滤器?

基本上,在 XML 中,要使用默认值,您需要添加 resource-server

<oauth:resource-server id="resourceServerFilter"
        token-services-ref="tokenServices"
        resource-id="myId" />

添加了 OAuth2AuthenticationManagerOAuth2AuthenticationProcessingFilter(详见 https://github.com/spring-projects/spring-security-oauth/blob/ec215f79f4f73f8bb5d4b8a3ff9abe15b3335866/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/config/xml/ResourceServerBeanDefinitionParser.java

然后将该过滤器添加到 <sec:http> 元素中:

<sec:custom-filter ref="resourceServerFilter" position="PRE_AUTH_FILTER" />

但是如果您需要使用 OAuth2AuthenticationProcessingFilter 专业化而不是 OAuth2AuthenticationProcessingFilter 本身,您可以执行以下操作:

我。手动添加OAuth2AuthenticationManager

<bean id="authenticationManager" class="org.springframework.security.oauth2.config.xml.OAuth2AuthenticationManager">
    <property name="tokenServices" ref="tokenServices"/>
    <property name="resourceId" value="myId"/>
</bean>

二.手动添加过滤器更换:

<bean id="resourceServerFilter"class="YourFilterImplementationClass">
    <property name="authenticationManager" ref="authenticationManager"/>
</bean>

三。像往常一样将过滤器插入过滤器链:

<sec:custom-filter ref="resourceServerFilter" position="PRE_AUTH_FILTER" />

更好的方法可能是扩展 org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor 并为其创建 bean 并在

中引用它
<oauth:resource-server id="resourceServerFilter"
        token-services-ref="tokenServices" token-extractor-ref="idofyourtokenextractionbeanhere" 
        resource-id="myId" />