gpt4 book ai didi

java - 如何在 mvcmock 单元测试中注入(inject)身份验证

转载 作者:行者123 更新时间:2023-12-02 03:25:39 24 4
gpt4 key购买 nike

概述

我有一个带有注入(inject)身份验证的 REST 服务,我想使用 mockmvc 为其创建一个单元测试。我的 RestController 类如下:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.blss.security.securityCommon.entities.SecureOperatorDetails;
import com.blss.security.securityGateway.providers.AccAuthenticationProvider;

import lombok.Data;

@RestController
@RequestMapping("/gateway")
public class AuthenticationDetailsRestController {

@RequestMapping(value = "/userdetails", method = RequestMethod.GET)
public UserDetailsResource currentUserName(Authentication authentication) {

ArrayList<String> rolesList = new ArrayList<>();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
authorities
.forEach(a -> {
if (!a.getAuthority().startsWith(
AccAuthenticationProvider.CAD_TOKEN_AUTHORITY_PREFIX)) {
rolesList.add(a.getAuthority());
}
});

SecureOperatorDetails operator = ((SecureOperatorDetails) authentication.getDetails());

return new UserDetailsResource(
authentication.getName(),
operator.getOperator().getName(),
operator.getOperator().getPermittedRetailerIds(),
operator.getOperator().getStores(),
operator.getOperator().getRetailerId(),
operator.getDefaultStoreId(),
operator.getDeviceId(),
rolesList);
}

@Data
static class UserDetailsResource {
private final String username;
private final String name;
private final Set<String> retailerIds;
private final Set<String> stores;
private final String retailerId;
private final String storeId;
private final String deviceId;
private final ArrayList<String> roles;
}
}

问题

我不知道如何模拟身份验证并将其注入(inject)到我的测试类中,以避免 401 http 异常完全身份验证需要访问此资源

Now I would be grateful if anyone can help me solve this problem

最佳答案

您可以使用org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers配置身份验证模拟

然后你应该按如下方式初始化它:

private MockMvc mockMvc;

@Override
protected void before() {
this.mockMvc = webAppContextSetup(context).apply(SecurityMockMvcConfigurers.springSecurity()).build();
}

关于java - 如何在 mvcmock 单元测试中注入(inject)身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950992/

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