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

Java17 --- SpringSecurity之OAuth2

一、OAuth2

1.1、使用github以授权码方式

1.1.1、注册应用程序

 

 

1.1.2、测试代码

 pom依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: Ov23liQnQPka0x1qX6ZI
            client-secret: 278f3ad4ecdd8dad4b318d7bd8d33f2bb9428019
@Controller
public class IndexController {
    @GetMapping("/")
    public String index(Model model, @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User) {
        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userAttributes", oauth2User.getAttributes());
        return "index";
    }
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
  <title>Spring Security - OAuth 2.0 Login</title>
  <meta charset="utf-8" />
</head>
<body>
<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()">
  <div style="float:left">
    <span style="font-weight:bold">User: </span><span sec:authentication="name"></span>
  </div>
  <div style="float:none">&nbsp;</div>
  <div style="float:right">
    <form action="#" th:action="@{/logout}" method="post">
      <input type="submit" value="Logout" />
    </form>
  </div>
</div>
<h1>OAuth 2.0 Login with Spring Security</h1>
<div>
  You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>
  via the OAuth 2.0 Client <span style="font-weight:bold" th:text="${clientName}"></span>
</div>
<div>&nbsp;</div>
<div>
  <span style="font-weight:bold">User Attributes:</span>
  <ul>
    <li th:each="userAttribute : ${userAttributes}">
      <span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span>
    </li>
  </ul>
</div>
</body>
</html>

 

 

 

相关文章:

  • c、c#、c++嵌入式比较?
  • electron录制工具-视频保存、编辑页面
  • 【Java04】引用变量数组初始化的内存机制
  • STL-常用容器
  • 10.Docker Compose容器编排
  • 学单片机前先学什么?
  • 树莓派4B_OpenCv学习笔记10:调整视频帧大小
  • Ubuntu 22.04 解决 firefox 中文界面乱码
  • 活动集锦 | 英码科技积极参与行业盛会,AI赋能城市数字化转型
  • Optional详解和常用API
  • 对LitJson开源插件的自定义尝试
  • EasyExcel文件导出,出现有文件但没有数据的问题
  • 揭开 Docker 容器的神秘面纱:深入理解容器原理
  • 【网络安全】【深度学习】【入侵检测】SDN模拟网络入侵攻击并检测,实时检测,深度学习【二】
  • JVM常用概念之线程本地分配缓冲区(ThreadLocal Allocation Buffer,TLAB)
  • 【双系统 安装ADB】
  • Oracle中select取值后的字符串处理
  • 跨服务器迁移 Redis 数据
  • Web前端开发12章:深入探索与实战解析
  • 在不使用js在情况下只用css实现瀑布流效果
  • 新加坡国会选举投票抽样结果公布,执政党已获超半数议席
  • 成为中国骑手“孵化器”,环球马术冠军赛是最好的历练舞台
  • 徐丹任武汉大学药学院院长:研究领域在国际上处领跑地位
  • 美法官裁定特朗普援引战时法律驱逐黑帮违法,系首次永久性驳回
  • 挑大梁!一季度北上广等7省份进出口占外贸总值四分之三
  • 韩国代总统、国务总理韩德洙宣布辞职,将择期宣布参选总统