@WithMockUser with custom User implementation

后端 未结 1 1940
眼角桃花
眼角桃花 2021-02-10 07:04

I\'m using spring OAuth2 and JWT tokens to secure an application. I am extending org.springframework.security.core.userdetails in order to add some additional a

相关标签:
1条回答
  • 2021-02-10 07:53

    You can use the @WithUserDetails annotation.
    If you have a user with the username "user1", then you can annotate your test with @WithUserDetails("user1") and it will execute with a CustomUser principal, including the custom attribute "bookId" associated with "user1".
    You can find more information about the annotation in the spring-security docs.

    If you want more flexibility, you can also use the @WithSecurityContext annotation.
    This allows you to create your own annotation, e.g @WithMockCustomUser, where you set the security context yourself.
    You can find more details in the spring-security docs.

    One more option, if you are using MockMvc to run your tests, it to use a request post processor.
    Your test would look like this

    mvc
        .perform(get("/api/books/1")
        .with(user(customUser)));
    

    where customUser is an instance of CustomUser that you create in the test.

    0 讨论(0)
提交回复
热议问题