簡體   English   中英

使用Spring Security成功登錄后發送請求

[英]Send request after success login with spring security

現在,我正在學習有關使用Spring Security Framework實現REST API的知識。

我的問題是,在使用Spring Security成功登錄后,如何將請求發送到服務器,並確保服務器知道我已經被授權(已經成功登錄)?

我有一些實驗代碼可以進行測試

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebAppConfig.class, SecurityConfig.class })
public class TheTest {

    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private FilterChainProxy filterChainProxy;

    protected MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders//
                .webAppContextSetup(wac)//
                .addFilter(filterChainProxy)//
                .build()//
        ;
    }

    @Test
    public void testDoingArequest() throws Exception {

        // login here
        HttpSession session = mockMvc.perform(//
                //
                post("/login-process")//
                        .param("username", "theusername")//
                        .param("password", "thepassword")//
                )//
                .andDo(print())//
                .andExpect(status().isFound())//
                .andReturn().getRequest().getSession()//
        ;

        // login is success and now trying to call request
        this.mockMvc.perform(//
                get("/doingRequest")//
                        .session((MockHttpSession) session)// <-- where this part must added to?
                )//
                .andExpect(status().isOk())//
                .andDo(print())//
        ;

    }

}

--

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()//
            .antMatchers("/doingRequest").authenticated()//
            .anyRequest().permitAll()//
            .and()//
            .csrf().disable()//
            .formLogin()//
            .loginPage("/")//
            .loginProcessingUrl("/login-process")//
            .defaultSuccessUrl("/");

}

--

@Controller
public class TheController {

    @RequestMapping(value = "doingRequest", method = RequestMethod.GET)
    @ResponseBody
    public String doingSomething() {
        return "Only authorized user can read this";
    }

}

--

上面的代碼運行良好,但是我不知道如何在HTTP中實現“會話”部分。 我期望在現實生活中的應用程序/實現中放置令牌或在標頭或url中放置某種東西,而不是在測試環境中。 客戶如何獲得代幣? 我們如何在客戶端代碼中調用請求(嵌入令牌)?

您是否正在尋找模擬會話對象,如果需要,則需要導入模擬會話對象,並且可以在測試類中創建和使用該對象。

導入org.springframework.mock.web.MockHttpSession;

MockHttpSession會話=新的MockHttpSession();

session.setAttribute(“ variable”,object);

您擁有的配置將使用服務器端會話來維護安全性上下文,並且與客戶端的鏈接是標准的Servlet JSESSIONID cookie,因此與Spring Security無關。 您是否真正想要一個會話取決於客戶的性質。 如果客戶端和服務器之間沒有維護任何狀態,則來自客戶端的每個請求都必須分別進行身份驗證/授權。 例如,這可以使用基本身份驗證來完成,或者根據您的要求使用OAuth2訪問令牌之類的方式來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM