基础知识:Spring Boot + Spring Security 5 + OAuth2 / OIDC客户端

皇甫雨石
2023-12-01

很长一段时间以来,我想使用Spring Security集成一个OpenID Connect提供程序。上次尝试时,我感到它非常复杂,并编写了自己的。由于Spring Security 5对OAuth2 Client具有本机支持,并且扩展了其对OpenID connect的使用,因此我想了解它的集成有多么容易。

对于此示例,我们将构建一个简单的应用程序,当我们试图访问受保护的端点时,会重定向到google

第1步:

https://start.spring.io创建一个具有以下依赖项的spring boot项目

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.fasterxml.jackson.module:jackson-module-kotlin'
    implementation 'org.jetbrains.kotlin:kotlin-reflect'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

第2步:

创建一个将显示当前用户身份验证数据的端点

@RestController
class HelloController {

    @GetMapping("/me")
    fun hello(currentUser: OAuth2AuthenticationToken): ResponseEntity<OAuth2AuthenticationToken> {
        return ResponseEntity.ok(currentUser)
    }

}

第3步:

在application.yml中配置OAuth2客户端信息。 在Google开发人员控制台中,将应用程序的重定向uri配置为http:// localhost:8080 / login / oauth2 / code / google

# @see https://console.developers.google.com/apis/ to create your client credentials
logging.level.org.springframework: INFO
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            provider: google
            client-id: <<your-client-id>>
            client-secret: <<your-client-secret>> 
            client-authentication-method: basic
            authorization-grant-type: authorization_code
            scope:
              - openid
              - email
              - profile
              - https://www.googleapis.com/auth/tasks.readonly
        provider:
          google:
            issuer-uri: https://accounts.google.com

第4步:

运行应用程序,转到http:// localhost:8080 / me,完成登录过程,您将看到此信息。

{
"authorities": [
{
"authority": "ROLE_USER",
"attributes": {
"at_hash": "28AV0o6xKM8f3UQlljlGuw",
"sub": "10080000000000000",
"email_verified": true,
"iss": "https://accounts.google.com",
"given_name": "Syamala",
"locale": "en",
"picture": "https://lh6.googleusercontent.com/photo.jpg",
"aud": [
"client-id"
],
"azp": "client-id",
"name": "Syamala Umamaheswaran",
"exp": "2019-03-24T18:27:19Z",
"family_name": "Umamaheswaran",
"iat": "2019-03-24T17:27:19Z",
"email": "xxxx@gmail.com"
},
"idToken": {...},
"userInfo": null
}
],
"details": null,
"authenticated": true,
"principal": {},
"authorizedClientRegistrationId": "google",
"credentials": "",
"name": "10080000000000000"
}

心里话:

令我震惊的是,无需编写任何安全性代码就可以与OpenID Connect提供程序集成,我需要知道它的工作方式如此轻松。细节中有魔鬼,请继续关注我的下一篇博客文章,其中我解释了幕后故事以及如何访问受保护的资源以及如何自动刷新令牌。

完整的源代码@ https://github.com/shyamz-22/oidc-spring-security-5

原文链接:https://dev.to//shyamala_u/spring-boot--spring-security-5--oauth2oidc-client---basics-4ibo

 类似资料: