tocken机制

cookie-session机制的缺点

  • 如果web服务器做了负载均衡,那么下一个操作请求到了另一台服务器的时候session会丢失,因为session默认存放在一个服务器内存中。
  • 每次认证用户发起请求时,服务器需要去创建一个记录来存储信息。过多的Session存储在服务器内存中,会对服务器造成压力。
  • 如果浏览器不支持cookie,cookie-session机制便无法使用。
  • cookie存在跨域的限制。

tocken机制流程

  • 当用户登录成功之后, 服务器端就会通过指定算法生成一个 token,过期时间48h,可以将token 存储在redis,再将这个token值返回给客户端;
  • .客户端拿到 token 值之后,进行保存;
  • 当客户端调用接口请求数据时,就会携带token值发送给服务器;
  • 服务器接收到客户端的请求之后,会取出token值与保存在redis中的token值做对比。
  • 如果token对比成功,说明用户处于登录状态,否则表示登录状态失效,需要用户重新登陆。用户每次重新登陆会刷新token的过期时间。

tocken的优点

  • session是需要空间进行存储的,如果是多服务器session需要同步信息,但是token在服务器是可以不需要存储用户信息的。
  • token可以使用浏览器的localStorge等,APP也可以使用自带数据库存储字符串。且不会出现cookies出现跨域问题。
  • token可以用JWT来携带部分不太敏感的信息比如用户ID等,服务器只要解密token即可使用部分信息。
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用如下代码获取Java中的token: ``` import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.Base64; public class TokenUtil { public static String getToken(String clientId, String clientSecret) { String plainCreds = clientId + ":" + clientSecret; byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.UTF_8); String base64Creds = Base64.getEncoder().encodeToString(plainCredsBytes); String tokenUrl = "http://your.auth.server/oauth/token"; //your auth server url String grantType = "client_credentials"; //the type of grant String scope = "read write"; //the scope of the access token String url = tokenUrl + "?grant_type=" + grantType + "&scope=" + scope; URL obj; InputStream in = null; try { obj = new URL(url); URLConnection conn = obj.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Authorization", "Basic " + base64Creds); in = new BufferedInputStream(httpConn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } } ``` 该方法使用了Basic认证方式,将client id和client secret进行base64编码后传递给token server。同时,也传递了`grant_type`和`scope`参数,用于指定授权方式和访问权限范围。在token server验证完成后,会返回一个JSON格式字符串,里面包括了access_token等信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值