Java Spring 5授权未按预期工作
我是春天安全的新手。在我的一个示例中,我们将SpringSecurity 5.4.5与SpringBoot一起使用 我在下面的配置类中尝试在RESTAPI的/user和/admin端点中应用Spring安全身份验证/授权Java Spring 5授权未按预期工作,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,我是春天安全的新手。在我的一个示例中,我们将SpringSecurity 5.4.5与SpringBoot一起使用 我在下面的配置类中尝试在RESTAPI的/user和/admin端点中应用Spring安全身份验证/授权 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired PasswordEncoder bc
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder bcryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().principal("guest").authorities("GUEST_ROLE")//Provide the name and role to the annonymous user
.and()
.authorizeRequests()
.antMatchers("/register").anonymous()//allows registration page to be accessed by annonymous users only
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/admin").hasAnyRole("ADMIN_ROLE")
.antMatchers(HttpMethod.GET,"/user").hasAnyRole("STUDENT_ROLE", "ADMIN_ROLE")
.and()
.httpBasic();
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
UserDetails annaSmithUserDetails = User.builder()
.username("annasmith")
.password(bcryptPasswordEncoder.encode("password"))//default password enoder is bcrypt
.roles("STUDENT_ROLE", "ADMIN_ROLE") //role of the user
.authorities("STUDENT_READ","STUDENT_WRITE","COURSE_READ","COURSE_WRITE") //authorities or we can say permission assigned to the user
.build();
return new InMemoryUserDetailsManager(annaSmithUserDetails);//can configure different
}
}
根据上述Spring配置,用户和管理员角色都可以访问/user,管理员角色可以访问/ADMIN
当我试图在浏览器中访问/user时,它会显示用户名和密码弹出窗口,一旦我输入配置用户的正确凭据,它将不工作,并给出403错误
我有以下三个问题
- 你的请求做得不恰当
- 您的密码可能不正确,因为我发现您的密码加密不正确()
- 确保使用正确的前缀存储密码,或使用
UserBuilder users=User.withDefaultPasswordEncoder()代码>在文档中构建用户时
- (_角色)是否遵循任何标准
- 登录后是否重定向到不允许访问的内容
答案很模糊,因为问题很模糊。@感谢您分享详细信息。我能够解决该问题,并将确保下次在问题中提供足够的详细信息。我已经在问题中提到了以下语句,当我尝试在浏览器中访问/user时,它会显示用户名和密码弹出窗口,一旦我输入了配置用户的正确凭据,则不会显示正在工作,并给出403错误。因此,当你说我没有提到我如何尝试访问应用程序时,我不理解你的评论。你能详细说明一下吗?