简体   繁体   English

Spring 安全主体不适用于@PostConstruct

[英]Spring security Principal won't work with @PostConstruct

I have a managedbean which contains this function that returns the username of the logged in user:我有一个 managedbean,其中包含这个 function,它返回登录用户的用户名:

public String getConnectedUser( ){  
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null)
        return null;
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserDetails) {
        return ((UserDetails) principal).getUsername();
    } else {
        return principal.toString();
    }

I want to get the user with my DAO using the username I get from spring security.我想使用我从 spring 安全性获得的用户名让用户使用我的 DAO。 When I call it inside the @PostConstruct method it doesn't return anything.当我在 @PostConstruct 方法中调用它时,它不会返回任何内容。

    @PostConstruct
public void init() {

user = utilisateurService.getUtilisateurByLogin( getConnectedUser());

but when I call it in JSF, it shows me the correct logged in username:但是当我在 JSF 中调用它时,它显示了正确的登录用户名:

        <h:outputText
            value="Logged as : #{testMB.getConnectedUser()}" />

in conclusion: with Init function I get nothing in the view, with the JSF call I get the username, can someone help me out?总之:使用 Init function 我什么都看不到,通过 JSF 调用我得到用户名,有人可以帮我吗?

EDIT: i run some tests and it appears that the authentication is null, even tho i'm logged in编辑:我运行了一些测试,似乎身份验证是 null,即使我已登录

I think it makes sense that Spring Security principal is not available in PostConstruct.我认为 Spring 安全主体在 PostConstruct 中不可用是有道理的。

PostConstruct on DAO would have been called at the time of application startup. DAO 上的 PostConstruct 将在应用程序启动时被调用。 At that time, there would be no logged in user.那时,将没有登录用户。 But, when you browse through a JSF page, there you might have logged in and that's why Principal is available there.但是,当您浏览 JSF 页面时,您可能已经登录,这就是 Principal 可用的原因。

Spring Security Filter chain will get invoked when you visit application url.当您访问应用程序 url 时,将调用 Spring 安全过滤器链。

I suggest you to call this method during your regular DAO method calls.我建议您在常规 DAO 方法调用期间调用此方法。 If you are logged in, then Principal should be available.如果您已登录,则 Principal 应该可用。

@Repository
public class SomeDao
{

public String someDaoMethod() {
  getConnectedUser();
  ....
}
private String getConnectedUser( ){  
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication == null)
        return null;
    Object principal = authentication.getPrincipal();
    if (principal instanceof UserDetails) {
        return ((UserDetails) principal).getUsername();
    } else {
        return principal.toString();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM