【问题标题】:Show user informations in header using Spring使用 Spring 在标头中显示用户信息
【发布时间】:2019-02-01 21:43:17
【问题描述】:

我正在使用 SpringThymeleaf,我试图在所有页面的标题中显示用户信息(用户名)。

header.html

<div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()">     
        Logged in user: <span sec:authentication="name"></span> |                   
        Roles: <span sec:authentication="principal.authorities"></span>             
        <div>
            <form action="#" th:action="@{/logout}" method="post">                  
                <input type="submit" value="Logout" />
            </form>
        </div>
    </div>

但它没有显示任何东西

【问题讨论】:

    标签: spring spring-boot spring-security thymeleaf


    【解决方案1】:

    将依赖项添加到适当版本的org.thymeleaf.extras:thymeleaf-extras-springsecurity4

    然后将xmlns添加到你的html中

    <html xmlns:th="http://www.thymeleaf.org"
                xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    

    你可以做到

    <div th:text="${#authentication.name}">
        The value of the "name" property of the authentication object should appear here.
    </div>
    

    更多关于Spring Security Integration module的信息

    【讨论】:

    • 它显示以下错误Property or field 'name' cannot be found on null
    • 表示身份验证对象为空..当此标题页加载时,您能否验证身份验证对象是否为空
    • 我该怎么做?!?
    • 经过多次尝试 hasAuthority('ADMIN')hasRole('ADMIN')sec:authentication="name" 不起作用,输出没有显示任何想法?!?
    【解决方案2】:

    这个问题的解决方案:

    第一步:创建一个 CommunAdviceController

    public class CommunAdviceController {
    
    @Autowired
    UtilisateurRepository utilisateurRepository;
    
    @ModelAttribute("nomEtPrenom")
    public String nomEtPrenomUtilisateur() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Utilisateur util = utilisateurRepository.findByEmail(authentication.getName()) ;    
        if( util != null) {         
            return util.getUsername();
        }else {
        return "Anonyme";
        }
    }
    

    }

    请注意,在我的情况下,我将用户的邮件地址设为getUsername

    STEP 2 : 在 HTML 中调用方法

    <a href ="#" th:text="${nomEtPrenom}" class="nav-link dropdown-toggle"  id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">      
    

    任务完成了。

    希望它对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2016-12-27
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多