title: Spring Oauth2 : Authentication Object was not found in the SecurityContext
body: <p>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'.</p>
  
  <p>SecurityContext of my project is : </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;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"&gt;
  
  &lt;global-method-security jsr250-annotations="enabled" /&gt;
  &lt;http pattern="/**/*.css" security="none" /&gt;
  &lt;http pattern="/**/*.css.map" security="none" /&gt;
  
  
  &lt;http pattern="/**/*.gif" security="none" /&gt;
  &lt;http pattern="/**/*.html" security="none" /&gt;
  &lt;http pattern="/**/*.ttf" security="none" /&gt;
  &lt;http pattern="/**/*.eot" security="none" /&gt;
  &lt;http pattern="/**/*.svg" security="none" /&gt;
  &lt;http pattern="/**/*.woff" security="none" /&gt;
  &lt;http pattern="/**/*.woff2" security="none" /&gt;
  &lt;http pattern="/**/*.xls" security="none" /&gt;
  &lt;http pattern="/**/*.ico" security="none" /&gt;
  &lt;http pattern="/**/*.jpg" security="none" /&gt;
  &lt;http pattern="/**/*.js" security="none" /&gt;
  &lt;http pattern="/**/*.png" security="none" /&gt;
  &lt;http pattern="/**/*.xml" security="none" /&gt;
  &lt;http pattern="/**/*.mp4" security="none" /&gt;
  &lt;http pattern="editCustomerTrnx" security="none"/&gt;
  &lt;!--&lt;http pattern="/embed/*" security="none"/&gt; --&gt;
  
  &lt;!-- Default URL provided by spring to get the token(access and refresh) from oauth --&gt;
  &lt;http pattern="/oauth/token" create-session="never"
        authentication-manager-ref="clientAuthenticationManager"
        xmlns="http://www.springframework.org/schema/security"&gt;
      &lt;intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY"/&gt;
      &lt;http-basic entry-point-ref="clientAuthenticationEntryPoint"/&gt;
      &lt;!-- Using this to authenticate client using request parameter --&gt;
      &lt;custom-filter ref="clientCredentialsTokenEndPointFilter" after="BASIC_AUTH_FILTER"/&gt;
      &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;
  &lt;/http&gt;
  
  &lt;!-- 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 --&gt;
  &lt;http pattern="/Api/**" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
        access-decision-manager-ref="accessDecisionManager"
        xmlns="http://www.springframework.org/schema/security"&gt;
     &lt;anonymous enabled="false"/&gt;
     &lt;intercept-url pattern="/Api/**" access="ROLE_ADMIN"/&gt;
     &lt;custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /&gt;
     &lt;access-denied-handler ref="oauthAccessDeniedHandler"/&gt;
  &lt;/http&gt;
  
  &lt;!-- 2 --&gt;
  &lt;http auto-config="true"&gt;
      &lt;intercept-url pattern="/Admin/**"
          access="ROLE_ADMINISTRATOR,ROLE_AUTHENTICATED" requires-channel="any" /&gt;
      &lt;intercept-url pattern="/Seller/**" access="ROLE_AUTHENTICATED,ROLE_SELLER"
          requires-channel="any" /&gt;
      &lt;intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"
          requires-channel="any" /&gt;
      &lt;intercept-url  pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"
          requires-channel="any" /&gt;
      &lt;!-- &lt;remember-me key="remittancerm" /&gt; --&gt;
      &lt;custom-filter position="CONCURRENT_SESSION_FILTER" ref="customSessionFilter" /&gt;
      &lt;form-login login-page="/main"
  
          authentication-failure-handler-ref="failureHandler"
          always-use-default-target="false" default-target-url="/"
          authentication-success-handler-ref="ash" /&gt;
      &lt;logout logout-url="/logout" logout-success-url="/" /&gt;
      &lt;access-denied-handler ref="" error-page="/" /&gt;
      &lt;!-- authentication-failure-url="/main?errormessage=authentication.login.failed" --&gt;
      &lt;session-management
          session-authentication-strategy-ref="sls" /&gt;
      &lt;port-mappings&gt;
          &lt;port-mapping http="8080" https="8443" /&gt;
      &lt;/port-mappings&gt;
  &lt;/http&gt;
  
  &lt;authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security"&gt;
      &lt;authentication-provider&gt; &lt;!-- user-service-ref="userDetailService" --&gt;
          &lt;user-service&gt;
             &lt;user name="subash" authorities="ROLE_ADMIN" password="123456"/&gt;
          &lt;/user-service&gt;
          &lt;!-- &lt;password-encoder ref="passwordEncoder"&gt;
          &lt;/password-encoder&gt; --&gt;
      &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
  
  &lt;beans:bean id="ash"
      class="com.remittance.session.CustomSavedRequestAwareAuthenticationSuccessHandler"&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="failureHandler" class="com.remittance.session.CustomAuthenticationFailureHandler"&gt;
  &lt;/beans:bean&gt;
  &lt;beans:bean id="forbiddenEntryPoint"
      class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" /&gt;
  
  
  &lt;beans:bean id="customSessionFilter" class="com.remittance.session.CustomSessionFilter"&gt;
      &lt;beans:constructor-arg ref="sessionRegistry" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="sls"
      class="com.remittance.session.SessionLoggingStrategy"&gt;
      &lt;beans:constructor-arg ref="sas" /&gt;
      &lt;beans:constructor-arg ref="sessionLogApi" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="sas"
      class="com.remittance.session.PersistingConcurrentSessionControlStrategy"&gt;
      &lt;beans:constructor-arg name="sessionRegistry"
          ref="sessionRegistry" /&gt;
      &lt;beans:constructor-arg name="sessionApi" ref="sessionApi" /&gt;
      &lt;beans:property name="maximumSessions" value="-1" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="sessionRegistry"
      class="com.remittance.session.PersistingSessionRegistry"&gt;
      &lt;beans:constructor-arg ref="sessionApi" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="userDetailService"
      class="com.remittance.session.UserDetailsServiceImpl"&gt;
      &lt;beans:constructor-arg ref="userRepository" /&gt;
  &lt;/beans:bean&gt;
  
  &lt;beans:bean id="passwordEncoder"
      class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" /&gt;
  
  
  &lt;beans:bean id="userTest" class="com.remittance.session.UserTest"&gt;
      &lt;beans:constructor-arg ref="userRepository" /&gt;
  &lt;/beans:bean&gt;
  
  
  
  &lt;!-- OAuth2 Security  --&gt;
  
  
  &lt;!-- Resource protected by oauth2 security --&gt;
  
  &lt;!-- OAuth Client Details --&gt;
  &lt;oauth2:client-details-service id="clientDetails"&gt;
     &lt;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"/&gt;
     &lt;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"/&gt;
  &lt;/oauth2:client-details-service&gt;
  
   &lt;!-- This defined token store, we have used in memory token store for now but this can be changed to a user defined one --&gt;
   &lt;beans:bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore"/&gt;
  
   &lt;!-- Load User By User name --&gt;
   &lt;beans:bean id="clientDetailsUserDetailsService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService"&gt;
      &lt;beans:constructor-arg ref="clientDetails"/&gt;
   &lt;/beans:bean&gt;
  
   &lt;!-- This is where we defined token based configurations, token validity and other things --&gt;
   &lt;beans:bean id="tokenService" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"&gt;
     &lt;beans:property name="tokenStore" ref="tokenStore"/&gt;
     &lt;beans:property name="accessTokenValiditySeconds" value="500"/&gt;
     &lt;beans:property name="clientDetailsService" ref="clientDetails"/&gt;
     &lt;beans:property name="supportRefreshToken" value="true"/&gt;
   &lt;/beans:bean&gt;
  
   &lt;!-- It Determine whether a given client authentication request has been approved by user or not --&gt;
   &lt;!-- ToeknStoreUserApprovalHandler : A user approval handler that remembers approval decisions by consulting existing tokens --&gt;
   &lt;beans:bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler"&gt;
      &lt;beans:property name="tokenStore" ref="tokenStore"/&gt;
      &lt;beans:property name="requestFactory" ref="oauth2RequestFactory"/&gt;
   &lt;/beans:bean&gt;
  
  
   &lt;!-- Server issuing access token to the client after successfully authenticating the resource owner and obtaining authorization --&gt;
   &lt;oauth2:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenService"
                               user-approval-handler-ref="userApprovalHandler"&gt;
       &lt;!-- &lt;oauth2:authorization-code/&gt; --&gt;
       &lt;!-- &lt;oauth2:client-credentials/&gt; --&gt;
       &lt;!-- &lt;oauth2:implicit/&gt; --&gt;
       &lt;oauth2:password/&gt;
       &lt;!-- &lt;oauth2:refresh-token/&gt; --&gt;
   &lt;/oauth2:authorization-server&gt;
  
   &lt;authentication-manager id="clientAuthenticationManager"&gt;
       &lt;authentication-provider user-service-ref="clientDetailsUserDetailsService"/&gt;
   &lt;/authentication-manager&gt;
  
   &lt;!-- Include this if you need to authenticate client via request parameter --&gt;
   &lt;beans:bean id="clientCredentialsTokenEndPointFilter"
      class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"&gt;
      &lt;beans:property name="authenticationManager" ref="clientAuthenticationManager" /&gt;
  &lt;/beans:bean&gt;
  
   &lt;!-- Server hosting the protected resource ,capable of accepting and responding to protected resource request using access tokens --&gt;
   &lt;oauth2:resource-server id="resourceServerFilter" resource-id="test" token-services-ref="tokenService"/&gt;
  
   &lt;!-- Authentication Entry Point --&gt;
   &lt;beans:bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
     &lt;beans:property name="realmName" value="test" /&gt;
   &lt;/beans:bean&gt;
  
   &lt;beans:bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"&gt;
      &lt;beans:property name="realmName" value="test/client" /&gt;
      &lt;beans:property name="typeName" value="Basic" /&gt;
   &lt;/beans:bean&gt;
  
  &lt;!-- Access Denied Handler --&gt;
  &lt;beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/&gt;
  
  &lt;!-- This beans prepares oauth2Request using incoming request parameter --&gt;
  &lt;beans:bean id="oauth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory"&gt;
    &lt;beans:constructor-arg ref="clientDetails"/&gt;
  &lt;/beans:bean&gt;
  
  &lt;!-- Access Decision Manager --&gt;
  &lt;beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"&gt;
    &lt;beans:constructor-arg&gt;
      &lt;beans:list&gt;
          &lt;beans:bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /&gt;
          &lt;beans:bean class="org.springframework.security.access.vote.RoleVoter" /&gt;
          &lt;beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter" /&gt;
      &lt;/beans:list&gt;
  &lt;/beans:constructor-arg&gt;
  &lt;/beans:bean&gt;
  </code></pre>
  
  <p></p>
  
  <p>I request for token using <a href="http://localhost:8060/oauth/token?grant_type=password&amp;client_id=nokia3320&amp;client_secret=0987654321&amp;username=subash&amp;password=123456" rel="nofollow noreferrer">http://localhost:8060/oauth/token?grant_type=password&amp;client_id=nokia3320&amp;client_secret=0987654321&amp;username=subash&amp;password=123456</a> and i got following response</p>
  
  <pre><code>{
   "access_token": "9f5a89ce-a0d9-4d65-8e83-5d3b16d8c025",
   "token_type": "bearer",
   "refresh_token": "c2ac82ec-9f41-46dd-b7c2-4772c018505c",
   "expires_in": 499,
   "scope": "read trust write"
  }
  </code></pre>
  
  <p>When i try to access resource using <a href="http://localhost:8060/Api/currencyList" rel="nofollow noreferrer">http://localhost:8060/Api/currencyList</a> with access token in authorizatioin error i got following response</p>
  
  <pre><code>{
   "error": "unauthorized",
   "error_description": "An Authentication object was not found in the 
                        SecurityContext"
  }
  </code></pre>
  
  <p>I want to protect the resource below using spring oauth2</p>
  
  <pre><code>@RequestMapping(value="/currencyList",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE})
  @ResponseBody
  public List&lt;CurrencyDTO&gt; getCurrencyList(){
  
      List&lt;CurrencyDTO&gt; currencyList=new ArrayList&lt;CurrencyDTO&gt;();
  
      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;
  
  }
  </code></pre>
  
  <p>I got stuck in this problem for about 2 days.How could i resolve this problem?</p>