spring-boot - 在spring security(Spring boot)中获取所有url中的禁止错误
问题描述
我已经配置了弹簧安全性。我创建了一个登录表单,用于登录我的应用程序。但是对于任何基于授权的“USER”或“ADMIN”角色的 url,都会出现禁止错误。但所有 permitAll 权限 url 工作正常。
在配置文件...
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/bootstrap/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/home").hasRole("user")
.antMatchers("/admin").hasRole("admin")
.antMatchers("/**").denyAll()
.and()
.formLogin()
.loginPage("/")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.httpBasic()
.and()
.csrf()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
在控制器类
@Controller
public class HomeController {
@RequestMapping(value= {"/", "/index"}, method=RequestMethod.GET)
public String showHome() {
return "index";
}
@RequestMapping(value="/home")
public String login() {
return "home";
}
@RequestMapping(value="/admin")
public String showDashboard() {
return "dashboard";
}
}
在登录表单中,
<form class="form-signin" th:action="@{/}" method="post">
...
...
...
</form>
在 pom.xml 中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
NB 应用程序已成功编译并运行,没有给出堆栈跟踪。只要给我禁止的错误。
我找不到,哪里出错了。拜托,你能帮帮我吗?
提前致谢。
解决方案
这是从数据库加载用户名、密码和权限的默认 sql。
public static final String DEF_USERS_BY_USERNAME_QUERY = "select username,password,enabled "
+ "from users " + "where username = ?";
public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select username,authority "
+ "from authorities " + "where username = ?";
而角色只是一个以 开头的权限ROLE_
,hasRole('XXX')
与hasAuthority('ROLE_XXX')
因此,您可以将数据库中的角色名称更改为ROLE_ADMIN
,
或者你可以使用hasAuthority('admin')
而不是hasRole
推荐阅读
- kubernetes - Kafka 副本突然不同步
- javascript - Postman 在尝试浏览图像文件时不显示图像文件
- teradata - Teradata CLOB 对象
- python - 如何在不关闭任何这些连接的情况下处理来自多个客户端套接字的数据流?
- python - Pandas 结合日期和小时列
- reactjs - 设计 Bootstrap 动态导航选项卡组件
- javascript - 异步函数返回挂起/已满
- javascript - VueJS:如何在 App.vue 中编辑所有相同类型的组件
- python - 是否可以调用间接调用另一个 cuda.jit 函数的 cuda.jit 函数?
- python - 是否有一种有效/最佳的方式将数据从 BigQuery 表传输到 Elasticsearch?