перемещение примера Discord в отдельную папку
36
discord/README.MD
Normal file
@@ -0,0 +1,36 @@
|
||||
# Spring Boot + OAuth2 Discord
|
||||
|
||||
<img alt="Spring Boot" width="auto" height="100" src="https://spring.io/images/spring-initializr-4291cc0115eb104348717b82161a81de.svg">
|
||||
<img alt="Discord" width="auto" height="100" src="https://www.freepngimg.com/thumb/computer/94317-teamspeak-discord-servers-computer-facial-smile-expression.png">
|
||||
|
||||
## Перед запуском
|
||||
### Создание Discord Application
|
||||
Для запуска понадобиться обзавестить своим **Discord Application**.
|
||||
|
||||
1. Переходим на [Discord Developer Portal](https://discord.com/developers/applications)
|
||||
2. Создаём новое приложение
|
||||

|
||||
3. Переходим в раздел OAuth2
|
||||

|
||||
4. Добавляем адрес `http://127.0.0.1:8080/login/oauth2/code/discord` как адрес переадресации при успешной авторизации
|
||||

|
||||

|
||||
5. Создаём **Client Secret**
|
||||

|
||||

|
||||
6. Не забываем сохранить внесённые изменения!
|
||||

|
||||
|
||||
### Настройка Spring
|
||||
Открываем файл `src/main/resources/application.yml` и указываем там **Client ID** и **Client Secret**,
|
||||
которые были указаны в разделе **OAuth2**:
|
||||
```yaml
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
registration:
|
||||
discord:
|
||||
client-id: 965013316982423632
|
||||
client-secret: yhb13RP26WxfOru9fcQ6CxPcAUWr_2q6
|
||||
```
|
||||
21
discord/build.gradle
Normal file
@@ -0,0 +1,21 @@
|
||||
plugins {
|
||||
id 'org.springframework.boot' version '2.6.6'
|
||||
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group = 'example.oauth2'
|
||||
version = '1.0-SNAPSHOT'
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation('org.springframework.boot:spring-boot-starter-web')
|
||||
implementation('org.springframework.boot:spring-boot-starter-thymeleaf')
|
||||
|
||||
implementation('org.springframework.boot:spring-boot-starter-security')
|
||||
implementation('org.springframework.security:spring-security-oauth2-client')
|
||||
}
|
||||
BIN
discord/docs/1.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
discord/docs/2.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
discord/docs/3.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
discord/docs/4.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
discord/docs/5.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
discord/docs/6.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
BIN
discord/docs/7.png
Normal file
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,13 @@
|
||||
package example.oauth2.discord;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ApplicationDiscord {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApplicationDiscord.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package example.oauth2.discord.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||
|
||||
/*
|
||||
Отдельное спасибо
|
||||
- https://www.baeldung.com/spring-security-5-oauth2-login
|
||||
- https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/oauth2/client/CommonOAuth2Provider.java
|
||||
*/
|
||||
|
||||
@Configuration
|
||||
public class DiscordOAuth2Config {
|
||||
private static final String DISCORD_CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.discord";
|
||||
private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
|
||||
|
||||
private final Environment env;
|
||||
|
||||
public DiscordOAuth2Config(Environment env) {
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ClientRegistrationRepository discordClientRegistrationRepository() {
|
||||
String clientId = env.getProperty(DISCORD_CLIENT_PROPERTY_KEY + ".client-id");
|
||||
String clientSecret = env.getProperty(DISCORD_CLIENT_PROPERTY_KEY + ".client-secret");
|
||||
|
||||
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("discord")
|
||||
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|
||||
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
|
||||
.redirectUri(DEFAULT_REDIRECT_URL)
|
||||
.scope("identify", "email")
|
||||
.authorizationUri("https://discord.com/api/oauth2/authorize")
|
||||
.tokenUri("https://discord.com/api/oauth2/token")
|
||||
.userInfoUri("https://discord.com/api/users/@me")
|
||||
// revokeTokenUri: https://discord.com/api/oauth2/token/revoke
|
||||
.userNameAttributeName("username")
|
||||
.clientName("Discord")
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.build();
|
||||
|
||||
return new InMemoryClientRegistrationRepository(clientRegistration);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public OAuth2AuthorizedClientService discordAuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
|
||||
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package example.oauth2.discord.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/").setViewName("index");
|
||||
registry.addViewController("/secret").setViewName("secret");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package example.oauth2.discord.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||
private final OAuth2AuthorizedClientService authorizedClientService;
|
||||
|
||||
public WebSecurityConfig(ClientRegistrationRepository discordClientRegistrationRepository,
|
||||
OAuth2AuthorizedClientService discordAuthorizedClientService) {
|
||||
this.clientRegistrationRepository = discordClientRegistrationRepository;
|
||||
this.authorizedClientService = discordAuthorizedClientService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
//@formatter:off
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/").permitAll() //Доступ разрешен всем пользователей
|
||||
.anyRequest().authenticated() //Все остальные страницы требуют аутентификации
|
||||
.and()
|
||||
.oauth2Login()
|
||||
.clientRegistrationRepository(clientRegistrationRepository)
|
||||
.authorizedClientService(authorizedClientService)
|
||||
;
|
||||
//@formatter:on
|
||||
}
|
||||
}
|
||||
14
discord/src/main/resources/application.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
server:
|
||||
address: 127.0.0.1
|
||||
port: 8080
|
||||
|
||||
debug: false
|
||||
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
client:
|
||||
registration:
|
||||
discord:
|
||||
client-id: 965013316982423632
|
||||
client-secret: yhb13RP26WxfOru9fcQ6CxPcAUWr_2q6
|
||||
18
discord/src/main/resources/templates/index.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru"
|
||||
xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="https://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Discord OAuth2 Example</title>
|
||||
<link rel="icon" href="data:;base64,=">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Discord OAuth2 Example</h1>
|
||||
<hr>
|
||||
<p>
|
||||
Home public page<br>
|
||||
---> <a th:href="@{/secret}">Secret Page</a> <---<br>
|
||||
[ <a th:href="@{/oauth2/authorization/discord}">Login Discord</a> ]
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
12
discord/src/main/resources/templates/secret.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<title>Discord OAuth2 Example</title>
|
||||
<link rel="icon" href="data:;base64,=">
|
||||
</head>
|
||||
<body>
|
||||
<h1>Discord OAuth2 Example</h1>
|
||||
<hr>
|
||||
<p style="color: red">[TOP SECRET PAGE]</p>
|
||||
</body>
|
||||
</html>
|
||||