Spring Security配置jdbcAuthentication()登录后返回403 Forbidden,inMemory认证正常
问题根因
你遇到的403错误核心是Spring Security的hasRole()/hasAnyRole()方法会自动给角色名称添加ROLE_前缀,而你数据库authorities表中存储的role值没有对应前缀,导致权限校验匹配失败。你输入错误密码会返回Bad Credentials,说明账号密码的认证逻辑已经正常生效,仅仅是授权环节的角色匹配出现问题。
解决方案1:修改数据库存储的角色值
直接更新authorities表的role字段,给所有角色加上ROLE_前缀即可,无需调整代码:
update stackoverflow.authorities set role = 'ROLE_REGISTERED_USER' where role = 'REGISTERED_USER'; update stackoverflow.authorities set role = 'ROLE_ADMIN' where role = 'ADMIN';
解决方案2:调整权限校验规则,改用hasAnyAuthority()
hasAnyAuthority()方法不会自动添加ROLE_前缀,会直接匹配数据库存储的权限值,只需修改configure(HttpSecurity http)方法内的权限配置即可:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/user-profile/admin/**").hasAnyAuthority("ADMIN") .antMatchers("/user-profile/users/**").hasAnyAuthority("REGISTERED_USER","ADMIN") .antMatchers("/welcome").permitAll().and().formLogin() .and().csrf().disable(); }
内容的提问来源于stack exchange,提问作者Arunabha Ghosh
相关产品推荐
相关产品推荐

