【发布时间】:2018-01-24 00:49:51
【问题描述】:
我有一个简单的(此时仍然是演示程序)Spring 程序(Spring Rest 和 Security),它以简单的方式工作。通过 JpaRepository,我可以获取所有(/option 由 findAll() 处理)、GET 一个(/option/1 由 findOne(Long id) 处理)、PUT 和 POST。
我的业务模型表明,登录用户应该只能看到他们有权访问的记录。所以 findAll() 应该返回三个记录, findOne(id) 应该返回一个或零。
我相信我必须将它们与注释中的 Principal 对象联系起来。我尝试了各种方案,但还没有弄清楚 Spring 想要我什么。对于 findAll() 我试过这个:
@Override
@Query("from Option o where o.id = 11")
public List<Option> findAll();
但是,findAll() 仍然返回许多记录。
然后我尝试将我的查询与校长联系起来:
@Override
@Query("from Option o where o.id = ?#{ principal.id}")
public List<Option> findAll();
(我也试过?#{#principal.id})
这以有趣的方式失败了。
- 当它返回 HTTP 500 时,我被告知找不到“主体”。
- 一旦我重新配置我的程序,我得到一个 HTTP 404,这意味着我问错了什么。但由于我不知道如何转储 principal.id 值(从接口记录?)我看不出我做错了什么。
这是我公开 UserDetailsService 的方式:
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
这是我在 pom.xml 中配置主体的方式:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
<!-- <version>4.2.1.RELEASE</version> -->
</dependency>
在 Java 中:
@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}
我的问题是:
- 为什么@Query("from Option o where o.id = 11") 不只返回一条记录?
- 如何判断“principal”的属性,从而判断它的ID是不是我想的那样?
- 我还应该问其他问题吗?
谢谢, 杰罗姆。
【问题讨论】:
标签: spring-security spring-data-jpa spring-el