【问题标题】:Java Spring Security. Logged user informationJava 弹簧安全。记录的用户信息
【发布时间】:2020-07-07 08:09:49
【问题描述】:

我想改进我的 REST API 待办事项应用程序。我想添加到安全配置中,当有人登录时,我想将他重定向到由 Utils userId 生成的端点。我想实现这样的目标:

            .formLogin().defaultSuccessUrl("/users/(logged in our session userId)").permitAll()

【问题讨论】:

    标签: java spring spring-boot rest spring-security


    【解决方案1】:

    你可以通过添加这几件事来做到这一点:

    在 WebSecurityConfigurerAdapter 的配置方法中添加这一行:

    .formLogin().successHandler(mySuccessHandler())...
    

    添加一个bean定义

    @Bean
    public AuthenticationSuccessHandler mySuccessHandler(){
        return new MyCustomAuthenticationSuccessHandler();
    }
    

    接下来您需要创建实现 AuthenticationSuccessHandler 的 MyCustomAuthenticationSuccessHandler。

    public class MyCustomAuthenticationSuccessHandler
      implements AuthenticationSuccessHandler {
    
        protected Log logger = LogFactory.getLog(this.getClass());
    
        private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, 
          HttpServletResponse response, Authentication authentication)
          throws IOException {
    
            handle(request, response, authentication);
        }
    
        protected void handle(
            HttpServletRequest request,
            HttpServletResponse response, 
            Authentication authentication
        ) throws IOException {
    
            String targetUrl = determineYourTargetUrl(request);
    
            if (response.isCommitted()) {
                logger.debug(
                    "Response has already been committed. Unable to redirect to "
                            + targetUrl);
                return;
            }
    
            redirectStrategy.sendRedirect(request, response, targetUrl);
        }
    
        protected String determineYourTargetUrl(HttpServletRequest request) {
            return "users/" + request.getSession().getId();
        }
    
    
    }
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2020-08-26
      • 2023-01-03
      • 2012-06-15
      相关资源
      最近更新 更多