【问题标题】:JHipster: Receive 401 Unauthorized when testing microservicesJHipster:测试微服务时收到 401 Unauthorized
【发布时间】:2020-03-23 20:10:00
【问题描述】:

我使用 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);
}

也像这样更改了securityconfig

.antMatchers("/api/**").permitAll()
.antMatchers("/api/**").anonymous()

【问题讨论】:

  • 可以显示生成的token吗?
  • 生成的令牌:eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOIiwiZXhwIjoxNTc0OTI4NTY4fQ.cq3EB07WDpR5tvlKRAaddumHpkyGVYXuzZ3BOyRp33XmoPbomNHTPI59QNDeOAYaWx_cFEPb7VtTPdwEJEr6tA 跨度>

标签: spring authentication spring-security jwt jhipster


【解决方案1】:

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

SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(createAuthentication());
SecurityContextHolder.setContext(securityContext);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多