我是春季安全方面的新手。刚刚使用jdbcauthenticationmanager向我的项目中添加了简单的基本身份验证,但它不起作用。
SpringSecurityConfig
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource ds;
@Bean
public BCryptPasswordEncoder getEncoder() {
return new BCryptPasswordEncoder(12);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(ds).usersByUsernameQuery("select * from users where username = ?")
.authoritiesByUsernameQuery("select username, authority from roles where username = ?")
.passwordEncoder(getEncoder());
;
}
@Override
public void configure(HttpSecurity http) throws Exception {
// Spring Security 4 automatically prefixes any role with ROLE_.
http.authorizeRequests().antMatchers("/").permitAll().anyRequest()
.hasAnyRole("ADMIN","USER").anyRequest().authenticated().and().httpBasic();
}
}
表中的数据:
insert into users ( username, password)
values ( 'payal', '$2a$12$YcoYj8Si2mbx.gYTLWwPeu51cfI2bTJlWBnnpaI2uYitfQtKzjPxm');
insert into users ( username, password)
values ( 'admin', '$2a$12$vhk1ELFdkwuvtAb8HrnUzOHEGJsnqX5ZX.C3TV3Q4Vuu9dsDcRH8e');
insert into roles ( username, authority)
values ( 'payal', 'ROLE_USER');
insert into roles ( username, authority)
values ( 'admin', 'ROLE_ADMIN');
完整代码可在https://github.com/payalbnsl/SpringMvcSecurity_err
中找到这是将内存数据库与db脚本一起使用,因此可以直接运行而无需任何额外的设置。
如果有人指出其未成功进行身份验证的原因,将有很大帮助。 每个用户名,密码,都是401,未经授权
但是,如果我将其更改为inMemoryAuthentication,则对用户名和密码进行硬编码。
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("payal").password("$2a$12$YcoYj8Si2mbx.gYTLWwPeu51cfI2bTJlWBnnpaI2uYitfQtKzjPxm").roles("USER");
}
答案 0 :(得分:0)
您必须使用默认方法bcrypt而非明文存储加密密码。
使用它来加密密码并存储加密的格式
System.out.println(new BCryptPasswordEncoder().encode("payal123"));
System.out.println(new BCryptPasswordEncoder().encode("admin"));
// . . .
答案 1 :(得分:0)
如果更改就可以工作
auth.jdbcAuthentication().dataSource(ds).usersByUsernameQuery("select * from users where username = ?")
.authoritiesByUsernameQuery("select username, authority from roles where username = ?")
.passwordEncoder(getEncoder());
;
到
auth.jdbcAuthentication().dataSource(ds).usersByUsernameQuery("select username, password, 'true' as enabled from users where username = ?")
.authoritiesByUsernameQuery("select username, authority from roles where username = ?")
.passwordEncoder(getEncoder());
;
添加“已启用'true'”可以解决该问题。