Java 使用spring security成功登录后发送请求
现在,我正在学习如何使用Spring安全框架实现RESTAPI 我的问题是,在使用spring security成功登录后,如何将请求发送到服务器,并确保服务器知道我已获得成功登录的授权 我有一些实验代码要做测试Java 使用spring security成功登录后发送请求,java,rest,authentication,spring-security,request,Java,Rest,Authentication,Spring Security,Request,现在,我正在学习如何使用Spring安全框架实现RESTAPI 我的问题是,在使用spring security成功登录后,如何将请求发送到服务器,并确保服务器知道我已获得成功登录的授权 我有一些实验代码要做测试 @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebAppConfig.class, SecurityConfig.class }) publ
@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())//
;
}
}
-
-
上面的代码运行良好,但我不知道如何在HTTP中实现会话部分。我期望在实际应用程序/实现中,而不是在测试环境中,在头或url中放置令牌或其他东西。客户端如何获取令牌?如何使用嵌入在客户机代码中的令牌调用请求?是否正在寻找模拟会话对象。如果是,则需要导入模拟会话对象,并在测试类中创建和使用该对象 导入org.springframework.mock.web.MockHttpSession MockHttpSession会话=新的MockHttpSession
session.setAttributevariable,对象 您的配置将使用服务器端会话来维护安全上下文,与客户端的链接是标准servlet JSESSIONID cookie,因此这与Spring安全性无关。您是否真正需要会话将取决于客户端的性质。如果客户端和服务器之间没有维护状态,那么来自客户端的每个请求都必须单独进行身份验证/授权。例如,可以使用基本身份验证或类似OAuth2访问令牌的方式来完成此操作,具体取决于您的要求。谢谢您的评论。对不起,我的问题不够清楚。但不,我的意思是在实际应用程序/实现中,而不是在测试环境中。客户端如何获取令牌?如何使用嵌入在客户机代码中的令牌调用请求。?
@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";
}
}