首页 > 其他分享 >Pig4Cloud之检验token

Pig4Cloud之检验token

时间:2022-11-24 15:25:03浏览次数:67  
标签:Pig4Cloud BearerTokenAuthenticationToken bearer request 检验 failed token response

前端校验请求

/src/page/index/index.vue

refreshToken() {
      this.refreshTime = setInterval(() => {
        checkToken(this.refreshLock, this.$store)
      }, 10000)
    }

checkToken

/**
 * 校验令牌,若有效期小于半小时自动续期
 * 
 * 定时任务请求后端接口返回实际的有效时间,不进行本地计算避免 客户端和服务器机器时钟不一致
 * @param refreshLock
 */
export const checkToken = (refreshLock, $store) => {
  const token = store.getters.access_token
  // 获取当前选中的 basic 认证信息
  let basicAuth = getStore({name: 'basicAuth'})

  if(validatenull(token) || validatenull(basicAuth)){
      return;
  }

  request({
    url: '/auth/token/check_token',
    headers: {
      isToken: false,
      Authorization: basicAuth
    },
    method: 'get',
    params: {token}
  }).then(response => {
    const expire = response && response.data && response.data.exp
    if (expire) {
      const expiredPeriod = expire * 1000 - new Date().getTime()
      console.log('当前token过期时间', expiredPeriod, '毫秒')
      //小于半小时自动续约
      if (expiredPeriod <= website.remainingTime) {
        if (!refreshLock) {
          refreshLock = true
          $store.dispatch('RefreshToken')
            .catch(() => {
              clearInterval(this.refreshTime)
            })
          refreshLock = false
        }
      }
    }
  }).catch(error => {
    console.error(error)
  })
}

流程

当用户携带token 请求资源服务器的资源时,Spring Security 拦截token,进行token 和 userdetails 匹配过程,把无状态的token 转化成具体用户

image

BearerTokenAuthenticationFilter

https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.html
作为一个OncePerRequestFilter核心逻辑在doFilterInternal中。

@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String token;
		try {
			token = this.bearerTokenResolver.resolve(request);
		}
		catch (OAuth2AuthenticationException invalid) {
			this.logger.trace("Sending to authentication entry point since failed to resolve bearer token", invalid);
			this.authenticationEntryPoint.commence(request, response, invalid);
			return;
		}
		if (token == null) {
			this.logger.trace("Did not process request since did not find bearer token");
			filterChain.doFilter(request, response);
			return;
		}

		BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken(token);
		authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));

		try {
			AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request);
			Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest);
			SecurityContext context = SecurityContextHolder.createEmptyContext();
			context.setAuthentication(authenticationResult);
			SecurityContextHolder.setContext(context);
			this.securityContextRepository.saveContext(context, request, response);
			if (this.logger.isDebugEnabled()) {
				this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authenticationResult));
			}
			filterChain.doFilter(request, response);
		}
		catch (AuthenticationException failed) {
			SecurityContextHolder.clearContext();
			this.logger.trace("Failed to process authentication request", failed);
			this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed);
		}
	}

1.拦截请求进行鉴权

BearerTokenAuthenticationFilter 拦截所有资源服务器的请求。
解析 header 或者参数中的 access_token 字段
image

根据access_token 构造出来 BearerTokenAuthenticationToken 认证对象
image

请求authenticationManager.authenticate(authenticationRequest);进行鉴权。
image

2.鉴权操作

BearerTokenAuthenticationFilter解析 Authentication: Bearer {token} 中的token,交给 OpaqueTokenAuthenticationProvider

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	if (!(authentication instanceof BearerTokenAuthenticationToken)) {
		return null;
	}
	BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication;
	OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer);
	AbstractAuthenticationToken result = convert(principal, bearer.getToken());
	result.setDetails(bearer.getDetails());
	this.logger.debug("Authenticated token");
	return result;
}
	
private OAuth2AuthenticatedPrincipal getOAuth2AuthenticatedPrincipal(BearerTokenAuthenticationToken bearer) {
	try {
		return this.introspector.introspect(bearer.getToken());
	}
	catch (BadOpaqueTokenException failed) {
		this.logger.debug("Failed to authenticate since token was invalid");
		throw new InvalidBearerTokenException(failed.getMessage(), failed);
	}
	catch (OAuth2IntrospectionException failed) {
		throw new AuthenticationServiceException(failed.getMessage(), failed);
	}
}

OpaqueTokenAuthenticationProvider 委托 OpaqueTokenIntrospector introspect 去校验 token。

PigRedisOAuth2AuthorizationService 通过token value 查询 认证中心下发令牌时 存储的用户认证信息.
image
调用RedisOAuth2AuthorizationServicefindByToken

	@Override
	@Nullable
	public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
		Assert.hasText(token, "token cannot be empty");
		Assert.notNull(tokenType, "tokenType cannot be empty");
		redisTemplate.setValueSerializer(RedisSerializer.java());
		return (OAuth2Authorization) redisTemplate.opsForValue().get(buildKey(tokenType.getValue(), token));
	}

标签:Pig4Cloud,BearerTokenAuthenticationToken,bearer,request,检验,failed,token,response
From: https://www.cnblogs.com/leepandar/p/16921943.html

相关文章

  • Pig4Cloud之登陆验证(二)发放token
    上一篇介绍了客户端认证处理,那是令牌颁发的前提。这篇开始,我们就来研究下令牌颁发。令牌颁发授权服务器提供令牌颁发接口(/oauth2/token),由客户端发起请求,授权服务器生成访......
  • 接口认证方式:Bearer Token
    因为HTTP协议是开放的,可以任人调用。所以,如果接口不希望被随意调用,就需要做访问权限的控制,认证是好的用户,才允许调用API。此文介绍下目前主流的访问权限控制/认证模......
  • token、session、cookie辨析——学生在线大例会
    http的特点我们平时使用http进行前后端的数据传输,但是http的协议是无状态的,也就是他没有记忆。比如,我自我介绍,我是前端总监吴羲勇,然后我要求在座的前端同学每人vivo50。......
  • Pig4Cloud之登陆验证(一)客户端认证处理
    前端登陆handleLogin(){this.$refs.loginForm.validate(valid=>{if(valid){this.$store.dispatch("LoginByUsername",t......
  • 数据统计与可视化复习总结(二):非参数检验、生存分析
    前面所介绍的各种检验法,是在总体分布类型已知的情况下,对其中的未知参数进行检验统称为参数检验.在实际问题中,有时我们并不能确切预知总体服从何种分布,这时就需要根据来自......
  • JWT( JSON Web Token —— JSON Web 令牌 )的学习笔记
    一、跨域认证的问题互联网服务离不开用户认证。一般流程是下面这样:1、用户向服务器发送用户名和密码。2、服务器验证通过后,在当前对话(session)里面保存相关数据,比如用......
  • Pig4Cloud之验证码
    登陆前端代码<template#append><divclass="login-code"><spanclass="login-code-img"@click="refreshCode......
  • cookie和session token
    面试常考①Cookie可以存储在浏览器或者本地,Session只能存在服务器②session能够存储任意的java对象,cookie只能存储String类型的对象③Session比Cookie更具有安全......
  • 登录校验封装以及token封装
    封装校验:用户名匹配:登录校验封装:导入模块:(按需导入)使用封装名称:封装token:设置-获取-删除导入token:使用token:......
  • StringTokenizer基本用法
    简介StringTokenizer是一个快速分割字符串的工具类基本用法//默认使用"\t\n\r\f"作为分隔符,将str进行分割publicStringTokenizer(Stringstr){this(str,......