programing

JSPEL 식에서 Spring 보안 주체 가져오기

itmemos 2023. 8. 15. 10:48
반응형

JSPEL 식에서 Spring 보안 주체 가져오기

Spring MVC와 Spring Security 버전 3.0.6을 사용하고 있습니다.풀어주다.JSP에서 사용자 이름을 가져오는 가장 쉬운 방법은 무엇입니까?또는 사용자가 로그인했는지 여부도 마찬가지입니까?몇 가지 방법을 생각해 볼 수 있습니다.

스크립틀릿

다음과 같은 스크립트를 사용하여 사용자가 로그인했는지 확인:

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

하지만 저는 스크립틀릿을 사용하는 것을 좋아하지 않습니다. 그리고 저는 이것을 사용하고 싶습니다.<c:if>태그. 페이지 속성으로 다시 넣어야 합니다.

보안 컨텍스트 홀더 사용

는 제 에서 할 수 .@Controller그리고 그것을 모델에 붙입니다.하지만 모든 페이지에 이 정보가 필요하기 때문에 모든 컨트롤러에 이 논리를 추가할 필요는 없습니다.

더 깨끗한 방법이 있을 것 같은데요

태그: Spring <sec:authentication property="principal.username" />

http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html

기록되었는지 확인할 수 있습니다.

<sec:authorize access="isAuthenticated()"> 

c:if 대신에

스레드에 다른 답변이 있는 것은 알지만 사용자 인증 여부를 확인하는 방법에 대한 답변은 없습니다.그래서 저는 제 코드가 어떻게 생겼는지 공유하고 있습니다.

프로젝트에 태그 lib 포함:

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

그런 다음 다음을 추가하여 현재 범위의 사용자 개체를 만듭니다.

<sec:authentication var="user" property="principal" />

그러면 추가하면 쉽게 사용자 이름을 표시할 수 있습니다.프로젝트에서 스프링 보안을 다른 클래스로 변경하는 방법으로 구현하지 않은 경우 '주체' 개체는 일반적으로 문자열 유형입니다.

<sec:authorize access="hasRole('ROLE_USER') and isAuthenticated()">
${user}
</sec:authorize>

사용자 역할을 확인하는 데 도움이 되었으면 합니다.

메이븐을 사용하는 경우 이 스레드에서 Christian Vielma가 언급한 대로 종속성 태그를 추가합니다.

감사합니다!

Spring Security Tag Lib - 3.1.3과 같이 사용할 수 있습니다.풀어주다

<sec:authentication var="principal" property="principal" />

그리고 나서:

${principal.username}

나는 메이븐을 사용하고 있어서 이것을 pom.xml에 추가하는 taglibs 라이브러리를 추가해야 했습니다.

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

그리고 내 jsp에서 다음과 같이 덧붙였습니다.

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

그리고:

<sec:authentication property="principal" />

principal.username계속해서 나에게 오류를 주었습니다(아마도 내가 만든 방법일 것입니다).UsernamePasswordAuthenticationToken개체, 확실하지 않음).

저는 alphx에 동의합니다, 저는 심지어 그의 대답에 투표했습니다.

하지만 다른 접근법이 필요하다면 Spring Roose가 사용하는 접근법을 사용할 수 있습니다.

SecurityContextHolderAwareRequestFilter가 있는 경우 SecurityContext에 액세스하는 요청 래퍼를 사용하여 표준 서블릿 API 보안 메서드를 제공합니다.

이 필터는 에 등록되어 있습니다.<http>Spring Security 네임스페이스의 태그입니다.또한 FilterChainProxy의 보안 필터 체인에 등록할 수 있습니다(애플리케이션 Context-security.xml의 선언된 빈에 참조를 추가하기만 하면 됩니다).

그런 다음 Roo처럼 보안 서블릿 API에 액세스할 수 있습니다(조건부 로그아웃 링크가 작성되는 방법을 보려면 footer.jspx를 찾으십시오).

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

생각합니다<sec:authentication property="principal.username" />반환된 형식이 Object이기 때문에 항상 작동하지는 않습니다. 즉, UserDetail(위에서 작동하는 사용자 세부 정보), String 또는 기타 형식일 수 있습니다.

JSP 페이지에 사용자 이름을 표시하기 위해 내가 더 신뢰할 수 있는 것은 사용하는 것입니다.${pageContext.request.userPrincipal.name}.

를 사용하여 String을 반환합니다.

이것은 사용자가 로그인했는지 여부와 상관없이 작동하며 익명 인증을 사용할 때 작동합니다.

<sec:authorize access="isAuthenticated()">
    <sec:authentication property="principal.username" var="username" />
</sec:authorize>
<sec:authorize access="!isAuthenticated()">
    <sec:authentication property="principal" var="username" />
</sec:authorize>

나중에...

Hello ${username}

j 태그:

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

sec 태그:

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

pom.xml에 추가:

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

페이지에 추가:

<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>

Spring Security 3.0.x는 기본적으로 를 설치하여 다음을 수행할 수 있는 것으로 알고 있습니다.Authentication전화로 반대합니다.HttpServletRequest.getUserPrincipal()그리고 당신은 또한 전화로 역할을 질의할 수 있습니다.HttpServletRequest.isUserInRole().

주 특성 사용에 액세스하려면 먼저 특성에 대한 변수를 만듭니다.

<sec:authentication property="principal.attributes" var="principalAttr"/>

그런 다음 이 맵을 사용하여 속성 키 이름으로 값을 검색할 수 있습니다.

${principalAttr.get("given_name")}

메이븐 종속성 목록에 스프링 보안 태그립을 추가하는 것을 잊지 마십시오.

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

추가 필드 모바일이 있는 내 사용자 클래스:

 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;
    }

}

사용자 세부 정보 서비스 Impl.java에서 이 사용자 지정 사이트 사용자 개체를 채웠습니다.

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;
}

다음과 같이 접근할 예정입니다.

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

언급URL : https://stackoverflow.com/questions/9048995/get-spring-security-principal-in-jsp-el-expression

반응형