在春季安全性中按角色进行api授权并通过httpbasic(username:password)进行身份验证

时间:2019-07-18 09:52:43

标签: mongodb spring-boot spring-security spring-rest

我正在尝试通过spring-security身份验证(用户名:密码)和授权(角色)来保护api端点。身份验证可以正常工作,但不能正常工作。

我尝试使用antMatchers()方法指定具有角色授权的终结点。我是一个初学者,无法解决问题。任何提示将非常有帮助。

SecurityConfig.java

package com.example.mongoBootDemo.security;

    @Configuration 
    @EnableConfigurationProperties
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        MongoUserDetailsService uds;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/hotels/users").hasRole("ADMIN")
                .antMatchers("/hotels/address/**").hasRole("EMPLOYEE")
                .anyRequest().fullyAuthenticated()
                //.anyRequest().authenticated()
                .and().httpBasic()
                .and().sessionManagement().disable();
        }

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

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(uds);
        }
    }

MongoUserDetailsS​​ervice.java

package com.example.mongoBootDemo.service;

@Component
public class MongoUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersRepository ur;
    private Logger myLogger=Logger.getLogger(getClass().getName());

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Users user=ur.findByUsername(username);

        if(user==null) {
            throw new UsernameNotFoundException("User not found");
        }

        // to get the user role
        List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(user.getRole()));

        myLogger.info("=== : "+user.getUsername()+user.getPassword()+authorities );
//output: rinku$2a$10$L/HoziPhb1DjupoP0hkfcO4PteaofnNm77JWhe9IjTZBNoyit2eGG[EMPLOYEE]

        return new User(user.getUsername(),user.getPassword(),authorities);
    }
}

HotelController.java

 package com.example.mongoBootDemo.controller;
 @RestController
    @RequestMapping("/hotels")
    public class HotelController {

        @Autowired
        private PasswordEncoder pe;

        @Autowired
        private HotelMongoRepository hotelRepository;

        @Autowired
        private UsersRepository ur;

        @GetMapping("/all")
        public List<Hotel> getAll(){
           List<Hotel> hotels=hotelRepository.findAll();
           return hotels;
        }
        @GetMapping("/users")
        public List<Users> getUsers(){
            List<Users> user=ur.findAll();
            return user;
        }
        @PostMapping("/users")
        public void addUser(@RequestBody Users user) {
            user.setPassword(pe.encode(user.getPassword()));
            ur.save(user);  
        }
        @GetMapping("/address/{city}")
        public List<Hotel> getByCity(@PathVariable ("city") String city){
            List<Hotel> hotels=hotelRepository.findByCity(city);
            return hotels;
        }
    }

尽管分配了角色,但结果只是通过进行身份验证来提供对端点的访问权限。

0 个答案:

没有答案