【发布时间】:2019-01-01 12:35:33
【问题描述】:
我已经配置了弹簧安全性。我创建了一个登录表单,用于登录我的应用程序。但是对于任何基于授权的“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>
注意应用程序已成功编译并运行,没有给出堆栈跟踪。只要给我禁止的错误。
我找不到,哪里出错了。请问,你能帮帮我吗?
提前致谢。
【问题讨论】:
-
你如何加载你的角色?什么是sql?你有在数据库中定义的角色吗?
-
我有两张表,一张是 users 表,其中字段名称是用户名、密码和启用,另一个是权限表,字段名称是用户名和权限。我遵循本教程,仅数据库部分。 youtube.com/watch?v=uxbtIqaKsOA
-
@Rashed 可能与stackoverflow.com/questions/41946473/… 重复或者只是一个错字(小写而不是大写)?
-
不,我尝试了大写和小写,但没有成功。 @dur
-
角色名称是ROLE_ADMIN还是ADMIN?
标签: spring-boot spring-security