[英]Spring Security Redirects to login page and kills sessions after authentication success
[英]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.