栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于SpringBoot实现用户身份验证工具

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于SpringBoot实现用户身份验证工具

session失效时间

 在Tomcat上,session的默认有效时间是30分钟。也可以通过配置文件修改session的有效时间。

 1)修改web.xml

 
 
  1 

2).yml文件

server.session.cookie.http-only= #是否开启Httponly 
server.session.timeout = #会话超时(秒) 

使用过滤器获取session进行身份验证(未全部测试,慎用)

1)新建Filter

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.web.servlet.ServletComponentScan; 
import org.springframework.context.ApplicationContext; 
import org.springframework.stereotype.Component; 
import org.springframework.web.context.support.WebApplicationContextUtils; 
import javax.servlet.*; 
import javax.servlet.annotation.WebFilter; 
import javax.servlet.http.HttpServletRequest; 
import java.io.IOException; 
@Component 
@ServletComponentScan//让@WebFilter起作用 
@WebFilter(urlPatterns = " 
  public UserTypeEnum getUserAuthentication(HttpSession session){ 
    //获取session中的用户信息记录 
    Object userType = session.getAttribute(configProperties.getUserTypeKey()); 
    //获取session中记录的用户类型 
    if(userType != null && userType instanceof UserTypeEnum) { 
      return (UserTypeEnum)userType; 
    } 
    return null; 
  } 
   
  public void setUserAuthentication(HttpSession session,UserTypeEnum userType){ 
    session.setAttribute(configProperties.getUserTypeKey(),userType); 
  } 
} 

3)配置文件SessiionKeyConfig.properties

user_type_key = userTypeKey 

4)配置读取文件SessionKeyConfigProperties.class

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource; 
import org.springframework.stereotype.Component; 
@Configuration 
@PropertySource("classpath:config/SessiionKeyConfig.properties") 
@Component 
public class SessionKeyConfigProperties { 
  @Value("${user_type_key}") 
  private String userTypeKey; 
  public String getUserTypeKey() { 
    return userTypeKey; 
  } 
  public void setUserTypeKey(String userTypeKey) { 
    this.userTypeKey = userTypeKey; 
  } 
} 

5)Enum类

public enum UserTypeEnum { 
  ADMIN, 
  USER 
} 

注:本文删除了一些package信息及部分import信息。Enum类和配置类的内容请根据项目需求及数据字典自行修改。

总结

以上所述是小编给大家介绍的基于SpringBoot实现用户身份验证工具,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141232.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号