Spring Oauth2:在SecurityContext中找不到身份验证对象 [英] Spring Oauth2 : Authentication Object was not found in the SecurityContext

查看:4146
本文介绍了Spring Oauth2:在SecurityContext中找不到身份验证对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现Spring安全性和Spring OAuth2 Security的项目。当我请求访问令牌时,它运行良好但是当我使用访问令牌请求资源时,我得到了在SecurityContext中找不到身份验证对象。 / p>

我的项目的SecurityContext是:

 <?xml version = 1.0encoding =UTF-8?> 
< beans:beans xmlns =http://www.springframework.org/schema/security
xmlns:beans =http://www.springframework.org/schema/beans
xmlns:oauth2 =http://www.springframework.org/schema/security/oauth2
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation =http://www.springframework.org/schema/security/oauth2
http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http:// www。 springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd\">

< global-method-security jsr250-annotations =enabled/>
< http pattern =/ ** / *。csssecurity =none/>
< http pattern =/ ** / *。css.mapsecurity =none/>


< http pattern =/ ** / * .gifsecurity =none/>
< http pattern =/ ** / * .htmlsecurity =none/>
< http pattern =/ ** / * .ttfsecurity =none/>
< http pattern =/ ** / * .eotsecurity =none/>
< http pattern =/ ** / * .svgsecurity =none/>
< http pattern =/ ** / * .woffsecurity =none/>
< http pattern =/ ** / * .woff2security =none/>
< http pattern =/ ** / * .xlssecurity =none/>
< http pattern =/ ** / * .icosecurity =none/>
< http pattern =/ ** / * .jpgsecurity =none/>
< http pattern =/ ** / * .jssecurity =none/>
< http pattern =/ ** / * .pngsecurity =none/>
< http pattern =/ ** / * .xmlsecurity =none/>
< http pattern =/ ** / *。mp4security =none/>
< http pattern =editCustomerTrnxsecurity =none/>
<! - < http pattern =/ embed / *security =none/> - >

<! - 由spring提供的默认URL,用于从oauth获取令牌(访问和刷新) - >
< http pattern =/ oauth / tokencreate-session =never
authentication-manager-ref =clientAuthenticationManager
xmlns =http://www.springframework。组织/架构/安全>
< intercept-url pattern =/ oauth / tokenaccess =IS_AUTHENTICATED_FULLY/>
< http-basic entry-point-ref =clientAuthenticationEntryPoint/>
<! - 使用此命令使用请求参数验证客户端 - >
< custom-filter ref =clientCredentialsTokenEndPointFilter= =BASIC_AUTH_FILTER/>
< access-denied-handler ref =oauthAccessDeniedHandler/>
< / http>

<! - 受OAuth2保护的资源被分离到他们自己的块中,因此我们可以单独处理授权和错误处理
。这不是强制性的,但它可以更容易地控制行为 - >
< http pattern =/ Api / **create-session =无状态entry-point-ref =oauthAuthenticationEntryPoint
access-decision-manager-ref =accessDecisionManager
xmlns =http://www.springframework.org/schema/security>
< anonymous enabled =false/>
< intercept-url pattern =/ Api / **access =ROLE_ADMIN/>
< custom-filter ref =resourceServerFilterbefore =PRE_AUTH_FILTER/>
< access-denied-handler ref =oauthAccessDeniedHandler/>
< / http>

<! - 2 - >
< http auto-config =true>
< intercept-url pattern =/ Admin / **
access =ROLE_ADMINISTRATOR,ROLE_AUTHENTICATEDrequires-channel =any/>
< intercept-url pattern =/ Seller / **access =ROLE_AUTHENTICATED,ROLE_SELLER
requires-channel =any/>
< intercept-url pattern =/ login / **access =IS_AUTHENTICATED_ANONYMOUSLY
requires-channel =any/>
< intercept-url pattern =/access =IS_AUTHENTICATED_ANONYMOUSLY
requires-channel =any/>
<! - < remember-me key =remittancerm/> - >
< custom-filter position =CONCURRENT_SESSION_FILTERref =customSessionFilter/>
< form-login login-page =/ main

