共计 2053 个字符,预计需要花费 6 分钟才能阅读完成。
视频演示: https://www.bilibili.com/video/BV1M54y1z7A9/
需要完成以下步骤:
-
创建工程并引入依赖包
- spring-boot-starter-oauth2-client
- spring-boot-starter-security
- spring-boot-starter-web
- 创建 Security 配置信息
- 创建 Github、Google 的 client-id 和 client-secret
Oauth2GoogleLoginApplication.java
package com.deepincoding.oauth2googlelogin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Oauth2GoogleLoginApplication {public static void main(String[] args) {SpringApplication.run(Oauth2GoogleLoginApplication.class, args);
}
}
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;}
}
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();}
}
application.yml
spring:
security:
oauth2:
client:
registration:
github:
client-id: d64d35f9f66ea04ba64f
client-secret: b84a72f20fcec596deb947860cd4eacaf55b0f5b
google:
client-id: 195066099347-nj4et113vfl9p0aq9k5cb4hd6kg0c3hh.apps.googleusercontent.com
client-secret: Wk5XNm8wv36R0h4zGCxWOfYn
本文使用 mdnice 排版
正文完
发表至: springboot
2020-06-29