当前位置:网站首页>Login with a third-party account
Login with a third-party account
2022-07-24 02:07:00 【PS cool tutorial】
GitHub Sign in
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zzhua</groupId>
<artifactId>demo-github</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-github</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ProjectConfig
package com.zzhua.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {
/*private ClientRegistration clientRegistration2() { ClientRegistration cr = ClientRegistration.withRegistrationId("github") .clientId("00b3e3fab6ce54d9b959") .clientSecret("79ae5e50f40cfcdf2abad77b3af435d6a7ab9764") .scope(new String[]{"read:user"}) .authorizationUri("https://github.com/login/oauth/authorize") .tokenUri("https://github.com/login/oauth/access_token") .userInfoUri("https://api.github.com/user") .userNameAttributeName("id") .clientName("GitHub") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}") .build(); return cr; }*/
private ClientRegistration clientRegistration() {
return CommonOAuth2Provider.GITHUB.getBuilder("github")
.clientId("00b3e3fab6ce54d9b959")
.clientSecret("79ae5e50f40cfcdf2abad77b3af435d6a7ab9764")
.build();
}
// take ClientRegistrationRepository Type of bean Add to Spring Context , The bean Contains the ClientRegistration References to
@Bean
public ClientRegistrationRepository clientRepository() {
ClientRegistration clientRegistration = clientRegistration();
return new InMemoryClientRegistrationRepository(clientRegistration);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// Set the authentication method
http.oauth2Login(); // Added OAuth2LoginAuthenticationFilter filter
// Specify the user who needs to be authenticated , In order to make a request
http
.authorizeRequests()
.anyRequest().authenticated();
}
}
MainController
package com.zzhua.controller;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class MainController {
@GetMapping("/")
public String main(OAuth2AuthenticationToken token, HttpServletRequest req) {
System.out.println(token);
Object o = token.getPrincipal().getAttributes().get("login");
req.setAttribute("login", o);
return "main.html";
}
}
DemoGithubApplication
package com.zzhua;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoGithubApplication {
public static void main(String[] args) {
SpringApplication.run(DemoGithuubApplication.class, args);
}
}
main.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello there! Home page </h1>
<span th:text="${login}"></span>
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
home page ~
</body>
</html>
Gitee Sign in
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zzhua</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Network request -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- alibaba Of fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
thymeleaf:
cache: false
gitee:
oauth:
clientid: 33caa50212b18ad06462f0648be68ee6a82b63792c0f6f77b09ef361ce80a3f4
clientsecret: f7999a14eab91b100871c8bd307859541eba7517871d173c07f460f615d3ded4
callback: http://localhost:8080/callback
GiteeController
package com.zzhua.demo.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;
@Controller
public class GiteeController {
/** * gitee Provided in the authorization appid and appkey */
@Value("${gitee.oauth.clientid}")
public String CLIENTID;
@Value("${gitee.oauth.clientsecret}")
public String CLIENTSECRET;
@Value("${gitee.oauth.callback}")
public String URL;
/** * Request authorization page */
@GetMapping(value = "/auth")
public String qqAuth(HttpSession session) {
// Used for third-party applications to prevent CSRF attack
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
session.setAttribute("state", uuid);
// Step1: obtain Authorization Code
String url = "https://gitee.com/oauth/authorize?response_type=code" +
"&client_id=" + CLIENTID +
"&redirect_uri=" + URLEncoder.encode(URL) +
"&state=" + uuid +
"&scope=user_info";
// Because it uses thymeleaf template engine , So you can't parse a web address , Redirection only
return "redirect:"+url;
}
/** * Authorize the callback */
@GetMapping(value = "/callback")
public String qqCallback(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
// obtain Authorization Code
String code = request.getParameter("code");
// The status code we put in the address
String state = request.getParameter("state");
String uuid = (String) session.getAttribute("state");
// Verify the status code we sent
if (null != uuid) {
// The status code is incorrect , Go straight back to the login page
if (!uuid.equals(state)) {
return "index";
}
}
// Step2: adopt Authorization Code obtain Access Token
String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
"&client_id=" + CLIENTID +
"&client_secret=" + CLIENTSECRET +
"&code=" + code +
"&redirect_uri=" + URL;
JSONObject accessTokenJson = GiteeHttpClient.getAccessToken(url);
// Step3: Get user information
url = "https://gitee.com/api/v5/user?access_token=" + accessTokenJson.get("access_token");
JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
/** * After getting user information , It's time to write your own business logic */
System.out.println(jsonObject);
return "hello";
}
}
GiteeHttpClient
package com.zzhua.demo.controller;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class GiteeHttpClient {
/** * obtain Access Token * post */
public static JSONObject getAccessToken(String url) throws IOException {
HttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
String result = EntityUtils.toString(entity, "UTF-8");
return JSONObject.parseObject(result);
}
httpPost.releaseConnection();
return null;
}
/** * Get user information * get */
public static JSONObject getUserInfo(String url) throws IOException {
JSONObject jsonObject = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.parseObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
}
DemoGiteeApplication
@SpringBootApplication
public class DemoGiteeApplication{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World!</title>
</head>
<body>
<h1> Landing successful , welcome </h1>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a th:href="@{/auth}" class="link" title="Gitee Sign in ">gitee Sign in </a>
</body>
</html>
边栏推荐
- Jar package used by jsonarray in main function provided by leetcode
- Notes - record a dynamic datasource please check the setting of primary problem solving
- STM32概念和安装【第一天】
- LoadRunner12安装、录制第一个脚本以及代理服务器没有响应解决
- 中小型医院基础网络解决方案
- Troisième semaine d'été
- Basic knowledge of mathematical vector
- How to use the directory classification function of the new version of easycvr (v2.5.0)?
- 浅谈元宇宙中DeFi的可能性和局限性
- 暑假第三周
猜你喜欢

MySQL Basics (operators, sorting and paging, multi table queries, functions)
![[pumpkin Book ml] (task3) decision tree (updating)](/img/4c/fc7157518ad729400d605b811323de.png)
[pumpkin Book ml] (task3) decision tree (updating)

College degree want to 0 basic programming after looking for a job feasible?
![[bdsec CTF 2022] partial WP](/img/00/25c1953a324fbf04e3baf592079978.png)
[bdsec CTF 2022] partial WP

Install go environment under Kali

5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字

Install SSL Certificate in Litespeed web server

5年接觸近百比特老板,身為獵頭的我,發現昇職的秘密不過4個字

Graduation design campus information publishing platform website source code

Improvement of DB file sequential read caused by insert
随机推荐
Structure the second operation of the actual combat battalion module
Local empowerment learning
NETCORE - how to ensure that icollection or list privatization is not externally modified?
浅谈领域驱动设计
The difference between.Split (",", -1) and.Split (",")
On the possibility and limitation of defi in the metauniverse
STM32 concept and installation [day 1]
LiteSpeed Web服务器中安装SSL证书
Customer first | domestic Bi leader, smart software completes round C financing
Decrypt redis to help the e-commerce seckill system behind the double 11
Sword finger offer II 031. Least recently used cache
In depth understanding - wechat developer tools
解决script标签写在元素节点前面无法获取元素节点的问题
微信小程序之性能优化(分包、运行流程细节、精简结构、原生组件通信)
async await详解 & Promise
响应式布局一个网页在不同设备显示不同效果)meta:vp
View Binding 混淆问题。我两天都在研究混淆。
Redraw the button and make your own circular LED indicator
架构实战营模块二作业
Redis 6.0 source code learning simple dynamic string