authentication-failure-handler-ref =failureHandler
always-use-default-target =false default-target-url =/
authentication-success-handler-ref =ash/>
< logout logout-url =/ logoutlogout-success-url =//>
< access-denied-handler ref =error-page =//>
<! - authentication-failure-url =/ main?errormessage = authentication.login.failed - >
< session-management
session-authentication-strategy-ref =sls/>
< port-mappings>
< port-mapping http =8080https =8443/>
< / port-mappings>
< / http>

< authentication-manager alias =authenticationManagerxmlns =http://www.springframework.org/schema/security>
< authentication-provider> <! - user-service-ref =userDetailService - >
< user-service>
< user name =subashauthorities =ROLE_ADMINpassword =123456/>
< / user-service>
<! - < password-encoder ref =passwordEncoder>
< / password-encoder> - >
< / authentication-provider>
< / authentication-manager>

< beans:bean id =ash
class =com.remittance.session.CustomSavedRequestAwareAuthenticationSuccessHandler>
< / beans:bean>

< beans:bean id =failureHandlerclass =com.remittance.session.CustomAuthenticationFailureHandler>
< / beans:bean>
< beans:bean id =forbiddenEntryPoint
class =org.springframework.security.web.authentication.Http403ForbiddenEntryPoint/>


< beans:bean id =customSessionFilterclass =com.remittance.session.CustomSessionFilter>
< beans:constructor-arg ref =sessionRegistry/>
< / beans:bean>

< beans:bean id =sls
class =com.remittance.session.SessionLoggingStrategy>
< beans:constructor-arg ref =sas/>
< beans:constructor-arg ref =sessionLogApi/>
< / beans:bean>

< beans:bean id =sas
class =com.remittance.session.PersistingConcurrentSessionControlStrategy>
< beans:constructor-arg name =sessionRegistry
ref =sessionRegistry/>
< beans:constructor-arg name =sessionApiref =sessionApi/>
< beans:property name =maximumSessionsvalue = - 1/>
< / beans:bean>

< beans:bean id =sessionRegistry
class =com.remittance.session.PersistingSessionRegistry>
< beans:constructor-arg ref =sessionApi/>
< / beans:bean>

< beans:bean id =userDetailService
class =com.remittance.session.UserDetailsS​​erviceImpl>
< beans:constructor-arg ref =userRepository/>
< / beans:bean>

< beans:bean id =passwordEncoder
class =org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder/>


< beans:bean id =userTestclass =com.remittance.session.UserTest>
< beans:constructor-arg ref =userRepository/>
< / beans:bean>



<! - OAuth2 Security - >


<! - 受oauth2安全保护的资源 - >

<! - OAuth客户详细信息 - >
< oauth2:client-details-service id =clientDetails>
< oauth2:client client-id =android5.5secret =1234567890authorized-grant-types =password,authorization_code,refresh_token,implicit,client_credentials
authorities =ROLE_CLIENT,ROLE_TRUSTED_CLIENT scope =读,写,信任/>
< oauth2:client client-id =nokia3320secret =0987654321authorized-grant-types =password,authorization_code,refresh_token,implicit,client_credentials
authorities =ROLE_CLIENT,ROLE_TRUSTED_CLIENT范围= 读,写,信任/>
< / oauth2:client-details-service>

<! - 这个定义的令牌存储,我们现在已经在内存令牌存储中使用但是这可以改为用户定义的一个 - >
< beans:bean id =tokenStoreclass =org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore/>

<! - 按用户名加载用户 - >
< beans:bean id =clientDetailsUserDetailsS​​erviceclass =org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsS​​ervice>
< beans:constructor-arg ref =clientDetails/>
< / beans:bean>

