001package com.nimbusds.oauth2.sdk; 002 003 004import java.util.LinkedHashMap; 005import java.util.Map; 006 007import net.jcip.annotations.Immutable; 008 009import com.nimbusds.oauth2.sdk.token.RefreshToken; 010 011 012/** 013 * Refresh token grant. Used in refresh token requests. 014 * 015 * <p>Note that the optional scope parameter is not supported. 016 * 017 * <p>Related specifications: 018 * 019 * <ul> 020 * <li>OAuth 2.0 (RFC 6749), section 6. 021 * </ul> 022 */ 023@Immutable 024public final class RefreshTokenGrant extends AuthorizationGrant { 025 026 027 /** 028 * The associated grant type. 029 */ 030 public static final GrantType GRANT_TYPE = GrantType.REFRESH_TOKEN; 031 032 033 /** 034 * The refresh token. 035 */ 036 private final RefreshToken refreshToken; 037 038 039 /** 040 * Creates a new refresh token grant. 041 * 042 * @param refreshToken The refresh token. Must not be {@code null}. 043 */ 044 public RefreshTokenGrant(final RefreshToken refreshToken) { 045 046 047 super(GRANT_TYPE); 048 049 if (refreshToken == null) 050 throw new IllegalArgumentException("The refresh token must not be null"); 051 052 this.refreshToken = refreshToken; 053 } 054 055 056 /** 057 * Gets the refresh token. 058 * 059 * @return The refresh token. 060 */ 061 public RefreshToken getRefreshToken() { 062 063 return refreshToken; 064 } 065 066 067 @Override 068 public Map<String,String> toParameters() { 069 070 Map<String,String> params = new LinkedHashMap<String,String>(); 071 params.put("grant_type", GRANT_TYPE.getValue()); 072 params.put("refresh_token", refreshToken.getValue()); 073 return params; 074 } 075 076 077 /** 078 * Parses a refresh token grant from the specified parameters. 079 * 080 * <p>Example: 081 * 082 * <pre> 083 * grant_type=refresh_token 084 * refresh_token=tGzv3JOkF0XG5Qx2TlKWIA 085 * </pre> 086 * 087 * @param params The parameters. 088 * 089 * @return The refresh token grant. 090 * 091 * @throws ParseException If parsing failed. 092 */ 093 public static RefreshTokenGrant parse(final Map<String,String> params) 094 throws ParseException { 095 096 // Parse grant type 097 String grantTypeString = params.get("grant_type"); 098 099 if (grantTypeString == null) 100 throw new ParseException("Missing \"grant_type\" parameter", OAuth2Error.INVALID_REQUEST); 101 102 GrantType grantType = new GrantType(grantTypeString); 103 104 if (! grantType.equals(GRANT_TYPE)) 105 throw new ParseException("The \"grant_type\" must be " + GRANT_TYPE, OAuth2Error.INVALID_GRANT); 106 107 // Parse refresh token 108 String refreshTokenString = params.get("refresh_token"); 109 110 if (refreshTokenString == null || refreshTokenString.trim().isEmpty()) 111 throw new ParseException("Missing or empty \"refresh_token\" parameter", OAuth2Error.INVALID_REQUEST); 112 113 RefreshToken refreshToken = new RefreshToken(refreshTokenString); 114 115 return new RefreshTokenGrant(refreshToken); 116 } 117}