Spring Security 强制退出指定用户的方法
应用场景
最近社区总有人发文章带上小广告,严重影响社区氛围,好气!对于这种类型的用户,就该永久拉黑!
社区的安全框架使用了spring-security和spring-session,登录状态30天有效,session信息是存在redis中,如何优雅地处理这些不老实的用户呢?
首先,简单划分下用户的权限:
- 管理员(ROLE_MANAGER):基本操作+管理操作
- 普通用户(ROLE_USER):基本操作
- 拉黑用户(ROLE_BLACK):不允许登录
然后,拉黑指定用户(ROLE_USER->ROLE_BLACK),再强制该用户退出即可(删除该用户在redis中session信息)。
项目相关依赖及配置
Maven依赖
org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-data-redis org.springframework.session spring-session-data-redis
SpringSession策略配置application.yml
#此处省略redis连接相关配置 spring: session: store-type:redis
SpringSecurity配置代码示例
@EnableWebSecurity
publicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{
@Override
protectedvoidconfigure(HttpSecurityhttp)throwsException{
http
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").hasAnyRole(RoleEnum.MANAGER.getMessage())
.anyRequest().permitAll()
.and().formLogin().loginPage("/login").permitAll()
.and().logout().permitAll()
.and().csrf().disable();
}
}
强制退出指定给用户接口
importcom.spring4all.bean.ResponseBean;
importcom.spring4all.service.UserService;
importlombok.AllArgsConstructor;
importorg.springframework.session.FindByIndexNameSessionRepository;
importorg.springframework.session.Session;
importorg.springframework.session.data.redis.RedisOperationsSessionRepository;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
@RestController
@AllArgsConstructor
publicclassUserManageApi{
privatefinalFindByIndexNameSessionRepositorysessionRepository;
privatefinalRedisOperationsSessionRepositoryredisOperationsSessionRepository;
privatefinalUserServiceuserService;
/**
*管理指定用户退出登录
*@paramuserId用户ID
*@return用户Session信息
*/
@PreAuthorize("hasRole('MANAGER')")
@GetMapping("/manager/logout/{userId}")
publicResponseBeandata(@PathVariable()LonguserId){
//查询PrincipalNameIndexName(Redis用户信息的key),结合自身业务逻辑来实现
StringindexName=userService.getPrincipalNameIndexName(userId);
//查询用户的Session信息,返回值key为sessionId
MapuserSessions=sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,indexName);
//移除用户的session信息
ListsessionIds=newArrayList<>(userSessions.keySet());
for(Stringsession:sessionIds){
redisOperationsSessionRepository.deleteById(session);
}
returnResponseBean.success(userSessions);
}
}
说明indexName为Principal.getName()的返回值。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。