Spring Security: пользовательские данные пользователя

Я новичок в Java и Spring 3 (последние 8 лет использовал в основном PHP). Я получил spring security 3 для работы со всеми userDetails и userDetailsService по умолчанию, и я знаю, что могу получить доступ к имени пользователя, вошедшего в систему, в контроллере, используя:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName(); //get logged in username

Но есть две проблемы, которые я не могу понять:

  1. Есть много других сведений о пользователе, которые я хотел бы сохранить, когда пользователь входит в систему (например, дата рождения, пол и т. д.), и чтобы они были доступны через контроллеры позже. Что мне нужно сделать, чтобы созданный объект userDetails содержал мои настраиваемые поля?

  2. Я уже вызываю "HttpSession session = request.getSession(true);" в верхней части каждого из моих методов в моем контроллере. Можно ли сохранить вошедшего в систему пользователя userDetails в сеансе при входе в систему, чтобы мне не нужно было также вызывать "Authentication auth = SecurityContextHolder.getContext().getAuthentication();" в начале каждого метода?

Security-applicationContext.xml:

<global-method-security secured-annotations="enabled"></global-method-security>     
<http auto-config='true' access-denied-page="/access-denied.html">
    <!-- NO RESTRICTIONS -->        
    <intercept-url pattern="/login.html" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/*.html" access="IS_AUTHENTICATED_ANONYMOUSLY"  /> 
    <!-- RESTRICTED PAGES -->
    <intercept-url pattern="/admin/*.html" access="ROLE_ADMIN" />
    <intercept-url pattern="/member/*.html" access="ROLE_ADMIN, ROLE_STAFF" />

    <form-login login-page="/login.html"
                login-processing-url="/loginProcess"
                authentication-failure-url="/login.html?login_error=1"
                default-target-url="/member/home.html" />
    <logout logout-success-url="/login.html"/>
</http>

<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="SELECT U.username, UR.authority, U.userid FROM users U, userroles UR WHERE U.username=? AND U.roleid=UR.roleid LIMIT 1" />
        <password-encoder hash="md5"/>
    </authentication-provider>
</authentication-manager>

login.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<tiles:insertDefinition name="header" />
<tiles:insertDefinition name="menu" />
<tiles:insertDefinition name="prebody" />

<h1>Login</h1>

<c:if test="${not empty param.login_error}">
    <font color="red"><c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.<br /><br /></font>
</c:if>
<form name="f" action="<c:url value='/loginProcess'/>" method="POST">
    <table>
        <tr><td>User:</td><td><input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' /></td></tr>
            <tr><td>Password:</td><td><input type='password' name='j_password' /></td></tr>
            <tr><td>&nbsp;</td><td><input type="checkbox" name="_spring_security_remember_me" /> Remember Me</td></tr>
            <tr><td>&nbsp;</td><td><input name="submit" type="submit" value="Login" /></td></tr>
        </table>
    </form>

<tiles:insertDefinition name="postbody" />
<tiles:insertDefinition name="footer" />
9
задан Felix 15 May 2012 в 19:42
поделиться