0

добавлен пример для Twitch

This commit is contained in:
2022-04-17 19:00:52 +03:00
parent fb86fa2e8a
commit 3fa106491a
19 changed files with 246 additions and 1 deletions

42
twitch/README.MD Normal file
View File

@@ -0,0 +1,42 @@
# Spring Boot + OAuth2 Twitch
<img alt="Spring Boot" width="auto" height="100" src="../docs/spring-boot.svg">
<img alt="Spring Boot" width="auto" height="100" src="docs/twitch.svg">
## Перед запуском
### Создание Application
Для запуска понадобиться обзавестить своим **Twitch Application**.
1. Переходим в [Twitch Developers](https://dev.twitch.tv/console)
2. Создаём новое OAuth приложение
![](docs/1.png)
3. Заполняем поля
⚠️ **Внимание!** Есть ряд ограничений.
Для **Name**:
- Не должен содежрать слово "twitch"
Для **OAuth Redirect URLs**:
- Если запуск **не** локальный, требуется HTTPS протокол
- Если запуск локальный, то вводить не `127.0.0.1`, а `localhost`
![](docs/2.png)
4. После переходим в управление приложением
![](docs/3.png)
5. Сгенерировать новый **Client Secret**
![](docs/4.png)
![](docs/5.png)
### Настройка Spring
Открываем файл `src/main/resources/application.yml` и указываем там **Client ID** и **Client Secret**:
```yaml
spring:
security:
oauth2:
client:
registration:
twitch:
client-id: 89fwqw0i5b9857n5orpz3sb3dyfhti
client-secret: mlatyu8twmzq69mx0um1hbahfi7p31
```

21
twitch/build.gradle Normal file
View 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-freemarker')
implementation('org.springframework.boot:spring-boot-starter-security')
implementation('org.springframework.security:spring-security-oauth2-client')
}

BIN
twitch/docs/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

BIN
twitch/docs/2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

BIN
twitch/docs/3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

BIN
twitch/docs/4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

BIN
twitch/docs/5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

19
twitch/docs/twitch.svg Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg version="1.1" id="svg5" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 10.16 10.7188"
width="10.160001mm" height="10.718801mm">
<style type="text/css">
.p1{fill:#8d23a9;}
.p2{fill:#ffffff;}
</style>
<g transform="translate(-78.071167,-86.006942)">
<path class="p1"
d="m 80.611166,96.018776 v -0.706967 h -1.269999 -1.27 v -3.644794 -3.644793 l 0.424531,-1.00764 0.424531,-1.00764 h 4.655469 4.65547 v 3.240627 3.240626 l -1.411827,1.411807 -1.411826,1.411807 h -0.986377 -0.986376 l -0.706929,0.706967 -0.706929,0.706967 h -0.704868 -0.70487 z"/>
<path class="p2"
d="m 84.416934,93.347543 h 1.269963 l 0.709102,-0.709065 0.709102,-0.709064 v -2.398203 -2.398202 h -3.5306 -3.530601 v 3.107267 3.107267 h 0.846666 0.846667 v 0.704831 0.70483 l 0.704869,-0.70483 0.704869,-0.704831 z"/>
<path class="p1"
d="m 83.997834,90.236042 v -1.4097 h 0.702734 0.702733 v 1.4097 1.409701 h -0.702733 -0.702734 z"/>
<path class="p1"
d="m 81.745701,90.236042 v -1.4097 h 0.702732 0.702733 v 1.4097 1.409701 h -0.702733 -0.702732 z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@@ -0,0 +1,13 @@
package example.oauth2.twitch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationTwitch {
public static void main(String[] args) {
SpringApplication.run(ApplicationTwitch.class, args);
}
}

View File

@@ -0,0 +1,15 @@
package example.oauth2.twitch.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");
}
}

View File

@@ -0,0 +1,59 @@
package example.oauth2.twitch.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
- https://discuss.dev.twitch.tv/t/springboot-oauth2-integration-with-twitch/35011
- https://www.youtube.com/watch?v=n9oO5D-aHCY
*/
@Configuration
public class TwitchOAuth2Config {
private static final String TWITCH_CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.twitch";
private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
private final Environment env;
public TwitchOAuth2Config(Environment env) {
this.env = env;
}
@Bean
public ClientRegistrationRepository twitchClientRegistrationRepository() {
String clientId = env.getProperty(TWITCH_CLIENT_PROPERTY_KEY + ".client-id");
String clientSecret = env.getProperty(TWITCH_CLIENT_PROPERTY_KEY + ".client-secret");
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("twitch")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(DEFAULT_REDIRECT_URL)
.scope("user:read:email")
.authorizationUri("https://id.twitch.tv/oauth2/authorize")
.tokenUri("https://id.twitch.tv/oauth2/token")
.userInfoUri("https://id.twitch.tv/oauth2/userinfo")
.userNameAttributeName("preferred_username")
.clientName("Twitch")
.clientId(clientId)
.clientSecret(clientSecret)
.build();
return new InMemoryClientRegistrationRepository(clientRegistration);
}
@Bean
public OAuth2AuthorizedClientService twitchAuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
}
}

View File

@@ -0,0 +1,37 @@
package example.oauth2.twitch.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 twitchClientRegistrationRepository,
OAuth2AuthorizedClientService twitchAuthorizedClientService) {
this.clientRegistrationRepository = twitchClientRegistrationRepository;
this.authorizedClientService = twitchAuthorizedClientService;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//@formatter:off
http
.authorizeRequests()
.antMatchers("/").permitAll() //Доступ разрешен всем пользователей
.anyRequest().authenticated() //Все остальные страницы требуют аутентификации
.and()
.oauth2Login()
.clientRegistrationRepository(clientRegistrationRepository)
.authorizedClientService(authorizedClientService)
;
//@formatter:on
}
}

View File

@@ -0,0 +1,17 @@
server:
address: 127.0.0.1
port: 8080
debug: false
spring:
freemarker:
template-loader-path: classpath:/templates
suffix: .ftlh
security:
oauth2:
client:
registration:
twitch:
client-id: 89fwqw0i5b9857n5orpz3sb3dyfhti
client-secret: mlatyu8twmzq69mx0um1hbahfi7p31

View File

@@ -0,0 +1,2 @@
</body>
</html>

View File

@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<title>Twitch OAuth2 Example</title>
<link rel="icon" href="data:;base64,=">
</head>
<body>
<h1>Twitch OAuth2 Example</h1>
<hr>

View File

@@ -0,0 +1,7 @@
<#include "includes/header.ftlh">
<p>
Home public page<br>
---&gt; <a href="/secret">Secret Page</a> &lt;---<br>
[ <a href="/oauth2/authorization/twitch">Login Twitch</a> ]
</p>
<#include "includes/foother.ftlh">

View File

@@ -0,0 +1,3 @@
<#include "includes/header.ftlh">
<p style="color: red">[TOP SECRET PAGE]</p>
<#include "includes/foother.ftlh">