1

ユーザー名とパスワードを含むuserIdなどのCookieに他のユーザー情報を保存したい。spring securityのremember me機能を使用すると、Cookieからユーザー名を取得できます。

spring-security.xml では、カスタムの userDetailService を使用しており、次のように実装しました

 <http>
 ......   
 <logout invalidate-session="true" 
        logout-success-url="/" 
        logout-url="/logout.htm"/>
 <remember-me user-service-ref="myUserDetailsService" key="89dqj219dn910lsAc12" token-validity-seconds="864000"/>
</http>

<authentication-manager>
        <authentication-provider user-service-ref="myUserDetailsService">
                <password-encoder ref="myEnocdePassword" >
                    <salt-source user-property="username"/>
                </password-encoder>
        </authentication-provider>
</authentication-manager>   
<beans:bean id="myEnocdePassword" class="com.mycom.myproject.utility.MyEnocdePassword" />

MyUserDetailService.java には次のようなコードがあります

  @Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {

    try {

    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    com.mycom.myproject.db.mybatis.model.User domainUser = userService.getUserByName(username);




    return  new User(
            domainUser.getUsername(), 
            domainUser.getPassword(),
            enabled,
            accountNonExpired,
            credentialsNonExpired,
            accountNonLocked,
            getAuthorities(domainUser.getRoleId);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

私のコントローラークラスでは、次を使用してユーザー名を取得できます

   String name = SecurityContextHolder.getContext().getAuthentication()
            .getName();

しかし、userId などの Cookie に他のユーザーの詳細を保存したいと考えています。どうすればそれができますか?userDao(name) でユーザー情報を取得し、手動でユーザー情報を Cookie に保存する必要がありますか?

4

2 に答える 2

3

この場合、Cookie を使用して何もする必要はありません。

ユーザーがログインしている限り (ログイン方法に関係なく、ログインフォームまたは「remember me」を使用して) 、Spring Security がUserDetailsそのユーザーにアクセスできます。SecurityContext

したがって、必要な情報を に入れUserDetails(必要に応じUserDetailsService.loadUserByUsername()て の独自のサブクラスを使用しますUserDetails)、次の方法でアクセスするだけSecurityContextです。

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
    Object principal = auth.getPrincipal();  
    if (principal instanceof UserDetails) {
        UserDetails user = (UserDetails) principal;
        ... // User is logged in, now you can access its details
    }
}

つまり、Spring Security がアクティブなセッションなしで、remember me Cookie を含むリクエストを受信すると、Cookie からのユーザー ID を使用して、UserDetailsそれらをロードしてSecurityContext(および新しく作成されたセッション セッションに) 配置します。後でこれらの詳細にアクセスできます SecurityContext

于 2012-09-05T11:41:21.567 に答える
0

通常、Cookie は既に存在します。値をセッションに保存できます。

値を長期間保存したい場合は、Session-Passivation を使用できます。

于 2012-09-05T09:49:03.557 に答える