我正在使用Spring Boot开发一个基本的笔记应用程序。当GET请求到达NoteController时,我想检查用户是否有此笔记。在示例中,ID为1的示例属于UserA。如果UserB尝试通过以下URL获得此注释:/ note / 1,则我不希望UserB访问此注释。为了解决此问题,每次对NoteController发出请求时,我都会从SecurityContextHolder中获取经过身份验证的用户,并检查note是否属于该用户。有什么比这更好的吗?
NoteController
package app.controller;
import app.entity.Note;
import app.entity.User;
import app.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/note")
public class NoteController
{
@Autowired
private NoteService noteService;
@PostMapping
public Note save(@RequestBody Note note)
{
User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
note.setUser(user);
noteService.save(note);
return note;
}
@PutMapping
public ResponseEntity<Void> update(@RequestBody Note note)
{
User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(noteService.findById(note.getId()).getUser().getId()==user.getId())
{
noteService.update(note);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@GetMapping("/{id}")
public ResponseEntity<Note> findById(@PathVariable int id)
{
User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Note note=noteService.findById(id);
if(note.getUser().getId()==user.getId())
return new ResponseEntity<>(note,HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
@GetMapping
public List<Note> findByUser()
{
User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return noteService.findByUser(user);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteById(@PathVariable int id)
{
User user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Note note=noteService.findById(id);
if(note.getUser().getId()==user.getId())
{
noteService.deleteById(id);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
WebSecurityConfig
package app.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private TokenFilter tokenFilter;
@Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
protected void configure(HttpSecurity http) throws Exception
{
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.POST,"/note").hasAuthority("CREATE")
.antMatchers(HttpMethod.GET,"/note").hasAuthority("READ")
.antMatchers(HttpMethod.PUT,"/note").hasAuthority("UPDATE")
.antMatchers(HttpMethod.DELETE,"/note").hasAuthority("DELETE")
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(tokenFilter,UsernamePasswordAuthenticationFilter.class);
}
}
答案 0 :(得分:0)
所有findById()
调用结果都提供给授权检查,这意味着逻辑可以移到一个公共位置,即findById()
。
可以使用Method Security Expressions:@PostAuthorize批注完成相同的授权逻辑
一个例子如下。可以修改NoteService.findById(id)
方法以进行此检查,并可以删除控制器方法中的用户检查逻辑。
@PostAuthorize("returnObject.user.id == principal.id")
public Note findById(Long id)
{
return noteRepository.findById(id);
}
这里@PostAuthorize
是在内置returnObject
上完成的。
还请记住启用GlobalMethodSecurity,如下所述,以使Pre和Post注释起作用
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
//...
}
希望这会有所帮助。