SpringBoot 整合security 实现自定义Token和clientId登录及退出(二)
接上一篇
6.认证相关处理创建
登录成功 DemoAuthenticationSuccessHandler.java
/*** 用户身份验证通过处理*/
@Component
@SuppressWarnings("all")
public class DemoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {@Autowiredprivate TokenService tokenService;@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication) throws IOException, ServletException {// 取得认证用户信息UserDetailsInfo userInfo = (UserDetailsInfo) authentication.getDetails();// 设置用户返回信息UserInfoOutputDto outputDto = new UserInfoOutputDto();String username = userInfo.getUsername();Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");outputDto.setRole(userInfo.getRole());outputDto.setLoginTime(dateFormat.format(date));outputDto.setUserId(userInfo.getUserId());outputDto.setUserName(userInfo.getUsername());// 创建TokenuserInfo.setIp(ClientIdUtil.getIp(httpServletRequest));TokenInfo tokenInfo = tokenService.createToken(userInfo);outputDto.setClientId(tokenInfo.getClientId());outputDto.setAccessToken(tokenInfo.getAccessToken());ResultData data = new ResultData(1, "login successful", outputDto);Gson gson = new Gson();httpServletResponse.getWriter().write(gson.toJson(data));}
}
UserInfoOutputDto.java
/*** 用户登录返回信息*/
public class UserInfoOutputDto {private String userId;private String userName;private String role;private String clientId;private String accessToken;private String loginTime;...
登录失败 DemoAuthenticationFailureHandler.java
/*** 用户身份验证失败处理*/
@Component
public class DemoAuthenticationFailureHandler implements AuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,AuthenticationException e) throws IOException, ServletException {PermissionJsonException jsonException = new PermissionJsonException();if (e instanceof UsernameNotFoundException) {jsonException.setCode(10001);jsonException.setMsg("username not exits");} else if (e instanceof BadCredentialsException) {jsonException.setCode(10002);jsonException.setMsg("wrong password ");} else if (e instanceof DisabledException) {jsonException.setCode(10003);jsonException.setMsg("user is disabled");} else {jsonException.setCode(10004);jsonException.setMsg("error");}httpServletResponse.setContentType("application/json;charset=UTF-8");Gson gson = new Gson();httpServletResponse.getWriter().write(gson.toJson(jsonException));}
}
账号同时登录处理 DemoExpiredHandler.java
/*** 账号同时登录处理*/
@Component
@SuppressWarnings("all")
public class DemoExpiredHandler implements SessionInformationExpiredStrategy {@Autowiredprivate TokenService tokenService;@Overridepublic void onExpiredSessionDetected(SessionInformationExpiredEventsessionInformationExpiredEvent) throws IOException, ServletException {// 获取登录的token信息String clientId = sessionInformationExpiredEvent.getRequest().getHeader("clientId");TokenInfo tokenInfo = tokenService.findByClientId(clientId);// 设置账户登录信息ExpiredData expiredData = new ExpiredData();// 登录ipexpiredData.setIp(tokenInfo.getIp());SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");// 登录时间expiredData.setLoginTime(dateFormat.format(tokenInfo.getUpdateTime()));Gson gson = new Gson();sessionInformationExpiredEvent.getResponse().getWriter().write(gson.toJson(expiredData));}
}
ExpiredData.java
/*** 重复登录信息*/
public class ExpiredData {/*** 登录ip*/private String ip;/*** 登录时间*/private String loginTime;public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getLoginTime() {return loginTime;}public void setLoginTime(String loginTime) {this.loginTime = loginTime;}
}
重点来了
7.Security配置
package com.example.demo.base.config;import com.example.demo.base.common.DemoAuthenticationFailureHandler;
import com.example.demo.base.common.DemoAuthenticationProvider;
import com.example.demo.base.common.DemoAuthenticationSuccessHandler;
import com.example.demo.base.common.DemoExpiredHandler;
import com.example.demo.base.common.DemoLogoutSuccessHandler;
import com.example.demo.base.filter.SecurityFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;/*** Security配置*/
@Configuration
@SuppressWarnings("all")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Autowiredprivate DemoAuthenticationProvider demoAuthenticationProvider;@Autowiredprivate DemoAuthenticationFailureHandler failureHandler;@Autowiredprivate DemoAuthenticationSuccessHandler successHandler;@Autowiredprivate DemoLogoutSuccessHandler logoutSuccessHandler;@Autowiredprivate DemoExpiredHandler expiredHandler;/*** 验证用户密码* @param auth* @throws Exception*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(demoAuthenticationProvider);}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/favicon.ico").permitAll()// 请求需要身份认证.anyRequest().authenticated()// 配置登录页面.and().formLogin().loginPage("/nopermission")// 登录请求url.loginProcessingUrl("/login")// 身份验证成功/失败 处理.successHandler(successHandler).failureHandler(failureHandler).permitAll()// 退出登录处理.and().logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).deleteCookies("JSESSIONID").and().addFilterAt(securityFilter(), FilterSecurityInterceptor.class).exceptionHandling()// 相同账号的最大用户数.and().sessionManagement().maximumSessions(1).expiredSessionStrategy(expiredHandler);}@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/static/**");}@BeanSecurityFilter securityFilter() {return new SecurityFilter();// 这个方法才能在拦截器中自动注入查询数据库的对象}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}
代码写到这,一个实现Token验证的登录就写好了,下一篇我们可以测试一下是否成功。
SpringBoot 整合security 实现自定义Token和clientId登录及退出(二)相关推荐
- SpringBoot 整合security 实现自定义Token和clientId登录及退出(一)
1.数据库创建 user表 user_token表 2.创建对Token和用户信息操作的service及实体类 话不多说,直接上代码 TokenInfo.java /*** Token信息*/ pub ...
- springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理
介绍 本系统为springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理.页面为极简模式,没有任何渲染. 源码:https://gite ...
- SpringBoot整合AlertManager,实现自定义的告警收敛以及邮件处理,告警风暴,解决重复告警问题
SpringBoot整合AlertManager,实现自定义的告警收敛以及邮件处理,告警风暴,解决重复告警问题 需求 将传感器通过Http发送到微服务(SpringBoot项目)的警报消息,通知给对应 ...
- SpringBoot整合SpringSession以及自定义CookieSerializer和RedisSerializer详解
官方文档:https://docs.spring.io/spring-session/docs/2.2.6.RELEASE/reference/html5/#api-cookieserializer ...
- SpringBoot 整合Security——自定义表单登录
文章目录 一.添加验证码 1.1 验证servlet 1.2 修改 login.html 1.3 添加匿名访问 Url 二.AJAX 验证 三.过滤器验证 3.1 编写验证码过滤器 3.2 注入过滤器 ...
- springboot整合security(一)入门
spring security主要功能: 1.认证--是什么身份 2.授权--有哪些权限 接下来演示如何使用(基于内存): 以上是入门演示,security本质是一个过滤器链,主要有三大过滤器: 1. ...
- springboot整合security实现权限控制
1.建表,五张表,如下: 1.1.用户表 CREATE TABLE `t_sys_user` (`user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ...
- 【微服务】Spring-Boot整合Consul (自定义服务配置及健康检查)
为什么80%的码农都做不了架构师?>>> 目的 上文提到仅使用discovery包自带的注册功能进行服务注册,但是由于监控的是 /health,使用actuator实现自由度不 ...
- SpringBoot整合security的登录问题
依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring ...
最新文章
- 在react-native中使用redux框架
- git pull 默认拉取远端其他分支 问题解决
- JWT(JSON Web Token)自动延长到期时间
- 什么是控制单元?—Vecloud微云
- IEnumerableT和IQueryableT区分
- (pytorch-深度学习系列)pytorch中backwards()函数对梯度的操作
- SSM简单参数传递与获取方法
- Finalize,Dispose,SuppressFinalize
- 学习笔记:平衡树-splay
- Sound Studio for Mac - 音频编辑处理工具
- java删除指定文件后重新建立文件系统_java file 操作之创建、删除文件及文件夹...
- 微信怎样诞生:张小龙给马化腾的一封邮件
- 【非同局域网】vue调取本地后台服务解决方法
- exec与sp_executesql
- 揭秘全美第一黑客组织Anonymous(匿名者)的装备库
- pythonbmi代码_用python写一个BMI体制指数测试
- 【翻译】BKZ 2.0: Better Lattice Security Estimates 论文翻译
- 报错GENERIC_INTERNAL_ERROR(65536)处理
- 我去!三面字节跳动,竟次次败,带薪摸鱼偷刷阿里老哥的面试宝典,成功上岸!
- typec耳机知识介绍-数字耳机,模拟耳机
热门文章
- 详解LocalTime
- 女人看一次哭一次的文章
- 解决This application failed to start because it could not find or load the Qt platform plugin windows
- 七牛云对象存储中的内容无法获取外链和无法下载的解决方法
- 2、PHP环境搭建(推荐宝塔面板)
- Multisim 中缺失 HI-TECH C51-Lite Compiler的问题。
- fileupload1
- web网页设计实例作业 ——中国风的茶文化(4页) web课程设计-HTML网页制作代码
- 十大排序算法 图解 (pythonjava)
- 高端婚礼的布置技巧 8个细节不能忽略