如何在Java中检查令牌是否过期?

huangapple go评论92阅读模式
英文:

How to check if token expired in java?

问题

我有一个用户,拥有以下属性:id,用户名,密码,以及一个日期类型的tokenExpires。当我生成一个令牌时,我会得到一个字符串。如何检查令牌是否未过期?

英文:

I have user which have: id, username,password, tokenExpires which is Date. When i generate token i generate a string, how to check if token is not expired?

答案1

得分: 2

## java.time

在处理日期和时间方面请使用现代的 Java 日期和时间 APIjava.time

```java
public class User {
    private String username;
    private String password;
    private Instant tokenExpires;
    
    // 构造函数、获取器、设置器
    
    public boolean isTokenExpired() {
        return !Instant.now().isBefore(tokenExpires);
    }
}

现代替代Date的是Instant。它代表一个时间点。

如果你不能修改User类,并且getTokenExpires()返回一个旧式的Date对象:

Instant tokenExpires = yourUser.getTokenExpires().toInstant();
if (Instant.now().isBefore(tokenExpires)) {
    System.out.println("Token has not expired");
} else {
    System.out.println("Token has expired");
}

链接: Oracle 教程:日期时间,介绍如何使用 java.time。


<details>
<summary>英文:</summary>

## java.time

Do use java.time, the modern Java date and time API, for your date and time work.

    public class User {
    	private String username;
    	private String password;
    	private Instant tokenExpires;
    	
    	// constructor, getters, setters
    	
    	public boolean isTokenExpired() {
    		return ! Instant.now().isBefore(tokenExpires);
    	}
    	
    }

The modern replacement for a `Date` is an `Instant`. It’s a point in time.

If you cannot change the `User` class and `getTokenExpires()` returns an old-fashioned `Date` object:

		Instant tokenExpires = yourUser.getTokenExpires().toInstant();
		if (Instant.now().isBefore(tokenExpires)) {
			System.out.println(&quot;Token has not expired&quot;);
		} else {
			System.out.println(&quot;Token has expired&quot;);
		}

**Link:** [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.


</details>



# 答案2
**得分**: 0

核心逻辑是将当前日期与令牌日期进行比较。如果当前日期大于令牌日期,则令牌已过期。以下是执行相同操作的代码示例。

```java
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  Date date1 = sdf.parse("2009-12-31");
  Date date2 = sdf.parse("2010-01-31");
  
  if (date1.compareTo(date2) >= 0) 
      System.out.println("Token not expired");
  else if (date1.compareTo(date2) < 0) 
      System.out.println("Token expired");
        

参考链接: 如何在Java中比较日期

英文:

The core logic behind it will be to compare the present date with the token date. If the present date is greater than the token date then the token has expired. Here is a code example of doing the same.

  SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;);
  Date date1 = sdf.parse(&quot;2009-12-31&quot;);
  Date date2 = sdf.parse(&quot;2010-01-31&quot;);
  
  if (date1.compareTo(date2) &gt;= 0) 
      System.out.println(&quot;Token not expired&quot;);
  else if (date1.compareTo(date2) &lt; 0) 
      System.out.println(&quot;Token expired&quot;);
        

Reference Link : How to compare dates in Java

答案3

得分: 0

也许使用JWT会更好。您可以定义令牌的有效期,并且用户数据可以存储为声明。这是一个示例教程:https://developer.okta.com/blog/2018/10/31/jwts-with-java
我认为这是一个更好的解决方案,因为您不需要实现所有功能。
在您当前的实现中,有机会某些用户会修改有效载荷。
但请记住,像密码之类的数据不应包含在JWT中,因为任何拥有令牌的人都可以读取所有声明。

英文:

Maybe it's better to use JWT. You can define how long the token should be valid and data about the user can be stored as claims. Here is example tutorial: https://developer.okta.com/blog/2018/10/31/jwts-with-java
I think it's a better solution because you don't need to implement all features.
On your current implementation is a chance that some user will modify the payload.
But remember that data like passwords should not be included to JWT because anyone who has the token can read all claims.

huangapple
  • 本文由 发表于 2020年4月6日 22:22:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/61062003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定