簡體   English   中英

如何使用 Spring 模擬身份驗證和授權

[英]How to mock authentication and authorization with Spring Security

我有一個 spring-boot REST API 應用程序。 REST 端點受 spring-security 保護。

這是spring-security的配置:

protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .exceptionHandling().authenticationEntryPoint(new CustomForbiddenErrorHandler())
            .and()

            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            .antMatchers("/api/**").authenticated() // HTTP 403 if the request is not authenticated
            .antMatchers("/**").permitAll();
}

它工作正常。 如果我制作Z65E800B5C6800AAD896F888888B2A62AFCZ,沒有Z293C9EA246FF9985DC62A62A62A62A5C62A62A5899869999999999999999999999999F31C749F6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF6EF65B6EF65B095B05B05B05B0.REND COR NONG CALCAFC

如果沒有按順序顯示,我可以強制 spring 以某種方式添加自我身份驗證令牌,這樣我就可以在沒有自己的訪問管理系統的情況下進行 REST 調用嗎? 稍后會安裝它。

我不是在問如何編寫 JUnit 測試。 我要問的是如何動態生成模擬身份驗證令牌並將其添加到請求中(如果它不存在)。

您可以覆蓋現有的身份驗證過濾器,或創建新的自定義過濾器,以檢查請求是否包含不記名令牌。 根據結果,您可以按原樣處理請求,也可以使用自定義身份驗證 object 擴充請求。

查看OAuth2AuthenticationProcessingFilter ,這會從傳入請求中提取 OAuth2 令牌並使用它來填充 Spring 安全上下文。 您可以覆蓋其行為或創建一個新過濾器,該過濾器使用您的模擬身份驗證 object 填充安全上下文。

這是一個示例代碼,可幫助您入門:

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    boolean debug = logger.isDebugEnabled();
    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;

    try {
        Authentication authentication = this.tokenExtractor.extract(request);
        if (Objects.isNull(authentication)) {
            final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("username", "password");

            authenticationToken.setDetails(Collections.singletonMap("user_uuid", userUuid.toString()));

            final OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(null, authenticationToken);

            // You can either ask your authenticatoin manager to authenticate these credentials or directly publish auth success event with your mock auth object.

            this.eventPublisher.publishAuthenticationSuccess(oAuth2Authentication);
            SecurityContextHolder.getContext().setAuthentication(oAuth2Authentication);

        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken)authentication;
                needsDetails.setDetails(this.authenticationDetailsSource.buildDetails(request));
            }

            Authentication authResult = this.authenticationManager.authenticate(authentication);
            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            this.eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }

暫無
暫無

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

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