前后端不分离的系统,无需特殊处理,例如访问页面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
1. 解压前端nginx并启动
2. 本地启动后端Demo
3. 浏览器访问http://localhost:8080/page1.html
4. 页面跳转gitee登录
5. 登录完成后,页面渲染page1.html页面