You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
4.8 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /*
  2. * Copyright 2018 Red Hat, Inc. and/or its affiliates
  3. * and other contributors as indicated by the @author tags.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package org.keycloak.social.discord;
  18. import com.fasterxml.jackson.databind.JsonNode;
  19. import org.jboss.logging.Logger;
  20. import org.keycloak.broker.oidc.AbstractOAuth2IdentityProvider;
  21. import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper;
  22. import org.keycloak.broker.provider.BrokeredIdentityContext;
  23. import org.keycloak.broker.provider.IdentityBrokerException;
  24. import org.keycloak.broker.provider.util.SimpleHttp;
  25. import org.keycloak.broker.social.SocialIdentityProvider;
  26. import org.keycloak.events.EventBuilder;
  27. import org.keycloak.models.KeycloakSession;
  28. import org.keycloak.services.ErrorPageException;
  29. import org.keycloak.services.messages.Messages;
  30. import javax.ws.rs.core.Response;
  31. import java.util.Set;
  32. /**
  33. * @author <a href="mailto:wadahiro@gmail.com">Hiroyuki Wada</a>
  34. */
  35. public class DiscordIdentityProvider extends AbstractOAuth2IdentityProvider<DiscordIdentityProviderConfig>
  36. implements SocialIdentityProvider<DiscordIdentityProviderConfig> {
  37. private static final Logger log = Logger.getLogger(DiscordIdentityProvider.class);
  38. public static final String AUTH_URL = "https://discord.com/api/oauth2/authorize";
  39. public static final String TOKEN_URL = "https://discord.com/api/oauth2/token";
  40. public static final String PROFILE_URL = "https://discord.com/api/users/@me";
  41. public static final String GROUP_URL = "https://discord.com/api/users/@me/guilds";
  42. public static final String DEFAULT_SCOPE = "identify email";
  43. public static final String GUILDS_SCOPE = "guilds";
  44. public DiscordIdentityProvider(KeycloakSession session, DiscordIdentityProviderConfig config) {
  45. super(session, config);
  46. config.setAuthorizationUrl(AUTH_URL);
  47. config.setTokenUrl(TOKEN_URL);
  48. config.setUserInfoUrl(PROFILE_URL);
  49. }
  50. @Override
  51. protected boolean supportsExternalExchange() {
  52. return true;
  53. }
  54. @Override
  55. protected String getProfileEndpointForValidation(EventBuilder event) {
  56. return PROFILE_URL;
  57. }
  58. @Override
  59. protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode profile) {
  60. BrokeredIdentityContext user = new BrokeredIdentityContext(getJsonProperty(profile, "id"));
  61. user.setUsername(getJsonProperty(profile, "username") + "#" + getJsonProperty(profile, "discriminator"));
  62. user.setEmail(getJsonProperty(profile, "email"));
  63. user.setIdpConfig(getConfig());
  64. user.setIdp(this);
  65. AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());
  66. return user;
  67. }
  68. @Override
  69. protected BrokeredIdentityContext doGetFederatedIdentity(String accessToken) {
  70. log.debug("doGetFederatedIdentity()");
  71. JsonNode profile = null;
  72. try {
  73. profile = SimpleHttp.doGet(PROFILE_URL, session).header("Authorization", "Bearer " + accessToken).asJson();
  74. } catch (Exception e) {
  75. throw new IdentityBrokerException("Could not obtain user profile from discord.", e);
  76. }
  77. if (getConfig().hasAllowedGuilds()) {
  78. if (!isAllowedGuild(accessToken)) {
  79. throw new ErrorPageException(session, Response.Status.FORBIDDEN, Messages.INVALID_REQUESTER);
  80. }
  81. }
  82. return extractIdentityFromProfile(null, profile);
  83. }
  84. protected boolean isAllowedGuild(String accessToken) {
  85. try {
  86. JsonNode guilds = SimpleHttp.doGet(GROUP_URL, session).header("Authorization", "Bearer " + accessToken).asJson();
  87. Set<String> allowedGuilds = getConfig().getAllowedGuildsAsSet();
  88. for (JsonNode guild : guilds) {
  89. String guildId = getJsonProperty(guild, "id");
  90. if (allowedGuilds.contains(guildId)) {
  91. return true;
  92. }
  93. }
  94. return false;
  95. } catch (Exception e) {
  96. throw new IdentityBrokerException("Could not obtain guilds the current user is a member of from discord.", e);
  97. }
  98. }
  99. @Override
  100. protected String getDefaultScopes() {
  101. if (getConfig().hasAllowedGuilds()) {
  102. return DEFAULT_SCOPE + " " + GUILDS_SCOPE;
  103. } else {
  104. return DEFAULT_SCOPE;
  105. }
  106. }
  107. }