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