Spring Boot中Spring Security配置不生效,Admin用户登录后返回403错误
问题根因
Spring Security 中调用hasRole()、hasAnyRole()方法做角色校验时,会自动给传入的角色名称拼接ROLE_前缀,再和用户的权限字段值做匹配。你当前数据库authorities表中存储的权限值为Admin、User,没有对应前缀,导致匹配失败返回403。
解决方案(任选一种即可)
方案1:修改数据库权限值
连接你独立运行在9092端口的H2数据库,将authorities表中authority字段的值修改为带ROLE_前缀的格式:ROLE_Admin、ROLE_User,无需修改代码即可生效。
方案2:修改Security配置取消自动前缀拼接
有两种修改方式可选:
方式A:用权限校验方法替换角色校验方法
将HttpSecurity配置中的hasRole()替换为hasAuthority(),hasAnyRole()替换为hasAnyAuthority(),这两个方法不会自动拼接前缀,直接和权限字段值做匹配:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**").hasAuthority("Admin") .antMatchers("/office/createOffice", "/office/createOffices", "/office/updateOffice/**", "/office/deleteOffice/**").hasAuthority("Admin") .antMatchers("/employee/getEmployee/**", "/employee/getAllEmployees").hasAnyAuthority("Admin","User") .antMatchers("/office/getOffice/**", "/office/getAllOffices").hasAnyAuthority("Admin","User") .and().formLogin(); }
方式B:配置JDBC认证的角色前缀为空
在AuthenticationManagerBuilder配置中新增rolePrefix(""),指定角色前缀为空,取消自动拼接逻辑:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("select username,password,enabled from users where username = ?") .authoritiesByUsernameQuery("select username,authority from authorities where username = ?") .passwordEncoder(NoOpPasswordEncoder.getInstance()) .rolePrefix(""); }
注意
当前配置使用的NoOpPasswordEncoder为明文密码编码器,仅适合本地测试使用,生产环境请替换为BCryptPasswordEncoder等加密编码器。
内容的提问来源于stack exchange,提问作者kverma28
相关产品推荐
相关产品推荐

