SpringBoot OAuth2自定义登陆/授权页

news2024/9/21 4:20:27

      背景

        5 月份的时候,我实践并整理了一篇博客:SpringBoot搭建OAuth2,该博客完成之后,很长一段时间里我都有种意犹未尽的感觉。诚然,我把OAuth2搭起来了,各种场景的用例也跑通了,甚至源码也看了,但我还是觉得自己的了解不够透彻。

        我们公司也使用OAuth认证服务,企业微服务中是怎么应用OAuth2的?我搭建的认证服务离公司的成熟框架还有多远?这是我在学习OAuth时一直想弄明白的问题。幸运的是,在经历重重困难后,我终于把它们都梳理清楚了。我的学习成果会在本次及后面的几篇博客中体现。今天,咱们先迈出第一步:OAuth自定义登陆和授权页面

        在企业内使用OAuth2时,研发人员最先做的就是重新设计登陆和授权页面了。诚然,OAuth里有默认的登陆和授权页面,但那是最原生的页面,既不美观,也和其他服务的页面风格不搭,所以基本没有人会用原生页面。在这里,我就先实践下怎么自定义登陆和授权页面吧。

      代码实践

        纵观网上的各种资料,我发现OAuth2自定义登陆页面有两种方式,一种是利用thymeleaf的方式,通过Controller跳转到html,另一种是直接跳转到html的方式。这两种方式我都会演示下。为了方便测试,下文中的实践均采用InMemory的配置方式。另外建议下,在实践时不要在服务上加上下文根(如http://127.0.0.1:8080/leixi/oauth/…里的/leixi),非常影响测试。

      一、通过thymeleaf跳转自定义页面

        1、首先,引入Jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!--  OAuth2.0依赖  -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        <!--页面要用到的框架-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        2、配置@Config

package com.leixi.auth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

/**
 *
 * @author leixiyueqi
 * @since 2024/9/4 22:00
 */
// security 安全相关的配置类
@Configuration
@Order(1)
public class SecurityMemoryConfiguration extends WebSecurityConfigurerAdapter {

    private static final String loginUrl = "/login";
    private static final String loginPage = "/authcation/login";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // http security 要拦截的url,这里这拦截,oauth2相关和登录登录相关的url,其他的交给资源服务处理
                .requestMatchers()
                .antMatchers( "/oauth/**",loginUrl,loginPage)
                .and()
                .authorizeRequests()
                // 自定义页面或处理url是,如果不配置全局允许,浏览器会提示服务器将页面转发多次
                .antMatchers(loginUrl,loginPage)
                .permitAll()
                .anyRequest()
                .authenticated();

        // 表单登录
        http.formLogin()
                // 登录页面
                .loginPage(loginPage)
                // 登录处理url
                .loginProcessingUrl(loginUrl);
        http.httpBasic().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication()   //直接创建一个静态用户
                .passwordEncoder(encoder)
                .withUser("leixi").password(encoder.encode("123456")).roles("USER");
    }


    @Bean   //这里需要将AuthenticationManager注册为Bean,在OAuth配置中使用
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }
}


package com.leixi.auth2.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

import javax.annotation.Resource;

/**
 * 基于内存的设置方式,所有的客户端,用户信息都在内存里
 *
 * @author leixiyueqi
 * @since 2024/9/4 22:00
 */
@EnableAuthorizationServer   //开启验证服务器
@Configuration
public class OAuth2MemoryConfiguration extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager manager;

    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Resource
    UserDetailsService service;

    /**
     * 这个方法是对客户端进行配置,
     * 之后这些指定的客户端就可以按照下面指定的方式进行验证
     * @param clients 客户端配置工具
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()   //这里我们直接硬编码创建,当然也可以像Security那样自定义或是使用JDBC从数据库读取
                .withClient("client")   //客户端名称,随便起就行
                .secret(encoder.encode("654321"))      //只与客户端分享的secret,随便写,但是注意要加密
                .autoApprove(false)    //自动审批,这里关闭,要的就是一会体验那种感觉
                .scopes("book", "user", "borrow")     //授权范围,这里我们使用全部all
                .autoApprove(false)
                .redirectUris("http://127.0.0.1:19210/leixi/demo")
                .authorizedGrantTypes("client_credentials", "password", "implicit", "authorization_code", "refresh_token");
        //授权模式,一共支持5种,除了之前我们介绍的四种之外,还有一个刷新Token的模式
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .passwordEncoder(encoder)    //编码器设定为BCryptPasswordEncoder
                .allowFormAuthenticationForClients()  //允许客户端使用表单验证,一会我们POST请求中会携带表单信息
                .checkTokenAccess("permitAll()");   //允许所有的Token查询请求,没有这一行,check_token就会报401

    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .userDetailsService(service)
                .authenticationManager(manager);
        //这个是用于在登陆成功后,将授权请求Action替换自定义的Action,以便进入自定义授权页面
        endpoints.pathMapping("/oauth/confirm_access","/custom/confirm_access");
    }
}



        3、编写跳转的Controller

package com.leixi.auth2.controller;

import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 *
 * @author leixiyueqi
 * @since 2024/9/4 22:00
 */
@Controller
@SessionAttributes("authorizationRequest")
public class BootGrantController {

    @RequestMapping("/authcation/login")
    public String loginPage(Model model, HttpServletRequest request) {
        //跳转到登陆页
        return "login-page";
    }

    @RequestMapping("/custom/confirm_access")
    public String getAccessConfirmation(Map<String, Object> param, HttpServletRequest request, Model model) throws Exception {
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) param.get("authorizationRequest");
        if (authorizationRequest==null){
            return "redirect:"+"login-page";
        }
        String clientId = authorizationRequest.getClientId();
        model.addAttribute("scopes",authorizationRequest.getScope());
        Map<String, Object> client = new HashMap<>();
        client.put("clientId",clientId);
        client.put("name","leixi");  // 这里应该是用户名
        model.addAttribute("client",client);
        return "oauth-check";
    }
}

        4、在resources/static文件夹下编写登陆页login-page.html,授权页oauth-check.html。注意一定要在resources/static下,且文件取名要和Controller里配置的一样。

<!--这是登陆页login-page.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<!--spring security 默认处理用户名密码就是/login,可以自定义,需要loginProcessingUrl()-->
<p style="color: red" th:if="${param.error}">用户名或密码错误</p>
<form th:action="'/login'" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td>
                <label><input type="text" name="username"/></label>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <label><input type="password" name="password"/></label>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>


<!--这是授权页oauth-check.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>确认授权页面</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <link rel="stylesheet" href="//i.gtimg.cn/vipstyle/frozenui/2.0.0/css/frozen.css"/>

    <style>
        .block{
            position: relative;
        }
        .ui-notice{
            position: relative;
            padding:20px 15px;
            box-sizing: border-box;
        }
        .ui-notice p{
            color:#333;
            font-weight: 600;
        }
        .ui-btn-primary{
            background-color: #02cd93;
            border-color:#02cd93;;
        }
        .ui-notice-btn{
            padding:50px 0px 15px;
        }
    </style>
</head>
<body>
<div class="block">
    <section class="ui-notice">
        <i class="icon icon-notice"></i>
        <p>是否授权:<span th:text="${session.authorizationRequest.clientId}">clientId</span></p>
        <div class="ui-notice-btn">
            <form id='confirmationForm' name='confirmationForm' th:action="'/oauth/authorize'" method='post'>
                <input name='user_oauth_approval' value='true' type='hidden'/>
                <!--写好授权访问领域-->
                <div th:each="item:${scopes}">
                    <input type="radio" th:name="'scope.'+${item}" value="true" hidden="hidden" checked="checked"/>
                </div>
                <input class="ui-btn-primary ui-btn-lg ui-btn-primary" name='authorize' value='授权' type='submit'/>
            </form>
        </div>
    </section>
