【发布时间】:2017-02-28 07:58:22
【问题描述】:
我正在尝试开发一个可以与 REST API 一起使用的服务器后端。我想提供一个端点,用户通过请求发送用户名和密码。在数据库中查找用户数据,如果用户有效,则创建一个 JWT 令牌并通过响应发送给客户端。
对于查找,我想使用 Spring Security 附带的 jdbc 身份验证。为 jdbc 身份验证提供数据的正确方法是什么?我必须在请求标头中写入用户名和密码吗?或者可以使用http基本身份验证吗?
编辑: 我目前的方法如下。我已经配置了 jdbc 身份验证和 http 基本身份验证。我尝试通过集成测试对此进行测试。测试以 401 状态响应,而我期望 200 状态。我已经单独测试了 sql 查询。他们工作。
谁能告诉我我做错了什么?
安全配置:(这是一个内部类)
@Configuration
@Import(DaoConfig.class)
@Order(2)
public static class HttpBasicAuthConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("select username, password, 1 from account where username=?")
.authoritiesByUsernameQuery("select username, 'user' from account where username=?")
.rolePrefix("");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/auth/login")
.authorizeRequests()
.anyRequest().hasAuthority("user")
.and().httpBasic()
.and().csrf().disable();
}
}
测试代码:
@Autowired
private FilterChainProxy springSecurityFilterChain;
private MockMvc securityMockMvc;
@Before
public void SetupContext() {
securityMockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.addFilters(springSecurityFilterChain)
.apply(springSecurity()).build();
}
@Test
public void testLoginHttpBasic() throws Exception {
MockHttpServletRequestBuilder post = post("/auth/login").with(httpBasic("frank","password"));
securityMockMvc.perform(post).andExpect(status().isOk());
}
【问题讨论】:
-
这不是您问题的答案。但这可能值得一看。 stackoverflow.com/a/10864088/6785908
标签: java spring rest spring-security basic-authentication