@AuthenticationPrincipal返回空用户

时间:2016-12-08 22:12:00

标签: java spring spring-mvc spring-security

我有这个控制器,我保存与当前经过身份验证的用户关联的帖子信息:

static int nas_initalize(const char *path)
{
  int error = 0;
  bson_reader_t *reader = bson_reader_new_from_file(path, &bson_error);
  if (!reader) {
    fprintf (stderr, "ERROR: %d.%d: %s\n",
             bson_error.domain, bson_error.code, bson_error.message);
  }
  super_block = bson_reader_read(reader, NULL);
  bson_iter_init(&iter, super_block);

  if (bson_iter_find(&iter, "max_dir"))
    {
      max_dir = bson_iter_int32(&iter);
    }
  else
    {
      error = -1;
      bson_reader_destroy(reader);
    }

  if (bson_iter_find(&iter, "raid_lv"))
    {
      raid_lv = bson_iter_int32(&iter);
    }
  else
    {
      error = -1;
      bson_reader_destroy(reader);
    }

  if(bson_iter_find(&iter, "vol"))
    {
      int count = 0;
      bson_iter_recurse(&iter, sub_iter);
      while(bson_iter_next(sub_iter) == true)
        {
          if (bson_iter_find_descendant(&iter, "vol.0", sub_iter))
            {
              vol[count++] = bson_iter_utf8 (sub_iter, NULL);
            }
        }
    }
  else
    {
      error = -1;
      bson_reader_destroy(reader);
    }

  bson_reader_destroy(reader);

  return error;
}

@PostMapping("/create") public String processPost( @CurrentUser User activeUser, @ModelAttribute @Valid Post post, Errors errors){ if(errors.hasErrors()){ return "admin/post/create"; } User user2 = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); logger.info("Información del usuario mediate @CurrentUser: " + activeUser.toString()); logger.info("Información del usuario mediate SecurityContextHolder: " + user2.toString()); post.setAuthor(activeUser); postService.create(post); return "redirect:/admin/posts/all"; } 定义在这里:

@CurrentUser

执行控制器时,package services.security; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.security.core.annotation.AuthenticationPrincipal; /** * * @author sergio */ @Target({ElementType.PARAMETER, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal public @interface CurrentUser {} 获取的用户为空,@AuthenticationPrincipal获得的用户包含所有信息:

SecurityContextHolder

据我所知,使用2016-12-10 19:37:52 INFO PostController:62 - Información del usuario mediate @CurrentUser: User{id=null, username=null, passwordClear=null, confirmPassword=null, password=null, email=null, enabled=true, fullName=null, posts=[]} 2016-12-10 19:37:52 INFO PostController:63 - Información del usuario mediate SecurityContextHolder: User{id=1, username=sergio11, passwordClear=null, confirmPassword=null, password=$2a$10$LJvYTNacIvqZWDQWjF7xaeheK1MrF.FkXxovb2QgcF2CMudA1mM/., email=sss4esob@gmail.com, enabled=true, fullName=Sergio Sánchez Sánchez, posts=[]} 已在上下文中启用@EnableWebSecurity的解析器参数

我的Spring安全配置是:

@AuthenticationPrincipal

我正在使用 Spring Security 4.2.0.RELEASE

谢谢:)

2 个答案:

答案 0 :(得分:1)

此问题是因为来自DelegatingFlashMessagesConfiguration的{​​{1}}急切地初始化handlerExceptionResolver,这会阻止在Spring MVC构造DispatcherServlets自定义参数解析器之前注册AuthenticationPrincipalArgumentResolver。

因此我改变了:

CustomFlashMessagesConfigurer

对于另一个:

@Configuration
@EnableWebMvc
@ComponentScan(value = { "controllers", "services", "listeners" })
@Import(value = { ThymeleafConfig.class, i18nConfig.class, CustomFlashMessagesConfigurer.class })
public class WebConfig extends WebMvcConfigurerAdapter

这解决了这个问题。

答案 1 :(得分:0)

错误信息非常清楚。您的CustomerUserDetails对象听起来像是一个实体对象。在其中添加默认构造函数:

public class CustomUserDetails extends User implements UserDetails {
//..
   public CustomUserDetails(){}
//..
}