</div>
</body>
</html>

        5、yml中添加配置

spring:
  # 模板引擎配置
  thymeleaf:
    prefix: classpath:/static/
    suffix: .html
    cache: false
  mvc:
    throw-exception-if-no-handler-found: true

        6、启动项目,输入地址 

                http://127.0.0.1:19200/oauth/authorize?client_id=client&response_type=code

        进行测试,效果如下:

        自定义登陆页面:

        

        自定义授权页面:

        

        授权成功,可以得到code

        

        这么一看,怎么页面还没有原生的漂亮?

        嘞个……我只是为了演示怎么设置自定义页面,用的是最精减的代码,没有做相关样式的设计,所以丑点是正常的。

      二、直接跳转登陆页

        第二种实现方法是参考公司OAuth Server中的实现,直接在Config里配置登陆页,而不再通过Controller和thymeleaf实现页面的跳转,相比于第一种方式,它的实现更加简单,缺点是我目前还没有找到怎么跳转到自定义授权页面的方法,但是一般在企业应用中,都会直接配置自动授权,很少有需要进入授权页面的,这个缺陷并不重要。下面是相比于5月份的那个版本的代码变动。

        1、修改SecurityMemoryConfiguration中的configure(HttpSecurity http),如下

    private static final String loginUrl = "/loginpage.html";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // http security 要拦截的url,这里这拦截,oauth2相关和登录登录相关的url,其他的交给资源服务处理
                .authorizeRequests()
                .antMatchers( "/oauth/**","/**/*.css", "/**/*.ico", "/**/*.png", "/**/*.jpg", "/**/*.svg", "/login",
                        "/**/*.js", "/**/*.map",loginUrl, "/base-grant.html")
                .permitAll()
                .anyRequest()
                .authenticated();
        // post请求要设置允许跨域,然后会报401
        http.csrf().ignoringAntMatchers("/login", "/logout", "/unlock/apply");

        // 表单登录
        http.formLogin()
                // 登录页面
                .loginPage(loginUrl)
                // 登录处理url
                .loginProcessingUrl("/login");
        http.httpBasic();
    }

        2、在/resources/static下添加loginpage.html,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>登录</title>
</head>
<body>
<h2>自定义登录页面</h2>
<!--spring security 默认处理用户名密码就是/login,可以自定义,需要loginProcessingUrl()-->
<p style="color: red" th:if="${param.error}">用户名或密码错误</p>
<form th:action="'/login'" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td>
                <label><input type="text" name="username"/></label>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <label><input type="password" name="password"/></label>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

        3、如果不需要手动授权,可以修改OAuth2MemoryConfiguration中的client配置,这样就会自动略过授权页面了。

        4、功能测试,依然是那个链接,那个密码,结果如下:

        

        

      后记与致谢

        之前参考的资料里,大多都只写了thymeleaf的实现方法,这里之所以把两种方法都写出来,主要原因是第二种实现方法很简洁,被惊艳到了,另一个原因是我在实践的过程中,因为这两种方法吃了太多的亏。我总是以一种质疑的方式去模仿,为什么网上的方法和公司的实现不一样?非要按网上的来吗?公司好像没引入依赖包啊,这部分可以看网上,那部分公司写的很精练……结果抄来抄去,把两种实现方案抄混了,都没能达到效果。这是一种很低效的学习方法,无论学习什么技术,在有参考的情况下,至少先沿着前人的路走通一条,再去想着优化,革新,这是我得到的最宝贵的教训。

        在实践这篇博客的过程中,雷袭也参考学习了很多大佬的博客,以下这篇:Spring boot+Security OAuth2 自定义登录和授权页面是对我启发最大,最有帮助的,博主还在文中贴心的放上了源码链接,非常值得学习和尊重,拜谢大佬!

        最后再提一嘴,在网上搜索相关资料时,发现很多资料都很老,有的都是17,18年的老博客了。这也让我在研究这OAuth时有着浓浓的挫败感,毕竟技术是日新月异,不断迭代的,最新的博客很少,说明世面上肯定有很多新的技术取代旧技术了。侧面也说明了,我现在研究的东西,在七八年之前,已经有人成体系的研究出方案了,想想都感觉好落伍啊!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2119158.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

