草庐IT

未找到 404 页面未返回 java + spring security oauth token

coder 2024-03-21 原文

各位,我知道已经有针对类似问题的解决方案,但这个问题是不同的。

我还阅读了 link存在,但该解决方案不适用于我。

我的问题是,我正在尝试使用 oauth2.0 来保护我的 Java+Spring+Jersey web 服务应用程序,并且一直在使用 spring-security-oauth2 库版本。

每当我调用 /oauth/token 时,应用程序都会验证 header 下提供的详细信息(client_secret、client_id 和 grant_type),客户端已成功通过身份验证但 token 数据并未从服务器返回,而是显示 404 页面未找到响应。

配置如下:

  1. web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        version="2.5">
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring/dispatcher-servlet.xml</param-value>
        </context-param>
    
        <servlet>
            <servlet-name>jersey-servlet</servlet-name>
            <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.tprivity.babycenter.ws</param-value>
            </init-param>
            <init-param>
                <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
                <param-value>true</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>jersey-servlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    
        <filter>
            <filter-name>springSecurityFilterChain</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    
  2. dispatcher-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
        xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
            http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
            http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    
        <security:http pattern="/oauth/token" create-session="stateless"
            authentication-manager-ref="authenticationManager">
            <security:intercept-url pattern="/oauth/token"
                access="IS_AUTHENTICATED_FULLY" />
            <security:anonymous enabled="false" />
            <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" />
            <security:custom-filter ref="clientCredentialsTokenEndpointFilter"
                before="BASIC_AUTH_FILTER" />
            <security:access-denied-handler ref="oauthAccessDeniedHandler" />
        </security:http>
    
        <security:http pattern="/ws/**" create-session="never"
            authentication-manager-ref="authenticationManager" entry-point-ref="oauthAuthenticationEntryPoint">
            <security:anonymous enabled="false" />
            <security:intercept-url pattern="/ws/**"
                method="GET" access="IS_AUTHENTICATED_FULLY" />
            <security:intercept-url pattern="/ws/**"
                method="POST" access="IS_AUTHENTICATED_FULLY" />
            <security:custom-filter ref="resourceServerFilter"
                before="PRE_AUTH_FILTER" />
            <security:access-denied-handler ref="oauthAccessDeniedHandler" />
        </security:http>
    
        <bean id="oauthAuthenticationEntryPoint"
            class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        </bean>
    
        <bean id="clientAuthenticationEntryPoint"
            class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
            <property name="realmName" value="springsec/client" />
            <property name="typeName" value="Basic" />
        </bean>
    
        <bean id="oauthAccessDeniedHandler"
            class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
    
    
        <bean id="clientCredentialsTokenEndpointFilter"
            class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
            <property name="authenticationManager" ref="authenticationManager" />
        </bean>
    
        <security:authentication-manager alias="authenticationManager">
            <security:authentication-provider
                user-service-ref="clientDetailsUserService" />
        </security:authentication-manager>
    
        <bean id="clientDetailsUserService"
            class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
            <constructor-arg ref="clientDetails" />
        </bean>
    
        <bean id="clientDetails"
            class="org.springframework.security.oauth2.provider.client.JdbcClientDetailsService">
            <constructor-arg index="0">
                <ref bean="dataSource" />
            </constructor-arg>
        </bean>
    
        <security:authentication-manager id="userAuthenticationManager">
            <security:authentication-provider
                ref="customUserAuthenticationProvider" />
        </security:authentication-manager>
    
        <bean id="customUserAuthenticationProvider"
            class="com.tprivity.babycenter.ws.security.CustomUserAuthenticationProvider">
        </bean>
    
        <!-- Authorization Server Configuration of the server is used to provide 
            implementations of the client details service and token services and to enable 
            or disable certain aspects of the mechanism globally. -->
        <oauth2:authorization-server
            client-details-service-ref="clientDetails" token-services-ref="tokenServices"
            user-approval-handler-ref="userApprovalHandler">
            <oauth2:authorization-code />
            <oauth2:implicit />
            <oauth2:refresh-token />
            <oauth2:client-credentials />
            <oauth2:password authentication-manager-ref="userAuthenticationManager" />
        </oauth2:authorization-server>
    
        <oauth2:resource-server id="resourceServerFilter"
            resource-id="springsec" token-services-ref="tokenServices" />
    
        <bean id="tokenStore"
            class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
            <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
        </bean>
    
        <!-- Configure Authentication manager -->
        <bean id="passwordEncoder"
            class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
            <constructor-arg name="strength" value="11" />
        </bean>
    
        <!-- Grants access if only grant (or abstain) votes were received. We can 
            protect REST resource methods with JSR-250 annotations such as @RolesAllowed -->
        <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
            <property name="decisionVoters">
                <list>
                    <bean class="org.springframework.security.access.annotation.Jsr250Voter" />
                </list>
            </property>
        </bean>
    
        <bean id="tokenServices"
            class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
            <property name="tokenStore" ref="tokenStore" />
            <property name="supportRefreshToken" value="true" />
            <property name="accessTokenValiditySeconds" value="120"></property>
            <property name="clientDetailsService" ref="clientDetails" />
        </bean>
    
        <!-- A user approval handler that remembers approval decisions by consulting 
            existing tokens -->
        <bean id="oAuth2RequestFactory"
            class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
            <constructor-arg ref="clientDetails" />
        </bean>
    
        <bean id="userApprovalHandler"
            class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
            <property name="requestFactory" ref="oAuth2RequestFactory" />
            <property name="tokenStore" ref="tokenStore" />
        </bean>
    </beans>
    

