OIDC9-OIDC集成登录功能(SpringBoot3.0)

1.项目依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.me.mengyu.auth.net</groupId>

  <artifactId>mengyu-love</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>war</packaging>

  <description>Auth</description>

  <dependencies>

  <!-- JWT认证利用 -->

  <dependency>

    <groupId>io.jsonwebtoken</groupId>

    <artifactId>jjwt-api</artifactId>

    <version>0.11.5</version>

    </dependency>

    <dependency>

      <groupId>io.jsonwebtoken</groupId>

      <artifactId>jjwt-impl</artifactId>

      <version>0.11.5</version>

      <scope>runtime</scope>

    </dependency>

    <dependency>

      <groupId>io.jsonwebtoken</groupId>

      <artifactId>jjwt-jackson</artifactId>

      <version>0.11.5</version>

  </dependency>

 

  <!-- OIDC认证利用 -->

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-oauth2-client</artifactId>

    <version>3.0.0</version>

  </dependency>

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

    <version>3.0.0</version>

  </dependency>

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

    <version>3.0.0</version>

  </dependency>

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-security</artifactId>

    <version>3.0.0</version>

  </dependency>

</dependencies>

<build>

    <plugins>

      <plugin>

        <groupId>org.apache.maven.plugins</groupId>

        <artifactId>maven-war-plugin</artifactId>

        <version>3.3.2</version>

        <configuration>

            <failOnMissingWebXml>false</failOnMissingWebXml>

        </configuration>

      </plugin>

    </plugins>

  </build>

</project>

2.配置应用程序属性

        src/main/resources/application.yml 中配置 OIDC 相关属性,具体取决于您使用的身份提供者(如 GoogleOktaAuth0 等):

spring:

  security:

    oauth2:

      client:

        registration:

          my-client:

            client-id: your-client-id

            client-secret: your-client-secret

            scope: openid, profile, email

            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"

            authorization-grant-type: authorization_code

        provider:

          my-provider:

            authorization-uri: https://your-authorization-server.com/auth

            token-uri: https://your-authorization-server.com/token

            user-info-uri: https://your-authorization-server.com/userinfo

3.创建安全配置类

创建一个安全配置类,继承 WebSecurityConfigurerAdapter,以配置安全性:

package com.me.mengyu.love.config;

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;

import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

@Configuration

@EnableWebSecurity

public class SecurityConfig {

    @Bean

    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http

            .authorizeRequests()

                .requestMatchers("/", "/login", "/error").permitAll() // 允许所有用户访问的页面

                .anyRequest().authenticated() // 其余请求需要认证

            .and()

            .oauth2Login()

                .loginPage("/login") // 自定义登录页

                .defaultSuccessUrl("/home", true) // 登录成功后的默认跳转页

                .failureUrl("/login?error=true") // 登录失败后的跳转页

            .and()

            .exceptionHandling()

                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")); // 未认证用户访问的处理

       

        return http.build(); // 返回构建的 HttpSecurity

    }

}

注意1在 Spring Security 5.0 及以后的版本中,WebSecurityConfigurerAdapter 类已被标记为不推荐使用(deprecated)。因此,Spring Boot 3.0 和 Spring Security 5.7 及更高版本也不再需要使用 WebSecurityConfigurerAdapter。相应的配置可以通过新的安全配置方法来实现,使用 SecurityFilterChain 和 @EnableWebSecurity 注解来定义安全规则。

4.创建控制器

package com.me.mengyu.love.controller;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class HomeController {

    @GetMapping("/")

    public String index() {

        return "index"; // 返回首页视图

    }

    @GetMapping("/home")

    public String home() {

        return "home"; // 返回用户主页视图

    }

    @GetMapping("/login")

    public String login() {

        return "login"; // 返回登录视图

    }

}

5.创建视图

        src/main/resources/templates/ 下创建相应的 HTML 视图文件(例如,index.htmlhome.htmllogin.html)。

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Index Page</title>

</head>

<body>

    <h1>Welcome to the OIDC Demo!</h1>

    <a href="/login">Login</a>

</body>

</html>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Login Page</title>

</head>

<body>

    <h1>Login</h1>

    <a href="/oauth2/authorization/my-client">Login with OIDC</a>

    <div th:if="${param.error}">

        <p>Login failed. Please try again.</p>

    </div>

</body>

</html>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Home Page</title>

</head>

<body>

    <h1>Welcome Home!</h1>

    <p>You are successfully logged in.</p>

    <a href="/">Logout</a>

</body>

</html>

6.运行应用程序

         可以通过访问 http://localhost:8080 来访问应用程序,进行 OIDC 登录测试。

7.处理用户信息

         要获取用户信息,您可以在控制器中注入 OAuth2AuthenticationToken,并提取用户详细信息:

package com.me.mengyu.love.controller;

import org.springframework.security.core.annotation.AuthenticationPrincipal;

import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class UserController {

    @GetMapping("/user")

    public String user(@AuthenticationPrincipal OAuth2AuthenticationToken authentication) {

        return "User: " + authentication.getPrincipal().getAttributes().toString();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任风雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值