gpt4 book ai didi

spring-security - 在 Spring MVC 单元测试中模拟匿名认证

转载 作者:行者123 更新时间:2023-12-01 11:29:13 24 4
gpt4 key购买 nike

我正在尝试为 guest 用户帐户编写单元测试。被测代码通过调用此方法来检查 guest ,该方法在单元测试中为 guest 帐户返回 null。

/**
* Determines if the user is a guest account.
*
* @return True if the account is guest account, false otherwise.
*/
public boolean isGuest() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
if (auth instanceof AnonymousAuthenticationToken) {
return true;
} else {
return false;
}
} else {
return false;
}
}

在服务器 Tomcat 容器中,匿名用户可以返回 AnonymousAuthenticationToken 实例。因为容器环境和单元测试环境共享相同的安全配置类,所以假设安全配置可能是正确的。

下面的测试代码也适用于 MockUser 所以我也认为安全测试配置可能没问题:

@Test
@WithMockUser(username="Test.Customer.1@mailinator.com", roles = {"ADMIN"})
public void testCheckoutPage() throws Exception{
logger.entry();
String targetView = OrderViews.convertViewReference(getPageDirectory(), OrderViews.CHECKOUT_LOGIN_PAGE, false);
String targetUrl = "/checkout";

Order order = OrderBuilder.buildSampleGuestOrder(OrderStatus.NEW, 5);
prepareMocks(order);
Map<String, Object> sessionAttrs = new HashMap<>();
sessionAttrs.put(OrderConstants.OPEN_ORDER_ID_ATTRIBUTE, order.getId());

this.mockMvc.perform(get(targetUrl).sessionAttrs(sessionAttrs))
.andExpect(status().isOk())
.andExpect(view().name(targetView))
.andExpect(model().attribute("order", order))
.andExpect(model().attributeExists("loginForm"));


this.mockMvc.perform(MockMvcRequestBuilders.post(targetUrl))
.andExpect(status().isMethodNotAllowed());

logger.exit();
}

有谁知道如何在单元测试中模拟匿名身份验证 token ?

最佳答案

在 Spring Security 4.1(尚未正式发布)中,我们引入了对 @WithAnonymousUser 的支持.

@WithAnonymousUser 支持是使用 @WithSecurityContext 构建的.这意味着您可以轻松地将支持添加到 4.0.x 中的代码库,直到 4.1.x 发布。要使其正常工作,您需要将以下类复制到您的测试源文件夹中:

package org.springframework.security.test.context.support;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithAnonymousUserSecurityContextFactory.class)
public @interface WithAnonymousUser {}
package org.springframework.security.test.context.support;

import java.util.List;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

final class WithAnonymousUserSecurityContextFactory implements
WithSecurityContextFactory<WithAnonymousUser> {

public SecurityContext createSecurityContext(WithAnonymousUser withUser) {
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
Authentication authentication = new AnonymousAuthenticationToken("key", "anonymous", authorities);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}

然后您可以使用以下命令以匿名用户身份运行:

@Test
@WithAnonymousUser
public void testAnonymous() throws Exception {
// ...
}

注意:重要的是要注意,就像您需要为 @WithMockUser 做的一样,您需要确保使用 MockMvc 设置 应用(springSecurity())作为outlined in the reference .

关于spring-security - 在 Spring MVC 单元测试中模拟匿名认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com