0
我正嘗試使用JDBC(mysql)設置簡單身份驗證和授權。下面是即時通訊使用,以初始化用戶的SQL:Spring Boot中的JDBC授權
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的配置。任何人在我的代碼中看到錯誤?
您的「角色」列是否包含權限('ADMIN')或角色('ROLE_ADMIN')? –
這是'管理員','用戶'等沒有任何前綴。 –