1

私はSpring Oauthが初めてで、単純なOauthServerとResource Serverを構成しています。

コードを使用してアクセス トークンを取得するにはどうすればよいですか?

以下の 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