【发布时间】:2016-06-23 23:34:18
【问题描述】:
使用
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
我的示例运行良好。例如对于
http.authorizeRequests()
// ...
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
如果我将 inMemoryAuthentication 更改为 spring jdbc 默认值 - 我遇到了角色问题。
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
我确定我使用 spring 推荐配置了 db 和 schema(能够使用默认的 jdbc 身份验证)。
在调试模式下,我可以在
中看到从 db 加载的结果org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl
#loadUserByUsername(username)[line 208]
return createUserDetails(username, user, dbAuths);
它返回与内存配置类似的结果:
org.springframework.security.core.userdetails.User@183a3:
Username: dba;
Password: [PROTECTED];
Enabled: true;
AccountNonExpired: true;
credentialsNonExpired: true;
AccountNonLocked: true;
Granted Authorities: ADMIN,DBA
如您所见,它加载了相应的授权权限,但 http 请求将我重定向到 .accessDeniedPage("/Access_Denied")。我很困惑,因为它应该像以前一样适用于用户。
我的项目中没有使用 Spring Boot。 我的日志不包含任何 jdbc 错误配置。 我花了很多时间研究细节,我的想法刚刚完成。 你认为我需要添加来构建一些缓存库或其他东西吗?
【问题讨论】:
-
不,它不应该...当使用 in-memroy 数据库时,角色会自动以
ROLE_为前缀(默认角色前缀)。hasRole('ADMIN')也是如此,它还将检查传入的角色是否带有前缀,如果没有,则添加它。您的用户拥有ADMIN而不是ROLE_ADMIN的权限,因此检查失败。要么使用hasAuthority而不是hasRole(并在你的内存样本中将roles更改为authorities)或在数据库中的权限前加上ROLE_或将默认角色前缀更改为空而不是ROLE_. -
非常感谢!现在可以了。您能否在角色比较的位置添加链接(我希望这些信息在不久的将来对我有用)?
标签: spring security authentication jdbc role