HTTP请求⽅法

HTTP请求⽅法 1. GET &#xff1a;申请获取资源&#xff0c;不对服务器产⽣影响 2. POST &#xff1a; POST 请求通常⽤于发送数据&#xff0c;例如提交表单数据、上传⽂件等&#xff0c;会影响服务器&#xff0c;服务器可能动态创建新的资源或更新原有资源。 3. HEAD &#…

GPU 计算 CMPS224 2021 学习笔记 02

并行类型 &#xff08;1&#xff09;任务并行 &#xff08;2&#xff09;数据并行 CPU & GPU CPU和GPU拥有相互独立的内存空间&#xff0c;需要在两者之间相互传输数据。 &#xff08;1&#xff09;分配GPU内存 &#xff08;2&#xff09;将CPU上的数据复制到GPU上 &…

UE4_后期处理_后期处理材质四—场景物体描边

一、效果如下图&#xff1a; 二、分析&#xff1a; 回顾复习&#xff1a;在后期处理材质三中&#xff0c;我们通过计算开启自定义深度通道物体的像素点上下左右4个像素SceneTextureCustomDepth深度之和来判断物体的外部&#xff08;包含物体的边&#xff09;和内部&#xff0c…

【漏洞利用】2018年-2024年HVV 6000+个漏洞 POC 合集分享

此份poc 集成了Zabbix、用友、通达、Wordpress、Thinkcmf、Weblogic、Tomcat等 下载链接: 链接: https://pan.quark.cn/s/1cd7d8607b8a

Java小白一文讲清Java中集合相关的知识点(七)

LinkedHashSet LinkedHashSet是HashSet的子类 LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组双向链表 而在之前讲的HashSet中的链表是单向的哈&#xff0c;注意区分&#xff01; LinkedHashSet根据元素的hashcode值来决定元素的存储位置&#xff0c;同时使用链表…

从搜索热度上看Arcgis的衰退

Arcgis已被qgis快速赶上 google trends是一个google综合了每日的搜索情况的统计网站&#xff0c;可以追踪从2004年开始各个关键字的搜索热度。 我用arcgis和qgis作为对比&#xff0c;简单探索了arcgis和qgis的全球相关热度。 假设&#xff0c;搜索arcgis越高的区域&#xff…

机器学习 第8章 集成学习

目录 个体与集成BoostingBagging与随机森林Bagging随机森林 结合策略平均法投票法学习法 个体与集成 定义&#xff1a;集成学习&#xff0c;也叫多分类器系统、基于委员会的学习等&#xff0c;它是一种通过结合多个学习器来构建一个更强大的学习器的技术。如下图所示 在这里&a…

轨道交通系统详解,以及地铁如何精准停靠站台

ATC系统 全称“自动列车控制系统”&#xff0c;Automatic Train Control&#xff0c;ATC ATC是地铁运行的核心系统&#xff0c;它包括列车自动防护&#xff08;ATP&#xff09;、列车自动运行&#xff08;ATO&#xff09;和列车自动监控&#xff08;ATS&#xff09;三个子系统。…

嵌入式day41

哈希表 将要存储的数据的关键字和位置建立对应的关系&#xff0c;通过哈希函数&#xff08;散列函数&#xff09;将数据映射到存储的位置&#xff0c;方便快速查找 哈希冲突/哈希矛盾&#xff1a; key1 ! key2 f(key1) f(key2) 解决方法&#xff1a; 链地址法 算法 解决…

都2024年了还不明白Redis持久化?RDB文件、AOF文件、AOF重写

