问题:
SpringBoot 2.5.x 如何集成 OpenID Connect 登录
解决:
OpenID Connect 是在 OAuth2 之上形成的一套身份验证机制,可以实现 SSO
pom.xml
|
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> |
application.yml
|
spring: security: oauth2: client: registration: crcc: client-id: "aaa" client-secret: "bbbb" provider: "crcc-provider" scope: "openid,profile" redirectUri: "https://aaaa:7443/login/oauth2/code/crcc" clientName: dddddd authorizationGrantType: authorization_code provider: crcc-provider: issuer-uri: "https://b.com" |
IndexController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
package com.telsafe.crccdemo; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * @author tangfh * @date 2021/8/25 */ @Controller public class IndexController { @GetMapping("/") //public String ss(Model mv, Authentication auth) { public String ss(Model mv, @AuthenticationPrincipal OidcUser user) { //mv.addAttribute("name", auth.getName()); mv.addAttribute("name", user.getName()); mv.addAttribute("token", user.getIdToken().getTokenValue()); return "index"; } } |
Spring Security 关键类
|
OidcAuthorizationCodeAuthenticationProvider implements AuthenticationProvider : 获取用户信息 OAuth2LoginAuthenticationFilter: 处理返回认证中心授权回调的参数? OAuth2AuthorizationRequestRedirectFilter: 检测如果没有登录则跳转到认证中心 OidcUserService: 获取用户信息 OidcUser |
参考: