Spring集成Github单点登录时跳转本地登录页如何修改为跳Github登录
解决方案
第一步:添加Maven依赖
在你的pom.xml中引入OAuth2客户端相关启动器:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</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-oauth2-client</artifactId> </dependency> </dependencies>
第二步:申请GitHub OAuth凭证
进入GitHub开发者后台创建OAuth应用,获取client-id和client-secret,回调地址配置为http://localhost:8080/login/oauth2/code/github。
第三步:添加OAuth配置
在application.yml中填入GitHub的OAuth配置参数:
spring: security: oauth2: client: registration: github: client-id: 你申请到的GitHub客户端ID client-secret: 你申请到的GitHub客户端密钥 scope: read:user,user:email provider: github: authorization-uri: https://github.com/login/oauth/authorize token-uri: https://github.com/login/oauth/access_token user-info-uri: https://api.github.com/user
第四步:修改安全配置跳过本地登录页
创建安全配置类,将未认证请求直接重定向到GitHub授权页,无需经过本地/login页面:
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.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .oauth2Login(oauth2 -> oauth2 // 直接指定GitHub授权入口为登录页,跳过本地登录选择页 .loginPage("/oauth2/authorization/github") .permitAll() ); return http.build(); } }
效果验证
启动应用后访问根路径/,会直接跳转至GitHub登录页,若用户已登录GitHub则会直接跳过登录步骤完成授权,自动返回应用,实现和Gmail关联登录完全一致的一键登录效果。
内容的提问来源于stack exchange,提问作者Feridun
相关产品推荐
相关产品推荐

