簡體   English   中英

Java Spring 安全性。 記錄的用戶信息

[英]Java Spring Security. Logged user information

我想改進我的 REST API 待辦事項應用程序。 我想添加到安全配置中,當有人登錄時,我想將他重定向到由 Utils userId 生成的端點。 我想達到這樣的目標:

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

你可以通過添加以下幾件事來做到這一點:

在 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();
    }


}

希望這會幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM