有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring安全角色检查永久失败

我正在努力学习Spring安全性,并希望获得一个API。我想要一个一方面具有数据库身份验证,另一方面具有OAuth2身份验证的登录表单。 但我被困在第一项任务上。问题是应用程序不接受我的角色,我不知道为什么

下面是我的配置类:

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@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=?");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/createTrack").hasRole("CREATOR")
            .antMatchers("/getTrack").hasAnyRole("CREATOR", "USER")
            .antMatchers("/test").hasRole("CREATOR")
            .antMatchers("/all").permitAll()
            .and().formLogin();
}

@Bean
public PasswordEncoder getPasswordEncoder() {
    // TODO: Change this to hashed password (this is for demo purposes)
    return NoOpPasswordEncoder.getInstance();
}
}

一切都像Spring文档中描述的那样:https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-authentication-jdbc

我设计了几个API端点来测试登录用户的名称和角色。一切都很好——登录看起来很好,角色也很正确

但是,当我试图调用一个只能由一个或两个特定角色访问的端点时,会得到403错误响应

我做错了什么?我尝试了很多东西,但仍然不起作用

谢谢

PS:我正在使用MyBatis(我公司的任务)——如果这有什么关系的话


共 (1) 个答案

  1. # 1 楼答案

    谢谢你们的帮助! 托尔库姆拉尔的回答让我想到了解决办法。我按照你的建议打开了调试日志。CORS不是问题所在,但阅读调试消息让我走上了正确的道路

    不过问题很小。我将角色存储在数据库中作为“创建者”或“用户”。调试消息显示,Spring正在寻找“角色创建者”或“角色用户”,因为我的角色没有以这种方式保存,所以没有找到它们。因此,我得到了403 HTTP响应