【问题标题】:Null @AuthenticationPrincipal and PreAuthorized not working Spring Boot 2 / Security 5Null @AuthenticationPrincipal 和 PreAuthorized 不起作用 Spring Boot 2 / Security 5
【发布时间】:2018-10-21 17:12:39
【问题描述】:

我有一个 REST API,想用 Spring Security 保护它。我在这里按照教程进行操作:https://github.com/Zuehlke/springboot-sec-tutor 我的整个项目可以在这里找到:https://github.com/YanickSchraner/wodss-tippspiel_backend

我面临的问题是,即使在执行成功的登录 POST 请求之后,@AuthenticationPrincipal 也会返回 Null。我假设,因为 @PreAuthorized 注释也不起作用。

这是我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RESTAuthenticationSuccessHandler restAuthenticationSuccessHandler;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception{
        return super.authenticationManager();
    }

    @Bean
    public RESTAuthenticationFilter restAuthenticationFilter() {
        RESTAuthenticationFilter restAuthenticationFilter = new RESTAuthenticationFilter(objectMapper);
        restAuthenticationFilter.setAuthenticationManager(authenticationManager);
        restAuthenticationFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
        return restAuthenticationFilter;
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and().anonymous().disable()
                .csrf().disable() // CSRF protection is done with custom HTTP header (OWASP suggestion)
                .addFilterBefore(new XRequestedWithHeaderFilter(), CsrfFilter.class)
                .addFilterBefore(new EnforceCorsFilter(), CsrfFilter.class)
                .addFilterBefore(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .logout().logoutSuccessHandler((request, response, authentication) -> response.setStatus(HttpServletResponse.SC_OK))
                .and()
                .headers()
                .frameOptions().sameOrigin()
                .contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline'; report-uri /csp")
                .and()
                .httpStrictTransportSecurity()
                .maxAgeInSeconds(63072000);
        http
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)
                .deleteCookies("BettingGame_SchranerOhmeZumbrunn_JSESSIONID");
        http
                .sessionManagement()
                .sessionFixation()
                .newSession();
    }
}

这是我的 UserDetailsS​​erviceImpl:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Value("${security.login.errormessage}")
    private String errorMessage;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findUserByNameEquals(username)
                .orElseThrow(() -> new UsernameNotFoundException(errorMessage));
        HashSet<GrantedAuthority> authorities = new HashSet<>();
        if(user.getRoles() != null){
            user.getRoles().stream()
                    .map(Role::getName)
                    .map(SimpleGrantedAuthority::new)
                    .forEach(authorities::add);
        }
        return new org.springframework.security.core.userdetails.User(user.getName(),user.getPassword(), authorities);
    }
}

这是我的控制器的一部分,我从 @AuthenticationPricipal 获得 Null 并且即使在执行成功登录后@PreAuthorized 也返回 403:

@RestController
@RequestMapping("/users")
//@PreAuthorize("hasRole('USER')")
public class UserController {

    private final UserService service;

    @RequestMapping(value = "/self",method = RequestMethod.GET)
    public ResponseEntity<User> getLogedInUser(@AuthenticationPrincipal User user){
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @Autowired
    public UserController(UserService service) {
        this.service = service;
    }

    @GetMapping(produces = "application/json")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<List<User>> getAllUsers() {
        return new ResponseEntity<>(service.getAllUsers(), HttpStatus.OK);
    }

【问题讨论】:

    标签: rest spring-boot spring-security


    【解决方案1】:

    我终于明白了。两个简单的错误: 1. @AuthenticationPrinciple 为 Null,因为我要求的是 User 对象,但我的 UserDetailsS​​erviceImpl 正在存储/返回 UserDetails 对象。通过使我的 User 域对象实现 UserDetails 接口并使我的 UserDetailServiceImpl 返回该 User 对象,这个问题得到了解决。

    1. @PreAuthorize("hasRole('USER')") 导致了 403,因为 spring 为角色添加了“ROLE_”前缀,并且我将没有该前缀的角色存储在我的数据库中。通过在数据库中将角色名称从“USER”更改为“ROLE_USER”,此问题已得到解决。

    工作代码可以在这个公共 github 项目中找到:https://github.com/YanickSchraner/wodss-tippspiel_backend

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 2020-08-05
      • 1970-01-01
      • 2016-02-10
      • 2016-05-11
      • 2017-06-16
      • 2016-07-13
      相关资源
      最近更新 更多