Cannot deserialize session attribute [SPRING_SECURITY_CONTEXT] for session的解决办法

邓毅
2023-12-01

在SpringBoot整合SpringSecurity,并启用devtools的时候,会抛出如下异常:

Cannot deserialize session attribute [SPRING_SECURITY_CONTEXT] for session [xxx]

提示是无法序列化session,根据stackoverflow上的答案

只要在你序列化自定义的UserDetials类中传入的实体类就行:

package com.example.demo.config.security;

import com.example.demo.vo.SecurityUserVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;

/**
 * 功能描述:自定义spring security中,用于验证的用户实体类
 *
 * @author liuchaoyong
 * @version 1.0
 * @date 2019-02-21 21:38
 */
public class MyUserDetails implements UserDetails {

    private SecurityUserVO securityUserVO;

    public MyUserDetails(SecurityUserVO securityUserVO) {
        this.securityUserVO = securityUserVO;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return securityUserVO.getPassword();
    }

    @Override
    public String getUsername() {
        return securityUserVO.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return securityUserVO.getIsLocked().equals((byte)0);
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return securityUserVO.getIsEnable().equals((byte)1);
    }
}
package com.example.demo.vo;

import lombok.Data;

import java.io.Serializable;

/**
 * 功能描述:
 *
 * @author liuchaoyong
 * @version 1.0
 * @date 2019-03-06 17:21
 */
@Data
public class SecurityUserVO implements Serializable {


    private Long id;

    private String username;

    private String password;

    private Byte isLocked;

    private Byte isEnable;

}

 

 类似资料: