当前位置: 首页 > news >正文

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();

    }

}

相关文章:

  • 【Linux网络】详解TCP协议(3)
  • GitLab CI/CD脚本入门
  • JAVA工具类——Collections
  • AI学习指南深度学习篇-丢弃法Python实践
  • FTP访问方式详解
  • 【JVM】JVM执行流程和内存区域划分
  • 04_OpenCV图片缩放
  • element-plus中el-table固定列fixed失效问题
  • 智慧环保大数据平台建设方案
  • ASP.NET Core8.0学习笔记(十九)——EF Core DbSet
  • 论文阅读 | HiDDeN网络架构
  • 一次 Spring 扫描 @Component 注解修饰的类坑
  • 什么是数据挖掘?初学者指南
  • 基于python+django+vue的电影数据分析及可视化系统
  • 瓶子类型检测系统源码分享
  • 【347天】每日项目总结系列085(2018.01.18)
  • 【Amaple教程】5. 插件
  • 0x05 Python数据分析,Anaconda八斩刀
  • Android Studio:GIT提交项目到远程仓库
  • Android 架构优化~MVP 架构改造
  • canvas 高仿 Apple Watch 表盘
  • flask接收请求并推入栈
  • isset在php5.6-和php7.0+的一些差异
  • JavaScript/HTML5图表开发工具JavaScript Charts v3.19.6发布【附下载】
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • leetcode98. Validate Binary Search Tree
  • PhantomJS 安装
  • React系列之 Redux 架构模式
  • Redis 懒删除(lazy free)简史
  • uni-app项目数字滚动
  • Web标准制定过程
  • 初识 beanstalkd
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 前嗅ForeSpider采集配置界面介绍
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • 进程与线程(三)——进程/线程间通信
  • ​Benvista PhotoZoom Pro 9.0.4新功能介绍
  • ​MPV,汽车产品里一个特殊品类的进化过程
  • ​必胜客礼品卡回收多少钱,回收平台哪家好
  • #APPINVENTOR学习记录
  • #pragma预处理命令
  • #大学#套接字
  • (160)时序收敛--->(10)时序收敛十
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (二)Optional
  • (二)十分简易快速 自己训练样本 opencv级联lbp分类器 车牌识别
  • (附源码)springboot宠物医疗服务网站 毕业设计688413
  • (七)glDrawArry绘制
  • (四)c52学习之旅-流水LED灯
  • (一)、软硬件全开源智能手表,与手机互联,标配多表盘,功能丰富(ZSWatch-Zephyr)
  • (原創) 如何將struct塞進vector? (C/C++) (STL)
  • (转)Spring4.2.5+Hibernate4.3.11+Struts1.3.8集成方案一
  • (转)编辑寄语:因为爱心,所以美丽
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .NET C# 使用 SetWindowsHookEx 监听鼠标或键盘消息以及此方法的坑