spring bootManager每次都返回403

问题描述 投票:1回答:1

我是Spring安全性的新手,并试图在Spring引导休息服务上实现基本身份验证。我正在使用基于数据库的身份验证并拥有用户和角色表。当我使用正确的凭据向我的应用程序中的任何控制器发出请求时,它总是给我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)
             ;
    }
    }

这是我的UserDetailSservice实现:

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

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

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

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

每一个帮助和建议将不胜感激。

spring rest spring-boot spring-security basic-authentication
1个回答
0
投票

将角色保存为数据库中的ROLE_USER,ROLE_ADMIN并添加特定方法可能对您有所帮助。

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

编辑:Refer this to get more details on Roles

© www.soinside.com 2019 - 2024. All rights reserved.