【问题标题】:What is the right way to supply user and password for jdbc auth?为 jdbc auth 提供用户名和密码的正确方法是什么?
【发布时间】: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());
}

【问题讨论】:

标签: java spring rest spring-security basic-authentication


【解决方案1】:

从文档看来,您可以将其作为表单主体或基本身份验证提供,无论您喜欢哪种方式:

http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-form-and-basic

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2011-01-12
    • 2013-01-17
    • 1970-01-01
    • 2020-08-09
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多