cómo condicionalmente mostrar jsp contenido a los usuarios registrados con Spring security

StackOverflow https://stackoverflow.com/questions/1638170

Pregunta

Quiero mostrar el contenido de cualquier usuario que se registra en y para ocultar si no ha iniciado sesión.Estoy usando jsp y spring security.

Obviamente un hogar crecido solución es fácil de hacer.Pero lo que es el más limpio estándar manera de lograr esto?

La primavera etiquetas de seguridad no parecen tener buena manera que permita la incorporación de nuevas funciones en el futuro.

¿Fue útil?

Solución

He tenido éxito con los siguientes:

    <sec:authorize ifAnyGranted="ROLE_ANONYMOUS">
        <td><a href="<c:url value="/login.htm"/>">Login</a></td>
    </sec:authorize>
    <sec:authorize ifNotGranted="ROLE_ANONYMOUS">
        <td><a href="<c:url value="/j_spring_security_logout"/>">Logout</a></td>
    </sec:authorize>

Nuevos roles puede ser añadido sin afectar a la lógica aquí.


Para llevar esta respuesta hasta la fecha con Spring Security 3, utilizando el isAnonymous() y isAuthenticated() expresiones que han funcionado bien en combinación hasta ahora para lograr la misma cosa.He aquí un ejemplo:

<sec:authorize access="isAnonymous()">
    <form method="POST" action="<c:url value='j_spring_security_check'/>">
        Username: <input name="j_username" type="text" value="${SPRING_SECURITY_LAST_USERNAME}" /> 
        Password: <input name="j_password" type="password" /> 
        <input type="submit" value="Sign in" />
    </form>
</sec:authorize>
<sec:authorize access="isAuthenticated()">
    <a href="<c:url value="/j_spring_security_logout" />">Logout</a>
</sec:authorize>

Otros consejos

La versión actual (3.1 quizás incluso anterior) admite parámetros var para guardar el resultado en un atributo. Por eso puedes codificar lo siguiente:

<sec:authorize var="loggedIn" access="isAuthenticated()" />
<c:choose>
    <c:when test="${loggedIn}">
        You are loged in
    </c:when>
    <c:otherwise>
        You are logged out
    </c:otherwise>
</c:choose>

Puede usar Spring EL en la etiqueta <sec:authorize />, así:

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

<sec:authorize access="isAuthenticated()">
   YES, you are logged in!
</sec:authorize>

¿Qué tal esto? - Compatible con Spring 2.5 ;-)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

<security:authorize ifAllGranted="ROLE_USER">
   Welcome <%= request.getUserPrincipal().getName() %>
   <a href="<c:url value="/j_spring_security_logout"/>">Logout</a><br/>
</security:authorize>

¿Qué tal:

<%@ taglib uri="http://acegisecurity.org/authz" prefix="authz" %>

<c:set var="authenticated" value="${false}"/>
<authz:authorize ifAllGranted="ROLE_USER">
    <c:set var="authenticated" value="${true}"/>
</authz:authorize>

<c:if test="${authenticated}">
<!-- your secure content here -->
</c:if>

el más simple que usé para codificar esto ...

<%
if (request.getRemoteUser()== null) {%>  
    <!-- put public-only information-->
<%}%>

Así es como estoy haciendo esto:

<%@ page import="org.springframework.security.context.SecurityContextHolder" %>

<c:if test="<%=SecurityContextHolder.getContext().getAuthentication() != null %>">
    <!-- your secure content here -->
</c:if>

Avísame si esto también funciona para ti ...

-aj

puede usar esto dentro de la etiqueta de seguridad de primavera jsp

request.getUserPrincipal().getName()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top