Get Spring Security Principal in JSP EL expression

2020-02-07 18:10发布

I am using Spring MVC and Spring Security version 3.0.6.RELEASE. What is the easiest way to get the user name in my JSP? Or even just whether or not the user is logged in? I can think of a couple ways:

1. Using a scriptlet

Using a scriptlet like this to determine if the user is logged in:

<%=org.springframework.security.core.context.SecurityContextHolder.getContext()
    .getAuthentication().getPrincipal().equals("anonymousUser")
    ? "false":"true"%>

I'm not a fan of using scriptlets, though, and I want to use this in some <c:if> tags, which requires putting it back as a page attribute.

2. Using SecurityContextHolder

I could again use SecurityContextHolder from my @Controller and put it on the model. I need this on every page, though, so I'd rather not have to add this logic in every one of my Controllers.

I suspect there's a cleaner way to do this...

10条回答
smile是对你的礼貌
2楼-- · 2020-02-07 18:34

I was using Maven so I had to add the taglibs library adding this to the pom.xml

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

Then in my jsp added:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

And:

<sec:authentication property="principal" />

principal.username kept giving me errors (maybe is the way I created the UsernamePasswordAuthenticationToken object, not sure).

查看更多
爷的心禁止访问
3楼-- · 2020-02-07 18:34

1) MY CUSTOM USER CLASS with extra field mobile:

 public class SiteUser extends User {

    public SiteUser(String username, String password, Collection<? extends GrantedAuthority> authorities,
            String mobile) {
        super(username, password, true, true, true, true, authorities);
        this.mobile = mobile;
    }

    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

}

2) IN MY UserDetailsServiceImpl.java I POPULATED THIS CUSTOM SiteUser object.

public SiteUser loadUserByUsername(String username)  {
        UserInfoVO userInfoVO = userDAO.getUserInfo(username);
        GrantedAuthority authority = new SimpleGrantedAuthority(userInfoVO.getRole());

        SiteUser siteUser = new SiteUser(userInfoVO.getUsername(), userInfoVO.getPassword(),
                Arrays.asList(authority), userInfoVO.getMobile());

        return siteUser;
}

3) AND IN VIEW I AM ACCESSING IT AS:

< a href="#" th:text="${#httpServletRequest.userPrincipal.principal.mobile}">

查看更多
地球回转人心会变
4楼-- · 2020-02-07 18:40

I agree with alephx, I even voted his answer.

But if you need another approach, you could use the one that Spring Roo uses.

If you have the SecurityContextHolderAwareRequestFilter, it provides the standard servlet API security methods, using a request wrapper which accesses the SecurityContext.

This filter is registered with the <http> tag from the Spring Security namespace. You can also register it in the FilterChainProxy's security filter chain (just add the reference to a declared bean in your applicationContext-security.xml)

Then, you can access the security servlet API as Roo does (find the footer.jspx to see how a conditional logout link is written)

  <c:if test="${pageContext['request'].userPrincipal != null}">
<c:out value=" | "/>
...

查看更多
Fickle 薄情
5楼-- · 2020-02-07 18:44

j tag is:

<%@taglib prefix="j" uri="http://java.sun.com/jsp/jstl/core" %>

sec tag is:

<%@taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

Add to pom.xml:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>3.1.3.RELEASE</version>
</dependency>

Add to the page:

<sec:authentication var="principal" property="principal"/>
<j:choose>
    <j:when test="${principal eq 'anonymousUser'}">
          NOT AUTHENTICATED
    </j:when>
    <j:otherwise>
          AUTHENTICATED
    </j:otherwise>
</j:choose>
查看更多
登录 后发表回答