如何在 Spring Security 中的 SSO 登录后重定向我的上一页?
Posted
技术标签:
【中文标题】如何在 Spring Security 中的 SSO 登录后重定向我的上一页?【英文标题】:How to redirect my previous page after SSO Login in spring security? 【发布时间】:2020-07-27 02:29:57 【问题描述】:Spring Security 中 SSO 登录后如何重定向我的上一页
我使用 set userReferer as true ,
但无法实现。请推荐一些示例代码或网站。
我们正在使用 IDP 的 Spring 安全性
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler
implements AuthenticationSuccessHandler
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public LoginSuccessHandler()
super();
setUseReferer(true);
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException
/// some code
//set our response to OK status
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
String targetUrl = determineTargetUrl(authentication);
httpServletResponse.sendRedirect(targetUrl);
【问题讨论】:
【参考方案1】:一旦用户在 IDP(身份提供者)端获得身份验证,SP(服务提供者)就会收到来自 IDP 的断言或响应。该响应将在 SP 端得到验证。响应验证后,将调用此类 OAuthUserLoginSuccessHandler
,您可以在其中从 IDP 提供的响应中提取信息并按照以下代码进行重定向。
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
public class OAuthUserLoginSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler
public OAuthUserLoginSuccessHandler()
@Override
public void onAuthenticationSuccess(final HttpServletRequest request,
final HttpServletResponse response, final Authentication authentication)
throws IOException, ServletException
if (authentication.getPrincipal() instanceof UserDetails
|| authentication.getDetails() instanceof UserDetails)
UserDetails details;
if (authentication.getPrincipal() instanceof UserDetails)
details = (UserDetails) authentication.getPrincipal();
else
details = (UserDetails) authentication.getDetails();
String username = details.getUsername();
// get user info from datastore using username
// some code
String redirectUri; // get target uri either from relay state or from datastore
if (null != redirectUri)
response.sendRedirect(redirectUri);
return;
super.onAuthenticationSuccess(request, response, authentication);
【讨论】:
请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。以上是关于如何在 Spring Security 中的 SSO 登录后重定向我的上一页?的主要内容,如果未能解决你的问题,请参考以下文章
Spring Security 之自定义UserDetails
在进行跨域请求时,如何使用 SockJS 和 STOMP 添加 Spring Security JSESSIONID?
Spring security 4.x 往 5.x 升级的坑 (OAuth2)