都2024年了&#xff0c;不会还有人不知道redis的RDB和Aof吧&#xff1f;不知道没关系&#xff0c;看完这篇文章我相信你就会有个大概的了解和认识了 1. Redis持久化 1.1 持久化概念 Redis本身是一个基于内存的数据库&#xff0c;它提供了RDB持久化、AOF持久化两种方式&#…

黑神话,XSKY 星飞全闪单卷性能突破310万

当下&#xff0c;云计算仍然是企业主要的基础架构&#xff0c;随着关键业务的逐步虚拟化和云化&#xff0c;对于块存储的性能要求也日益提高。企业对于低延迟、高稳定性的存储解决方案的需求日益迫切。为了满足这些日益增长的 IO 密集型应用场景&#xff0c;众多云服务提供商正…

大奖收割机!望繁信科技荣获年度技术创新和应用品牌奖

2023年8月14日&#xff0c;第七届GAIR全球人工智能与机器人大会在新加坡如期举行。 会上公布了「GAIR 2023 GPT Pioneer 5」榜单&#xff0c;望繁信科技凭借完全自主研发的流程智能平台&#xff0c;以及一系列在头部企业中的成功实践案例&#xff0c;与百度智能云、阿里云、知…

vector 容器基础操作及用法

目录 vector 容器基础操作及用法 一&#xff1a;定义及初始化 二&#xff1a;添加数据 三&#xff1a;删除数据 vector 容器基础操作及用法 CSTL是一个非常强大的容器库&#xff0c;其中 vector 是最为常用也较为方便的容器之一&#xff0c;下面主要介绍一下 vector 的一些…

学习threejs,创建立方体,并执行旋转动画

文章目录 一、前言二、代码示例三、总结 一、前言 本文基于threejs&#xff0c;实现立方体的创建&#xff0c;并加入立方体旋转动画 二、代码示例 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>l…

数据同步方式何来“高级”与“低级”之说?场景匹配才是真理!

导读&#xff1a;数据同步方式的重要性对于数据集成领域的兴从业者不言而喻&#xff0c;选择正确的数据同步方式能让数据同步工作的成果事半功倍。目市面上的数据同步工具很多&#xff0c;提供的数据同步方式也有多种&#xff0c;不同的数据同步方式有什么区别&#xff1f;如何…

免费SSL证书正在逐渐被淘汰,证书部署自动化的发展趋势即将到来!

目录 背景解决方案。1.使用自签证书&#xff08;浏览器报警、免费&#xff09;2.更换支持自签自续的CA机构&#xff08;免费&#xff09;3.付费选择CA机构 免费SSL证书正在逐渐被淘汰&#xff0c;证书部署自动化的发展趋势即将到来免费的SSL证书有以下弊端1.有效期短&#xff1…

Python的安装与配置并在本地盘符创建共享路径打造低成本私人云盘

文章目录 前言1.本地文件服务器搭建1.1.Python的安装和设置1.2.cpolar的安装和注册 2.本地文件服务器的发布2.1.Cpolar云端设置2.2.Cpolar本地设置 3.公网访问测试4.结语 前言 本文主要介绍如何在Windows系统电脑上使用python这样的简单程序语言&#xff0c;在自己的电脑上搭建…

Leetcode面试经典150题-98.验证搜索二叉树

解法都在代码里&#xff0c;不懂就留言或者私信 二叉树的递归套路&#xff0c;练练就习惯了 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this…

内联汇编 (28)

1 首先是基本的格式。 网上的截图&#xff1a; 命令换行使用 \n\t 这里的constraint 指的就是 寄存器。 r , m , 比较重要。 这里的输出的意思是 &#xff0c; 从汇编到 C语言。 输入指的是 从C语言到 汇编语言 这是个具体的例子 %1, %2,%3, 是指 从上往下算&#xff0c;…

【Canvas与电脑桌面】白褐橘三色立方桌面(1920*1080)

【成图】 【代码】 <!DOCTYPE html> <html lang"utf-8"> <meta http-equiv"Content-Type" content"text/html; charsetutf-8"/> <head><title>白褐橘三色立方桌面Draft1</title><style type"text/c…