1. 首页
  2. 软件开发
  3. OAuth2——GitHub授权登录案例实现的详细步骤

OAuth2——GitHub授权登录案例实现的详细步骤

  • 发布于 2024-08-19
  • 0 次阅读

实现GitHub授权登录的案例通常涉及使用OAuth2协议。

在Spring框架中实现GitHub授权登录的详细步骤如下:

  1. 创建GitHub应用:在GitHub上注册一个OAuth应用程序,获取Client ID和Client Secret。
  2. 创建Spring Boot应用:使用Spring Boot创建一个新的项目。
  3. 添加依赖:在 pom.xml 中添加Spring Security OAuth2依赖。
  4. 配置应用:配置应用程序以允许GitHub授权登录。
  5. 创建控制器:编写控制器处理GitHub回调和登录逻辑。
  6. 创建视图:编写前端页面以实现GitHub登录按钮和展示用户信息。

1. 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

2. 配置应用

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        http
            .authorizeRequests()
            .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }
}

3. 创建控制器

@Controller
public class LoginController {
   

    @GetMapping("/")
    public String index() {
   
        return "index";
    }

    @GetMapping("/login")
    public String login() {
   
        return "login";
    }

    @GetMapping("/login/github")
    public String loginGitHub() {
   
        return "redirect:/oauth2/authorization/github";
    }

    @GetMapping("/user")
    public String user(Principal principal, Model model) {
   
        model.addAttribute("username", principal.getName());
        return "user";
    }
}

4. 创建视图

<!DOCTYPE html>
<html lang="en">
<body>
    <a href="/login/github">Login with GitHub</a>
</body>
</html>
  1. 创建视图
<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Welcome, ${username}!</h1>
</body>
</html>

通过以上步骤和代码,可以实现一个简单的Spring Boot应用程序,允许用户通过GitHub授权登录。用户点击登录按钮后将被重定向到GitHub登录页面,登录成功后将返回到您的应用程序并显示用户信息。

原文链接: https://blog.csdn.net/2401_82884096/article/details/137043130