我正在尝试将Spring Security与Spring Boot Restful API集成。我的项目代码如下:
Web安全配置如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/API/**");
http.authorizeRequests()
.antMatchers("/API/user/**").permitAll()
.and().exceptionHandling().accessDeniedPage("/access-denied");
}
}
用户控制器:
@RestController
@RequestMapping("/API/user")
public class UserRestApiController {
@Autowired
UserService userService;
@RequestMapping(value="/all", method=RequestMethod.GET)
public ResponseEntity<Collection<Users>> getAll(){
return new ResponseEntity<Collection<Users>>(userService.getAlluser(), HttpStatus.OK);
}
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public ResponseEntity<Users> getUser(@PathVariable(value="id") int id){
return new ResponseEntity<Users>(userService.getUser(id), HttpStatus.OK);
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.PUT)
public String deleteUser(@PathVariable(value="id")int id){
userService.deleteUser(id);
return "DELETED";
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public ResponseEntity<String> addUser(@Valid @RequestBody Users user){
return new ResponseEntity<String>(userService.addUser(user), HttpStatus.OK);
}
@RequestMapping(value="/update", method=RequestMethod.PUT)
public ResponseEntity<Object> updateUser(@Valid @RequestBody Users user){
return new ResponseEntity<Object>(userService.updateUser(user), HttpStatus.OK);
}
}
用户服务:
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public Collection<Users> getAlluser() {
return userRepository.findAll();
}
public Users getUser(int id) {
return userRepository.getOne(id);
}
public void deleteUser(int id) {
userRepository.deleteById(id);
}
public Users updateUser(Users user) {
//Users u = userRepository.getOne(user.getId());
Users userUpdate = null;
if(userRepository.findById(user.getId()) != null) {
userUpdate = userRepository.save(user);
}
return userUpdate;
}
public String addUser(Users user) {
Users tmpUser = userRepository.findByUsername(user.getUsername());
if(tmpUser == null) {
userRepository.save(user);
return "CREATED";
} else {
return "EXISTED";
}
}
}
我正在尝试构建restful API。当我尝试访问链接http://localhost:8080/API/user/all时,它不返回json值,而是重定向到登录页面(我没有配置这样做)。
登录页面的图片:登陆页 您能帮我解决这个问题吗?
spring-boot-starter-security
时,它会自动重定向到登录页面。我必须删除依赖项或配置登录。 - Vũ Minh Vương