SpringSecurity5-教程5-前后端分离系统OAuth2授权登录后渲染指定页面

在前后端不分离的系统中,SpringSecurity利用SavedRequestAwareAuthenticationSuccessHandler实现在用户授权登录后重定向回原页面。当使用REST请求时,前端需传递当前页面URL,自定义的AuthenticationSuccessHandler通过获取查询参数中的‘target’来实现页面重定向。提供了一个示例代码展示了如何处理这个过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前后端不分离的系统,无需特殊处理,例如访问页面A时未登录,在授权登录后,浏览器重定向到渲染A页面,

但是前后端分离架构下,服务端收到的时REST请求,并非页面, 因此默认情况下无法重定向到原页面。

前后端不分离的系统,Spring Security通过SavedRequestAwareAuthenticationSuccessHandler实现重定向原页面,因此可重写该Handler实现:

在调用REST请求时传入当前页面的URL,在Handler中获取后重定向该页面!

前端请求示例:

```

window.location = "http://localhost:8035/oauth2/login?target=http://localhost:8080/page1.html";

```

/oauth2/login是任意受保护资源的URI,因为都会被重定向到授权登录页面。

Handler示例:

        public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
            private RequestCache requestCache = new HttpSessionRequestCache();

            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                                Authentication authentication) throws ServletException, IOException {
                SavedRequest savedRequest = this.requestCache.getRequest(request, response);
                if (savedRequest == null) {
                    super.onAuthenticationSuccess(request, response, authentication);
                    return;
                }
                clearAuthenticationAttributes(request);
                String redirectUrl = savedRequest.getRedirectUrl();
                UriComponents uriComponents = UriComponentsBuilder.fromUriString(redirectUrl).build();
                MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
                String target = queryParams.getFirst("target");
                if (Strings.isNotBlank(target)) {
                    getRedirectStrategy().sendRedirect(request, response, target);
                    return;
                }
                getRedirectStrategy().sendRedirect(request, response, redirectUrl);
            }

            public void setRequestCache(RequestCache requestCache) {
                this.requestCache = requestCache;
            }

        }

Demo

demo下载

1. 解压前端nginx并启动

2. 本地启动后端Demo

3. 浏览器访问http://localhost:8080/page1.html

4. 页面跳转gitee登录

5. 登录完成后,页面渲染page1.html页面

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值