如何使用simpleJava代码从Spring Oath2中的客户端获取accessToken?

时间:2016-05-11 13:54:26

标签: java spring spring-security spring-oauth2

我是Spring Oauth的新手,我正在配置简单的OauthServer和资源服务器。

我如何使用代码获取访问令牌?

使用下面的curl命令:

  curl test3:test3@localhost:8080/oauth/token -d grant_type=password -d client_id=test3 -d client_secret=test3 -d username=user -d password=pass

我得到以下回复:

 {
       "access_token":"4b0d2c24-d02b-4294-943d-4781062bbaa8",
       "token_type":"bearer",
       "refresh_token":"12eae85b-3d7b-4ee2-a223-22e89e30e316",
       "expires_in":99,
       "scope":"openid"
    }

我如何使用客户端Java代码获得上述响应? 我尝试的是下面,但它给出了DefaultTokenService Null Pointer Exception的错误,但我不知道我是否使用了正确的方法。

 @Autowired
  DefaultTokenServices defaultTokenServices;


  public static void main(String[] args) throws Exception {

  /*  OAuth2AccessToken accessToken=new Test().getAccessToken("openid", "test3");
    System.out.println(accessToken.getTokenType());*/

    System.out.println(" "+new Test().getToken().getValue());

  }

 public OAuth2AccessToken getToken()
 {
   Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
   authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

   Map<String, String> requestParameters = new HashMap<String, String>();
   requestParameters.put("grant_type", "password");
   requestParameters.put("client_secret", "test3");
   requestParameters.put("client_id", "test3");
   requestParameters.put("username",  "user");
   requestParameters.put("password", "pass");
   requestParameters.put("redirect_uri", "http://localhost:8080/user");
   String clientId = "test3";
   boolean approved = true;
   Set<String> scope = new HashSet<String>();
   scope.add("openid");
   Set<String> resourceIds = new HashSet<String>();
   Set<String> responseTypes = new HashSet<String>();
   responseTypes.add("code");
   Map<String, Serializable> extensionProperties = new HashMap<String, Serializable>();

   OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId,
           authorities, approved, scope,
           resourceIds, null, responseTypes, extensionProperties);


   User userPrincipal = new User(requestParameters.get("username"), requestParameters.get("password"), true, true, true, true, authorities);

   UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
   OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
   System.out.println(auth.getAuthorities());
   return defaultTokenServices.createAccessToken(auth);
 }

0 个答案:

没有答案