我仍然是来自Grails背景的Spring启动初学者.
已有很多关于配置的文档.但到目前为止,我仍然没有任何作用,我想这是因为我仍然没有在春季启动时获得整个配置概念.
我希望我的应用程序使用我自己的数据库表进行身份验证.
我目前的表是:
CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(512) DEFAULT '', `password` varchar(512) DEFAULT NULL, `role_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `role` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `role_name` varchar(512) DEFAULT NULL, PRIMARY KEY (`id`) );
我试图用这个类配置我的安全性:
@Configuration @EnableWebSecurity @ComponentScan public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); } @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(this.dataSource) .authoritiesByUsernameQuery("select u.username,r.role_name from role r,users u where u.username = ? and u.role_id = r.id") .usersByUsernameQuery("SELECT username, password FROM users where username = ?") .passwordEncoder(new BCryptPasswordEncoder()); } }
但是当我尝试访问具有正确凭据的页面时,我仍然得到403.
我应该添加什么遗漏?我需要覆盖userDetailsService
我找不到任何明确的文档说明使用"users.username"列作为用户名,"users.password"作为密码或覆盖认证查询的方法.
谢谢
UserDetailsService
(JdbcDaoImpl
)的标准JDBC实现要求表加载用户的密码,帐户状态(启用或禁用)和权限列表(角色).该架构如下所示:
create table users( username varchar_ignorecase(50) not null primary key, password varchar_ignorecase(50) not null, enabled boolean not null ); create table authorities ( username varchar_ignorecase(50) not null, authority varchar_ignorecase(50) not null, constraint fk_authorities_users foreign key(username) references users(username) ); create unique index ix_auth_username on authorities (username,authority);
所以你应该用它来加载用户:
usersByUsernameQuery("SELECT username, password, enabled FROM users where username = ?")
这用于加载一个特定用户的所有权限:
select r.role_name from role r,users u where u.username = ? and u.role_id = r.id"
并且基于.passwordEncoder(new BCryptPasswordEncoder());
你在db中保存的密码应该用BCrypt
.请参阅spring security doc以获得有关Spring安全性如何工作的更多信息(而不是Spring boot的工作原理).
更新:用于启用HTTP Basic安全性:
@Override protected void configure(HttpSecurity http) throws Exception { http .httpBasic().and() .authorizeRequests().anyRequest().authenticated(); }
要进行身份验证,请添加如下Authorization
标题:
Authorization: Basic:
或者您可以将用户和密码包含在URL中:
http://user:passwd@localhost:8080/protected/service