Google或Github 登录Web引用
如何使用 Google或 Github账号注册和登录 Web应用
1 工程代码
1.1Maven依赖
<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>
1.2 SecurityConfig.java 配置信息
package com.deepincoding.oauth2googlelogin;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**").authorizeRequests()
.antMatchers("/", "/guest").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}
1.3 MessageController.java
package com.deepincoding.oauth2googlelogin;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Log4j2
public class MessageController {
@GetMapping("/")
public String hello(){
return "Hello Google Github.";
}
@GetMapping("/guest")
public String guest(){
return "Hello Guest.";
}
@GetMapping("/admin")
public OAuth2User admin(@AuthenticationPrincipal OAuth2User principal){
return principal;
}
}
1.3 application.yml 属性文件
spring:
security:
oauth2:
client:
registration:
github:
client-id: bed0b78029d1754d0c69
client-secret: a8d8f32f685a8e8b74ea9f6271631a7ed65f140c
google:
client-id: 195066099347-g3opjvnac6e4dvndk3o5d3qnnk5ce437.apps.googleusercontent.com
client-secret: qaNIJA1ZmRAjbSGgoRbf_Hy_
2 获取Google client-id和client-secret
访问 https://console.developers.google.com/
创建客户端ID
输入URI:http://localhost:8080/login/oauth2/login/google 然后创建
生成的client-id和client-secret拷贝到application.yml文件里
3 获取Github client-id和client-secret
访问 https://github.com/settings/developers 创建 New OAuth App
4 运行应用
在浏览器上输入http://localhost:8080/admin