<! - 这是我们定义基于令牌的配置,令牌有效性和其他事项的地方 - >
< beans:bean id =tokenServiceclass =org.springframework.security.oauth2.provider.token.DefaultTokenServices>
< beans:property name =tokenStoreref =tokenStore/>
< beans:property name =accessTokenValiditySecondsvalue =500/>
< beans:property name =clientDetailsS​​erviceref =clientDetails/>
< beans:property name =supportRefreshTokenvalue =true/>
< / beans:bean>

<! - 它确定给定的客户端身份验证请求是否已被用户批准 - >
<! - ToeknStoreUserApprovalHandler:用户批准处理程序,通过查询现有令牌来记住批准决策 - >
< beans:bean id =userApprovalHandlerclass =org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler>
< beans:property name =tokenStoreref =tokenStore/>
< beans:property name =requestFactoryref =oauth2RequestFactory/>
< / beans:bean>


<! - 在成功验证资源所有者并获得授权后向客户端发出访问令牌的服务器 - >
< oauth2:authorization-server client-details-service-ref =clientDetailstoken-services-ref =tokenService
user-approval-handler-ref =userApprovalHandler>
<! - < oauth2:authorization-code /> - >
<! - < oauth2:client-credentials /> - >
<! - < oauth2:implicit /> - >
< oauth2:password />
<! - < oauth2:refresh-token /> - >
< / oauth2:authorization-server>

< authentication-manager id =clientAuthenticationManager>
< authentication-provider user-service-ref =clientDetailsUserDetailsS​​ervice/>
< / authentication-manager>

<! - 如果您需要通过请求参数验证客户端,请包含此项 - >
< beans:bean id =clientCredentialsTokenEndPointFilter
class =org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter>
< beans:property name =authenticationManagerref =clientAuthenticationManager/>
< / beans:bean>

<! - 托管受保护资源的服务器,能够使用访问令牌接受和响应受保护资源请求 - >
< oauth2:resource-server id =resourceServerFilterresource-id =testtoken-services-ref =tokenService/>

<! - 身份验证入口点 - >
< beans:bean id =oauthAuthenticationEntryPointclass =org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint>
< beans:property name =realmNamevalue =test/>
< / beans:bean>

< beans:bean id =clientAuthenticationEntryPointclass =org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint>
< beans:property name =realmNamevalue =test / client/>
< beans:property name =typeNamevalue =Basic/>
< / beans:bean>

<! - 访问拒绝处理程序 - >
< beans:bean id =oauthAccessDeniedHandlerclass =org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler/>

<! - 这个bean使用传入的请求参数准备oauth2Request - >
< beans:bean id =oauth2RequestFactoryclass =org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory>
< beans:constructor-arg ref =clientDetails/>
< / beans:bean>

<! - 访问决策管理器 - >
< beans:bean id =accessDecisionManagerclass =org.springframework.security.access.vote.UnanimousBasedxmlns =http://www.springframework.org/schema/beans>
< beans:constructor-arg>
< beans:list>
< beans:bean class =org.springframework.security.oauth2.provider.vote.ScopeVoter/>
< beans:bean class =org.springframework.security.access.vote.RoleVoter/>
< beans:bean class =org.springframework.security.access.vote.AuthenticatedVoter/>
< / beans:list>
< / beans:constructor-arg>
< / beans:bean>



我使用<请求令牌a href =http:// localhost:8060 / oauth / token?grant_type = password& client_id = nokia3320& client_secret = 0987654321& username = subash& password = 123456 =nofollow noreferrer> http:// localhost:8060 / oauth / token?grant_type = password& client_id = nokia3320& client_secret = 0987654321& username = subash& password = 123456 我收到了以下回复

  {
access_token:9f5a89ce-a0d9-4d65-8e83-5d3b16d8c025,
token_type:bearer,
refresh_token:c2ac82ec -9f41-46dd-b7c2-4772c018505c,
expires_in:499,
范围:读取信任写入
}

