001package com.nimbusds.oauth2.sdk; 002 003 004import java.util.Map; 005 006 007/** 008 * Authorisation grant. Extending classes should be immutable. 009 * 010 * <p>Supported authorisation grant types: 011 * 012 * <ul> 013 * <li>{@link GrantType#AUTHORIZATION_CODE Authorisation code} 014 * <li>{@link GrantType#PASSWORD Resource owner password credentials} 015 * <li>{@link GrantType#CLIENT_CREDENTIALS Client credentials} 016 * <li>{@link GrantType#REFRESH_TOKEN Refresh token} 017 * </ul> 018 * 019 * <p>Related specifications: 020 * 021 * <ul> 022 * <li>OAuth 2.0 (RFC 6749), sections 1.3. 023 * </ul> 024 * 025 * @author Vladimir Dzhuvinov 026 */ 027public abstract class AuthorizationGrant { 028 029 030 /** 031 * The authorisation grant type. 032 */ 033 private final GrantType type; 034 035 036 /** 037 * Creates a new authorisation grant. 038 * 039 * @param type The authorisation grant type. Must not be {@code null}. 040 */ 041 protected AuthorizationGrant(final GrantType type) { 042 043 if (type == null) 044 throw new IllegalArgumentException("The grant type must not be null"); 045 046 this.type = type; 047 } 048 049 050 /** 051 * Gets the authorisation grant type. 052 * 053 * @return The authorisation grant type. 054 */ 055 public GrantType getType() { 056 057 return type; 058 } 059 060 061 /** 062 * Return the parameters for the authorisation grant. 063 * 064 * @return The parameters. 065 */ 066 public abstract Map<String,String> toParameters(); 067 068 069 /** 070 * Parses an authorisation grant from the specified parameters. 071 * 072 * @param params The parameters. Must not be {@code null}. 073 * 074 * @return The authorisation grant. 075 * 076 * @throws ParseException If parsing failed or the grant type is not 077 * supported. 078 */ 079 public static AuthorizationGrant parse(final Map<String,String> params) 080 throws ParseException { 081 082 // Parse grant type 083 String grantTypeString = params.get("grant_type"); 084 085 if (grantTypeString == null) 086 throw new ParseException("Missing \"grant_type\" parameter", OAuth2Error.INVALID_REQUEST); 087 088 GrantType grantType = new GrantType(grantTypeString); 089 090 if (grantType.equals(GrantType.AUTHORIZATION_CODE)) { 091 092 return AuthorizationCodeGrant.parse(params); 093 094 } else if (grantType.equals(GrantType.REFRESH_TOKEN)) { 095 096 return RefreshTokenGrant.parse(params); 097 } 098 099 else if (grantType.equals(GrantType.PASSWORD)) { 100 101 return ResourceOwnerPasswordCredentialsGrant.parse(params); 102 103 } else if (grantType.equals(GrantType.CLIENT_CREDENTIALS)) { 104 105 return ClientCredentialsGrant.parse(params); 106 107 } else { 108 109 throw new ParseException("Unsupported grant type: " + grantType, OAuth2Error.UNSUPPORTED_GRANT_TYPE); 110 } 111 } 112}