在 Spring Boot 中根据登录用户更改应用程序的 URL

Posted

技术标签:

【中文标题】在 Spring Boot 中根据登录用户更改应用程序的 URL【英文标题】:Change URL of application according to logged in user in Spring boot 【发布时间】:2020-03-13 15:14:26 【问题描述】:

我从事 Spring Boot 项目已有一段时间了。我正在使用 localhost:8080/XYZapp/login 之类的本地 url 访问我的应用程序登录,然后在成功登录后我的 url 更改为 localhost:8080/XYZapp/authenticated(这是我的仪表板)。

所有这些工作正常,但现在我希望我的 URL 能够动态更改。像localhost:8080/XYZapp/abcCompany/authenticated这样的登录用户。此 abcCompany 应根据登录用户每次更改。

我在一些参考资料和 SO 上搜索了它,但没有找到太多运气。

【问题讨论】:

你可能是成功认证的abcCompany,获取值并重定向到URL。如需更多信息,您可以添加相关代码 @PatelRomil 你能详细说明一下,它将如何更改网址。我也可以添加我当前想要实现的身份验证代码。 @high_on_java 实现 AuthenticationSuccessHandler 并覆盖 onAuthenticationSuccess() 方法,您可以在其中重定向到任何 URL。并在你的 spring 安全配置中配置你的处理程序给定.formLogin().successHandler(yourHandler) 【参考方案1】:

您需要做几件事。

第一个在cmets中已经提到过,就是使用AuthenticationSuccessHandler

@Component
public TenantAuthenticationSuccessHandler implements AuthenticationSuccessHandler 
    void onAuthenticationSuccess(HttpServletRequest request, 
        HttpServletResponse response, Authentication authentication) 

        if (authentication.getPrincipal() instanceof MyUser) 
            MyUser user = (MyUser) authentication.getPrincipal();
            String uri = "/XYZapp/" + user.getTenantName() + "/authenticated";
            AuthenticationSuccessHandler handler =
                new SimpleUrlAuthenticationSuccessHandler(uri);
            handler.onAuthenticationSuccess(handler);
        

        // throw exception
    

然后您可以将其连接到您的 DSL:

@Autowire
AuthenticationSuccessHandler tenantAuthenticationSuccessHandler;

// ...

http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .successHandler(this.tenantAuthenticationSuccessHandler);

当然,您可以考虑缓存 SimpleUrlAuthenticationSuccessHandler 实例,这样您就不会为每次登录创建一个。

其次,您可能需要能够根据被查找的用户知道租户的名称(例如 abcCompany)。

因此,您可能需要a custom UserDetailsService,以便您可以从数据存储中检索这些额外信息:

public class MyUser 
    String tenantName;

    // ...


// ...

@Component
public class MyUserUserDetailsService implements UserDetailsService 
    public UserDetails findUserByUsername(String username) 
        // query some backing store, Spring Data repository, etc.

        return myUser;
    

    private static class MyUserUserDetails extends MyUser implements UserDetails 
        // ...
    

【讨论】:

以上是关于在 Spring Boot 中根据登录用户更改应用程序的 URL的主要内容,如果未能解决你的问题,请参考以下文章

我想根据登录用户更改主页菜单。我如何在 Spring MVC 中做到这一点?

无需用户登录即可保护 Spring Boot 应用程序

如何使用 Keycloak 在 Spring Boot 中获取当前登录用户?

Spring Boot&& Spring Cloud系列单点登录SSO

如何让我的 Spring Boot 应用程序使用给定的用户名和密码登录到 keycloak?

如何在运行时更改日志级别而不重新启动 Spring Boot 应用程序