当我尝试使用 http: // localhost:8060 / Api / currencyList 在authorizatioin错误中有访问令牌我收到了以下回复

  {
错误:unauthor ized,
error_description:在
SecurityContext中找不到身份验证对象
}

我想使用spring oauth2保护下面的资源

  @RequestMapping(value = /currencyList\",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List< CurrencyDTO> getCurrencyList(){

List< CurrencyDTO> currencyList = new ArrayList< CurrencyDTO>();

CurrencyDTO currency1 = new CurrencyDTO();
currency1.setCurrencyCode(NEP);
currency1.setCurrencyName(Rupees);
currency1.setId((long)1);
currency1.setSymbol(Rs);

CurrencyDTO currency2 = new CurrencyDTO();
currency2.setCurrencyCode(AM);
currency2.setCurrencyName(Dollar);
currency2.setId((long)2);
currency2.setSymbol($);

currencyList.add(currency1);
currencyList.add(currency2);

return currencyList;

}

我遇到了这个问题大约2天。如何我可以解决这个问题吗?

解决方案

在我的情况下,我将我的api网址添加为公共网址。我的oauth保护的REST服务URL以 / resource / api / ** 开头,但我在我的安全配置类中添加了

  @Override 
public void configure(WebSecurity web)抛出异常{
web.ignoring()。antMatchers(/ css / **, / JS / **, /资源/ **);
}

所以, OAuth2AuthenticationProcessingFilter 没有调用,我得到了例外,因为在我的api服务器的SecurityContext 中找不到认证对象。


I have a project where i implement Spring security and Spring OAuth2 Security.When i request for access token it works well but when i request for resource using access token i got 'An authentication object was not found in the SecurityContext'.

SecurityContext of my project is :

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" 
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2
       http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

<global-method-security jsr250-annotations="enabled" />
<http pattern="/**/*.css" security="none" />
<http pattern="/**/*.css.map" security="none" />


<http pattern="/**/*.gif" security="none" />
<http pattern="/**/*.html" security="none" />
<http pattern="/**/*.ttf" security="none" />
<http pattern="/**/*.eot" security="none" />
<http pattern="/**/*.svg" security="none" />
<http pattern="/**/*.woff" security="none" />
<http pattern="/**/*.woff2" security="none" />
<http pattern="/**/*.xls" security="none" />
<http pattern="/**/*.ico" security="none" />
<http pattern="/**/*.jpg" security="none" />
<http pattern="/**/*.js" security="none" />
<http pattern="/**/*.png" security="none" />
<http pattern="/**/*.xml" security="none" />
<http pattern="/**/*.mp4" security="none" />
<http pattern="editCustomerTrnx" security="none"/>
<!--<http pattern="/embed/*" security="none"/> -->

<!-- Default URL provided by spring to get the token(access and refresh) from oauth -->
<http pattern="/oauth/token" create-session="never"
      authentication-manager-ref="clientAuthenticationManager"
      xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/>
    <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
    <!-- Using this to authenticate client using request parameter -->
    <custom-filter ref="clientCredentialsTokenEndPointFilter" after="BASIC_AUTH_FILTER"/>
    <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<!-- The OAuth2 protected resources are separated out into their own block so we can deal with authorization and error handling
      separately. This isn't mandatory, but it makes it easier to control the behaviour -->
<http pattern="/Api/**" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
      access-decision-manager-ref="accessDecisionManager"
      xmlns="http://www.springframework.org/schema/security">
   <anonymous enabled="false"/>
   <intercept-url pattern="/Api/**" access="ROLE_ADMIN"/>
   <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
   <access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>

