Reputation: 755
I am novice in spring security. Just added simple basic authentication to my project using jdbcauthenticationmanager and it is not working.
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();
}
}
Data in table:
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');
The entire code can be found at https://github.com/payalbnsl/SpringMvcSecurity_err
This is using in-memory database with db scripts, so can just run without any extra set-up needed.
It will be of great help if someone can point out why it is not authenticating successfully. Every username, password, it is saying 401, not authorized
However it works if i change it to inMemoryAuthentication, hardcoding the username, password.
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("payal").password("$2a$12$YcoYj8Si2mbx.gYTLWwPeu51cfI2bTJlWBnnpaI2uYitfQtKzjPxm").roles("USER");
}
Upvotes: 4
Views: 1466
Reputation: 755
Worked if changed
auth.jdbcAuthentication().dataSource(ds).usersByUsernameQuery("select * from users where username = ?")
.authoritiesByUsernameQuery("select username, authority from roles where username = ?")
.passwordEncoder(getEncoder());
;
to
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());
;
Adding "'true' as enabled" fixed it.
Upvotes: 2
Reputation: 14943
You have to store encrypted password using the default method, bcrypt, not plaintext.
Use this to encrypt your passwords and store the encrypted format
System.out.println(new BCryptPasswordEncoder().encode("payal123"));
System.out.println(new BCryptPasswordEncoder().encode("admin"));
// . . .
Upvotes: 0