代码之家  ›  专栏  ›  技术社区  ›  Jordi

Spring boot测试:用户保护的安全控制器正在测试中

  •  1
  • Jordi  · 技术社区  · 7 年前

    这里是我的控制器方法:

    @PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")
    public void ingestAudits() {
        // Do something
    }
    

    正如你所见,它是用 @PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")

    下面是我的测试代码:

    @WithMockUser(username=EspaiDocConstants.BO_COMPONENT_APP)
    @Test
    public void test() throws IOException, NoSuchAlgorithmException {
        this.controller.ingestAudits();
    }
    

    然而,我得到了一个例外信息:

    这是我的最爱。测试:91»访问被拒绝访问被拒绝

    编辑

    为了填充principal,我使用了一个自定义过滤器:

    public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
        @Override
        protected void doFilterInternal(
            HttpServletRequest req,
            HttpServletResponse res,
            FilterChain chain
        ) throws IOException, ServletException {
            String user = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                .getBody().getSubject();
    
            SecurityContextHolder.getContext()
                .setAuthentication(
                    new UsernamePasswordAuthenticationToken(user, null)
                );
    
            chain.doFilter(req, res);
        }
    }
    

    所以 principal 是一个 String 包含用户。

    除此之外,我现在无法更改此代码,我想知道如何提供 "String user" 委托人使用 @WithMockUser .

    1 回复  |  直到 7 年前
        1
  •  0
  •   Evgeniy Strepetov    7 年前

    您应该只验证用户名,而不是使用“==”验证整个主体对象。

    @预先授权(“委托人”)。 用户名 =='“+EspaiDocConstants.BO_组件_应用程序+ "'")

    推荐文章