<!-- 2 -->
<http auto-config="true">
    <intercept-url pattern="/Admin/**"
        access="ROLE_ADMINISTRATOR,ROLE_AUTHENTICATED" requires-channel="any" />
    <intercept-url pattern="/Seller/**" access="ROLE_AUTHENTICATED,ROLE_SELLER"
        requires-channel="any" />
    <intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />
    <intercept-url  pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"
        requires-channel="any" />
    <!-- <remember-me key="remittancerm" /> -->
    <custom-filter position="CONCURRENT_SESSION_FILTER" ref="customSessionFilter" />
    <form-login login-page="/main"

        authentication-failure-handler-ref="failureHandler"
        always-use-default-target="false" default-target-url="/"
        authentication-success-handler-ref="ash" />
    <logout logout-url="/logout" logout-success-url="/" />
    <access-denied-handler ref="" error-page="/" />
    <!-- authentication-failure-url="/main?errormessage=authentication.login.failed" -->
    <session-management
        session-authentication-strategy-ref="sls" />
    <port-mappings>
        <port-mapping http="8080" https="8443" />
    </port-mappings>
</http>

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
    <authentication-provider> <!-- user-service-ref="userDetailService" -->
        <user-service>
           <user name="subash" authorities="ROLE_ADMIN" password="123456"/>
        </user-service>
        <!-- <password-encoder ref="passwordEncoder">
        </password-encoder> -->
    </authentication-provider>
</authentication-manager>

<beans:bean id="ash"
    class="com.remittance.session.CustomSavedRequestAwareAuthenticationSuccessHandler">
</beans:bean>

<beans:bean id="failureHandler" class="com.remittance.session.CustomAuthenticationFailureHandler">
</beans:bean>
<beans:bean id="forbiddenEntryPoint"
    class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />


<beans:bean id="customSessionFilter" class="com.remittance.session.CustomSessionFilter">
    <beans:constructor-arg ref="sessionRegistry" />
</beans:bean>

<beans:bean id="sls"
    class="com.remittance.session.SessionLoggingStrategy">
    <beans:constructor-arg ref="sas" />
    <beans:constructor-arg ref="sessionLogApi" />
</beans:bean>

<beans:bean id="sas"
    class="com.remittance.session.PersistingConcurrentSessionControlStrategy">
    <beans:constructor-arg name="sessionRegistry"
        ref="sessionRegistry" />
    <beans:constructor-arg name="sessionApi" ref="sessionApi" />
    <beans:property name="maximumSessions" value="-1" />
</beans:bean>

<beans:bean id="sessionRegistry"
    class="com.remittance.session.PersistingSessionRegistry">
    <beans:constructor-arg ref="sessionApi" />
</beans:bean>

<beans:bean id="userDetailService"
    class="com.remittance.session.UserDetailsServiceImpl">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>

<beans:bean id="passwordEncoder"
    class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />


<beans:bean id="userTest" class="com.remittance.session.UserTest">
    <beans:constructor-arg ref="userRepository" />
</beans:bean>



<!-- OAuth2 Security  -->


<!-- Resource protected by oauth2 security -->

<!-- OAuth Client Details -->
<oauth2:client-details-service id="clientDetails">
   <oauth2:client client-id="android5.5" secret="1234567890" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
   <oauth2:client client-id="nokia3320" secret="0987654321" authorized-grant-types="password,authorization_code,refresh_token,implicit,client_credentials"
                 authorities="ROLE_CLIENT,ROLE_TRUSTED_CLIENT" scope="read,write,trust"/>
</oauth2:client-details-service>

 <!-- This defined token store, we have used in memory token store for now but this can be changed to a user defined one -->
 <beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"/>

 <!-- Load User By User name -->
 <beans:bean id="clientDetailsUserDetailsService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <beans:constructor-arg ref="clientDetails"/>
 </beans:bean>

 <!-- This is where we defined token based configurations, token validity and other things -->
 <beans:bean id="tokenService" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
   <beans:property name="tokenStore" ref="tokenStore"/>
   <beans:property name="accessTokenValiditySeconds" value="500"/>
   <beans:property name="clientDetailsService" ref="clientDetails"/>
   <beans:property name="supportRefreshToken" value="true"/>
 </beans:bean>

 <!-- It Determine whether a given client authentication request has been approved by user or not -->
 <!-- ToeknStoreUserApprovalHandler : A user approval handler that remembers approval decisions by consulting existing tokens -->
 <beans:bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
    <beans:property name="tokenStore" ref="tokenStore"/>
    <beans:property name="requestFactory" ref="oauth2RequestFactory"/>
 </beans:bean>


 <!-- Server issuing access token to the client after successfully authenticating the resource owner and obtaining authorization -->
 <oauth2:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenService"
                             user-approval-handler-ref="userApprovalHandler">
     <!-- <oauth2:authorization-code/> -->
     <!-- <oauth2:client-credentials/> -->
     <!-- <oauth2:implicit/> -->
     <oauth2:password/>
     <!-- <oauth2:refresh-token/> -->
 </oauth2:authorization-server>

 <authentication-manager id="clientAuthenticationManager">
     <authentication-provider user-service-ref="clientDetailsUserDetailsService"/>
 </authentication-manager>

 <!-- Include this if you need to authenticate client via request parameter -->
 <beans:bean id="clientCredentialsTokenEndPointFilter"
    class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <beans:property name="authenticationManager" ref="clientAuthenticationManager" />
</beans:bean>

 <!-- Server hosting the protected resource ,capable of accepting and responding to protected resource request using access tokens -->
 <oauth2:resource-server id="resourceServerFilter" resource-id="test" token-services-ref="tokenService"/>

 <!-- Authentication Entry Point -->
 <beans:bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
   <beans:property name="realmName" value="test" />
 </beans:bean>

 <beans:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <beans:property name="realmName" value="test/client" />
    <beans:property name="typeName" value="Basic" />
 </beans:bean>

<!-- Access Denied Handler -->
<beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

<!-- This beans prepares oauth2Request using incoming request parameter -->
<beans:bean id="oauth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
  <beans:constructor-arg ref="clientDetails"/>
</beans:bean>

<!-- Access Decision Manager -->
<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans">
  <beans:constructor-arg>
    <beans:list>
        <beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
        <beans:bean class="org.springframework.security.access.vote.RoleVoter" />
        <beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
    </beans:list>
</beans:constructor-arg>
</beans:bean>

I request for token using http://localhost:8060/oauth/token?grant_type=password&client_id=nokia3320&client_secret=0987654321&username=subash&password=123456 and i got following response

{
 "access_token": "9f5a89ce-a0d9-4d65-8e83-5d3b16d8c025",
 "token_type": "bearer",
 "refresh_token": "c2ac82ec-9f41-46dd-b7c2-4772c018505c",
 "expires_in": 499,
 "scope": "read trust write"
}

When i try to access resource using http://localhost:8060/Api/currencyList with access token in authorizatioin error i got following response

{
 "error": "unauthorized",
 "error_description": "An Authentication object was not found in the 
                      SecurityContext"
}

I want to protect the resource below using spring oauth2

@RequestMapping(value="/currencyList",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<CurrencyDTO> getCurrencyList(){

    List<CurrencyDTO> currencyList=new ArrayList<CurrencyDTO>();

    CurrencyDTO currency1 = new CurrencyDTO();
    currency1.setCurrencyCode("NEP");
    currency1.setCurrencyName("Rupees");
    currency1.setId((long)1);
    currency1.setSymbol("Rs");

    CurrencyDTO currency2 = new CurrencyDTO();
    currency2.setCurrencyCode("AM");
    currency2.setCurrencyName("Dollar");
    currency2.setId((long)2);
    currency2.setSymbol("$");

    currencyList.add(currency1);
    currencyList.add(currency2);

    return currencyList;

}

I got stuck in this problem for about 2 days.How could i resolve this problem?

解决方案

In my case, I added my api urls as public urls. My oauth protected REST-Service urls start with /resource/api/**, but I added in my security configuration class as

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**","/js/**","/resource/**");
}

So, OAuth2AuthenticationProcessingFilter did not invoke and I got exception as Authentication Object was not found in the SecurityContext at my api server.

这篇关于Spring Oauth2:在SecurityContext中找不到身份验证对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