【发布时间】:2018-02-11 10:51:23
【问题描述】:
我正在尝试使用 JDBC (mysql) 设置简单的身份验证和授权。这是我用来初始化用户的 sql:
INSERT INTO users(username,password,enabled)
VALUES ('admin','admin', true);
INSERT INTO user_roles (username, role)
VALUES ('admin', 'USER');
INSERT INTO user_roles (username, role)
VALUES ('admin', 'ADMIN');
数据源属性:
spring.datasource.password=xxxx
spring.datasource.url=jdbc:mysql://localhost:3306/spring
spring.datasource.username=xxx
安全配置:
class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource source;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/uploadfiles/**").access("hasRole('ADMIN')");
http.authorizeRequests().antMatchers("/fonts/**").permitAll();
http.authorizeRequests().antMatchers("/").permitAll();
http.authorizeRequests().anyRequest().fullyAuthenticated().and()
.formLogin().loginPage("/login").defaultSuccessUrl("/").failureUrl("/login?error").permitAll().and()
.logout().permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(source).
usersByUsernameQuery("select username,password,enabled from users where username=?").
authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
}
登录效果很好,但是当尝试以管理员身份打开 /uploadfiles 链接时,我得到 403 响应。我还尝试检查角色是否正确,它们是否正确。我使用以下代码检查了它们:
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
authorities.forEach(authority -> logger.info(authority.toString()));
当我设置 inMemoryAuthentication 时,它也按预期工作,所以我猜它必须与 mysql 配置有关。有人在我的代码中看到错误吗?
【问题讨论】:
-
您的
role列是否包含权限('ADMIN')或角色('ROLE_ADMIN')? -
它是'ADMIN'、'USER'等,没有任何前缀。
标签: java mysql jdbc spring-security