JHipster:测试微服务时接收401未经授权

问题描述 投票:0回答:1

我用Jhipster生成了简单的微服务应用程序,我编写了像hello world这样的简单控制器,当我尝试通过测试方法进行测试时,总是会出现未经授权的错误,并且测试失败。

控制器:

@RestController
@RequestMapping("/api")
public class TestController{
  @GetMapping("/test/{Id}")
  public String TestGetData(@PathVariable int Id) {
      return "Here is your data!";
  }
}

测试类:

@SpringBootTest(classes = HerstellerController.class)
@AutoConfigureMockMvc
public class TestIT {

@Autowired
private MockMvc mockMvc;

private static final long ONE_MINUTE = 60000;

private String token;
private Key key;
private TokenProvider tokenProvider;

@BeforeEach
public void setup() {
    tokenProvider = new TokenProvider( new JHipsterProperties());
    key = Keys.hmacShaKeyFor(Decoders.BASE64
        .decode("xxxx"));

    ReflectionTestUtils.setField(tokenProvider, "key", key);
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}

@Test
public void TestData() throws Exception {

    token=tokenProvider.createToken(createAuthentication(),false);
    String id="1";

    String expData = "Here is your data!";
    String result = mockMvc.perform(get("/api/test/"+ id)
        .header("Authorization","Bearer " + token))
        .andExpect(status().isOk())
        .andReturn()
        .getResponse()
        .getContentAsString();
    System.out.println("\nResult:\n"+result);
}

private Authentication createAuthentication() {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));
    return new UsernamePasswordAuthenticationToken("admin", "admin", authorities);
}

也更改了安全性配置

.antMatchers("/api/**").permitAll()
.antMatchers("/api/**").anonymous()
spring authentication spring-security jwt jhipster
1个回答
0
投票

我在Testclass的设置中向securityContext添加了身份验证!,它有效!

SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(createAuthentication());
SecurityContextHolder.setContext(securityContext);
© www.soinside.com 2019 - 2024. All rights reserved.