下面是相同的日志。

DEBUG [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - <Checking match of request : '/oauth/token'; against '/oauth/token'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 1 of 7 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 2 of 7 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 3 of 7 in additional filter chain; firing Filter: 'ClientCredentialsTokenEndpointFilter'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 4 of 7 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'>
DEBUG [org.springframework.security.web.authentication.www.BasicAuthenticationFilter] - <Basic Authentication Authorization header found for user 'bccws'>
DEBUG [org.springframework.security.authentication.ProviderManager] - <Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider>
WARN [org.springframework.context.support.ResourceBundleMessageSource] - <ResourceBundle [messages] not found for MessageSource: Can't find bundle for base name messages, locale en_US>
WARN [org.springframework.context.support.ResourceBundleMessageSource] - <ResourceBundle [labels] not found for MessageSource: Can't find bundle for base name labels, locale en_US>
WARN [org.springframework.context.support.ResourceBundleMessageSource] - <ResourceBundle [errors] not found for MessageSource: Can't find bundle for base name errors, locale en_US>
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - <Executing prepared SQL query>
DEBUG [org.springframework.jdbc.core.JdbcTemplate] - <Executing prepared SQL statement [select client_id, client_secret, resource_ids, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove from oauth_client_details where client_id = ?]>
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - <Fetching JDBC Connection from DataSource>
DEBUG [org.springframework.jdbc.datasource.DataSourceUtils] - <Returning JDBC Connection to DataSource>
DEBUG [org.springframework.security.web.authentication.www.BasicAuthenticationFilter] - <Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@f9d8c511: Principal: org.springframework.security.core.userdetails.User@593829e: Username: bccws; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ADMIN>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 5 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'>
DEBUG [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - <Checking match of request : '/oauth/token'; against '/oauth/token'>
DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - <Secure object: FilterInvocation: URL: /oauth/token; Attributes: [IS_AUTHENTICATED_FULLY]>
DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - <Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@f9d8c511: Principal: org.springframework.security.core.userdetails.User@593829e: Username: bccws; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ADMIN>
DEBUG [org.springframework.security.access.vote.AffirmativeBased] - <Voter: org.springframework.security.access.vote.RoleVoter@6dbd30e2, returned: 0>
DEBUG [org.springframework.security.access.vote.AffirmativeBased] - <Voter: org.springframework.security.access.vote.AuthenticatedVoter@19d7bbb3, returned: 1>
DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - <Authorization successful>
DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - <RunAsManager did not change Authentication object>
DEBUG [org.springframework.security.web.FilterChainProxy] - </oauth/token reached end of additional filter chain; proceeding with original chain>
DEBUG [org.springframework.security.web.access.ExceptionTranslationFilter] - <Chain processed normally>
DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - <SecurityContextHolder now cleared, as request processing completed>

我一直在研究问题,但没有找到任何解决方案。任何帮助将不胜感激。

最佳答案

当您的安全过滤器在其上下文中没有 oauth/token 端点时,就会发生这种情况。尝试在注册 springSecurityFilterChain

时在 web.xml 中添加上下文属性
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
    <param-name>contextAttribute</param-name>
    <param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher</param-value>
</init-param>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>

关于未找到 404 页面未返回 java + spring security oauth token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33431610/

有关未找到 404 页面未返回 java + spring security oauth token的更多相关文章

  1. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  5. ruby - Ruby 中的隐式返回值是怎么回事? - 2

    所以我开始关注ruby​​,很多东西看起来不错,但我对隐式return语句很反感。我理解默认情况下让所有内容返回self或nil但不是语句的最后一个值。对我来说,它看起来非常脆弱(尤其是)如果你正在使用一个不打算返回某些东西的方法(尤其是一个改变状态/破坏性方法的函数!),其他人可能最终依赖于一个返回对方法的目的并不重要,并且有很大的改变机会。隐式返回有什么意义?有没有办法让事情变得更简单?总是有返回以防止隐含返回被认为是好的做法吗?我是不是太担心这个了?附言当人们想要从方法中返回特定的东西时,他们是否经常使用隐式返回,这不是让你组中的其他人更容易破坏彼此的代码吗?当然,记录一切并给出

  6. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. ruby-on-rails - ruby 日期方程不返回预期的真值 - 2

    为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998

  9. ruby-on-rails - capybara ::ElementNotFound:无法找到 xpath "/html" - 2

    我正在学习http://ruby.railstutorial.org/chapters/static-pages上的RubyonRails教程并遇到以下错误StaticPagesHomepageshouldhavethecontent'SampleApp'Failure/Error:page.shouldhave_content('SampleApp')Capybara::ElementNotFound:Unabletofindxpath"/html"#(eval):2:in`text'#./spec/requests/static_pages_spec.rb:7:in`(root)'

  10. ruby - 从 String#split 返回的零长度字符串 - 2

    在Ruby1.9.3(可能还有更早的版本,不确定)中,我试图弄清楚为什么Ruby的String#split方法会给我某些结果。我得到的结果似乎与我的预期相反。这是一个例子:"abcabc".split("b")#=>["a","ca","c"]"abcabc".split("a")#=>["","bc","bc"]"abcabc".split("c")#=>["ab","ab"]在这里,第一个示例返回的正是我所期望的。但在第二个示例中,我很困惑为什么#split返回零长度字符串作为返回数组的第一个值。这是什么原因呢?这是我所期望的:"abcabc".split("a")#=>["bc"

随机推荐