使用Spring安全性从Spring中的控制器访问UserDetails对象

时间:2017-12-21 15:22:17

标签: spring spring-mvc spring-security

我想从会话中访问一些用户详细信息。我通过覆盖 loadUserByUsername(String username)方法使用Spring安全性和自定义身份验证。

我正在返回一个用户,并希望从我的控制器中访问它。我尝试了主要对象,但我无法访问 ESecurityUser 的companyId字段宾语。

任何帮助将不胜感激..

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    ESecurityUser user = new ESecurityUser();
    user.setUsername("hello");
    user.setPassword("world");
    user.setCompanyId(199);

    Set<EAuthority> authorities = new HashSet<EAuthority>();
    EAuthority authority = new EAuthority();
    authority.setAuthority("ROLE_ADMIN");
    authorities.add(authority);

    user.setAuthorities(authorities);;

    return user;
}

示例控制器代码

@RequestMapping("")
    public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
            Model model,Principal principal) {

        //What to write here so that i can access to authenticated user`s companyId field..

        return "Test";
    }

3 个答案:

答案 0 :(得分:1)

您可以使用注释@AuthenticationPrincipal直接访问ESecurityUser

@RequestMapping("")
public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
        Model model, @AuthenticationPrincipal ESecurityUser principal) {
    principal.getCompanyId();
    return "Test";
}

答案 1 :(得分:1)

你不远......

SpringMVC机制传递给控制器​​方法的Principal是标识用户的Authentication标记。您必须使用其getDetails()方法提取您从ESecurityUser

返回的loadUserByUsername

您的代码可能会变成:

@RequestMapping("")
    public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper,
            Model model,Principal principal) {

        ESecurityUser user = (ESecurityUser) ((Authentication) principal).getDetails();

        // stuff...
        return "Test";
}

答案 2 :(得分:0)

ESecurityUser e = (ESecurityUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

这对我有用..