001package com.nimbusds.oauth2.sdk;
002
003
004import java.util.LinkedHashMap;
005import java.util.Map;
006
007import net.jcip.annotations.Immutable;
008
009
010/**
011 * Client credentials grant. Used in access token requests with a client's
012 * identifier and secret.
013 *
014 * <p>Related specifications:
015 *
016 * <ul>
017 *     <li>OAuth 2.0 (RFC 6749), section 4.4.2.
018 * </ul>
019 */
020@Immutable
021public class ClientCredentialsGrant extends AuthorizationGrant {
022
023
024        /**
025         * The grant type.
026         */
027        public static final GrantType GRANT_TYPE = GrantType.CLIENT_CREDENTIALS;
028
029
030        /**
031         * Creates a new client credentials grant. The actual client
032         * credentials are included in the
033         * {@link com.nimbusds.oauth2.sdk.auth.ClientAuthentication client
034         * authentication} of the {@link com.nimbusds.oauth2.sdk.TokenRequest}.
035         */
036        public ClientCredentialsGrant() {
037
038                super(GRANT_TYPE);
039        }
040
041
042        @Override
043        public Map<String,String> toParameters() {
044
045                Map<String,String> params = new LinkedHashMap<>();
046                params.put("grant_type", GRANT_TYPE.getValue());
047                return params;
048        }
049
050
051        /**
052         * Parses a client credentials grant from the specified parameters.
053         *
054         * <p>Example:
055         *
056         * <pre>
057         * grant_type=client_credentials
058         * </pre>
059         *
060         * @param params The parameters.
061         *
062         * @return The client credentials grant.
063         *
064         * @throws ParseException If parsing failed.
065         */
066        public static ClientCredentialsGrant parse(final Map<String,String> params)
067                throws ParseException {
068
069                // Parse grant type
070                String grantTypeString = params.get("grant_type");
071
072                if (grantTypeString == null)
073                        throw new ParseException("Missing \"grant_type\" parameter", OAuth2Error.INVALID_REQUEST);
074
075                if (! GrantType.parse(grantTypeString).equals(GRANT_TYPE))
076                        throw new ParseException("The \"grant_type\" must be " + GRANT_TYPE, OAuth2Error.UNSUPPORTED_GRANT_TYPE);
077
078                return new ClientCredentialsGrant();
079        }
080}