1

我是 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);
 }
4

0 回答 0