首页 > 解决方案 > 在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 应用程序已成功编译并运行,没有给出堆栈跟踪。只要给我禁止的错误。

我找不到,哪里出错了。拜托,你能帮帮我吗?
提前致谢。

标签: spring-bootspring-security

解决方案


这是从数据库加载用户名、密码和权限的默认 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


推荐阅读