spring 每次启动 AuthenticationManager returns 403

spring boot AuthenticationManager returns 403 every time

我是 spring 安全方面的新手,正在尝试在 spring 启动休息上实施基本身份验证 service.I 我正在使用基于数据库的身份验证并拥有用户和角色 table.When我在我的应用程序中使用正确的凭据请求任何控制器它总是给我 403 forbidden.I 无法计算 why.I 检查角色很多次它是 correct.And 在数据库中角色名称是 "USER" 和 "RESTAURANT" 和 "ADMIN"。我尝试使用 ROLE_ 前缀和独立的大写语法两种方式都没有 work.Don 不知道我在做什么 wrong.Here 是我的配置class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled=true,jsr250Enabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService customUserDetailsService;

    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception
    {
        auth.userDetailsService(customUserDetailsService)
        .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .httpBasic()
            .authenticationEntryPoint(authEntryPoint)
            .and()
            .authorizeRequests()
            .antMatchers("/user/register","/forgotPassword").permitAll()
            .anyRequest().authenticated()
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
             ;
    }
    }

这是我的 UserDetailService 实现:

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user = userRepository.findByUsername(username);
        System.out.println(user.toString()); //here i check if it's finding right user 
        if (user == null) {
            throw  new UsernameNotFoundException(username +" not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
    }

    private static Collection<? extends GrantedAuthority> getAuthorities(User user)
    {
        String[] userRoles = user.getRoles()
                                    .stream()
                                    .map((role) -> role.getName())
                                    .toArray(String[]::new);
        Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(userRoles);
        return authorities;
    }
}

这是我的控制器之一 returns 403:

@PreAuthorize("hasRole('USER')")
    //@Secured("USER")
    @GetMapping("/{restaurantmenu}") //bütün menüyü çeker
    Collection<Menu> getMenu(@PathVariable("restaurantmenu") Long id) {
        return menuService.getMenuItemsByRestaurant(restaurantService.getRestaurant(id));
    }

并供您参考。我有一个注册 url 所以我通过 json 获取新用户并使用加密 (Bcrypt) 密码将其注册到数据库中,我正在尝试使用 that.I 进行身份验证我能够检索新用户并且注册到数据库并正确加密密码。 我不知道用这种方式注册时我是否能够控制用户名和电子邮件,但如果你关心这里是响应控制器方法:

@RestController
@RequestMapping(value="/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    void registerUser(@Valid @RequestBody User user) {
        userService.save(user);
    }
}

我们将竭诚为您提供帮助和建议。

在数据库中将角色另存为 ROLE_USER、ROLE_ADMIN 并添加特定方法可能会对您有所帮助。

.antMatchers(HttpMethod.POST,"/user/register","/forgotPassword").permitAll()
.antMatchers(HttpMethod.GET,"/restaurantURL").permitAll()

编辑: