Spring Boot AuthenticationManager每次返回403

时间:2019-02-25 21:31:48

标签: spring rest spring-boot spring-security basic-authentication

我是Spring Security的新手,并试图在Spring Boot Rest Service上实现基本身份验证。我正在使用基于数据库的身份验证并具有用户和角色表。当我在应用程序中使用正确的凭据请求任何控制器时,它会给我始终禁止403。我不知道为什么。我多次检查角色是否正确。并且在数据库中,角色名称为“ USER”,“ RESTAURANT”和“ ADMIN”。我尝试了ROLE_前缀和独立大写语法方式不起作用。不知道我在做什么错。这是我的配置类:

@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;
    }
}

这是我的返回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)密码将其注册到数据库中,并且我试图对此进行身份验证。我能够检索新用户并注册到db并正确地加密密码。    我不知道我是否可以通过这种方式在注册时控制用户名和电子邮件,但是如果您在乎,这是响应的控制器方法:

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

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

每一个帮助和建议都非常重要。

1 个答案:

答案 0 :(得分:0)

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

indexPathForPreferredFocusedView

编辑: Refer this to get more details on Roles