Spring Oauth2:在SecurityContext中找不到身份validation对象
我有一个项目,我实现了Spring安全性和Spring OAuth2 Security。当我请求访问令牌时,它运行良好但是当我使用访问令牌请求资源时,我得到了“在SecurityContext中找不到身份validation对象”。
我的项目的SecurityContext是:
<!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- --> <!-- -->
我使用http:// localhost:8060 / oauth / token请求令牌?grant_type =密码&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, "scope": "read trust write" }
当我尝试使用http:// localhost:8060 / Api / currencyList在authorizatioin错误中使用访问令牌访问资源时,我得到了以下响应
{ "error": "unauthorized", "error_description": "An Authentication object was not found in the SecurityContext" }
我想使用spring oauth2保护下面的资源
@RequestMapping(value="/currencyList",method=RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public List getCurrencyList(){ List currencyList=new ArrayList(); 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天。我怎么能解决这个问题?
在成功进行身份validation时,您必须在安全上下文中添加身份validation对象
public void successfulAuthentication(HttpServletRequest request,HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException { //your some custom code // Add the authentication to the Security context SecurityContextHolder.getContext().setAuthentication(authentication); }
这里的问题是资源和授权服务器都不共享令牌的公共内存位置。当我将InMemoryTokenStore更改为JdbcTokenStore时,我的问题得到解决。
请更新你的pom文件spring boot parent release 1.4.2.RELEASE
在我的情况下,我添加了我的api urls作为公共url。 我的oauth保护的REST服务URL以/resource/api/**
开头,但我在我的安全配置类中添加了
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/css/**","/js/**","/resource/**"); }
因此, OAuth2AuthenticationProcessingFilter
没有调用,因为在我的api服务器Authentication Object was not found in the SecurityContext
中Authentication Object was not found in the SecurityContext
,我得到了exception。