java http json token,用于Java的JWT(JSON Web Token)库

I am working on a web application developed using Java and AngularJS and chose to implement token authentication and authorization.

For the exercise purpose, I've come to the point where I send the credentials to the server, generate a random token store it and send it back to the client.

At every request to the server I'm attaching the token in the header and it works perfectly.

For the authentication point of view is perfect and wouldn't need more.

However, I now want to keep track of the user type (admin, regular user...), as well as it's id, or any other unique field; as I understood I have to encrypt that in the token that I'm sending back to the client during the log in action. Is that correct?

Is there any JWT library that you used and can generate, encrypt and decrypt such tokens?

A link to the library's API and Maven dependency would be much appreciated.

Thanks

解决方案

If anyone in the need for an answer,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 JSON Web Token (JWT) 实现登录的 Java 代码如下: 首先,需要引入以下依赖: ```xml <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 然后,可以编写一个 `JwtUtil` 类来实现 JWT 的生成和解析: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import java.security.Key; import java.util.Date; public class JwtUtil { private static final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); public static String generateToken(String subject, long expirationTimeMillis) { Date now = new Date(); Date expirationDate = new Date(now.getTime() + expirationTimeMillis); return Jwts.builder() .setSubject(subject) .setIssuedAt(now) .setExpiration(expirationDate) .signWith(key) .compact(); } public static String parseToken(String token) { Claims claims = Jwts.parserBuilder() .setSigningKey(key) .build() .parseClaimsJws(token) .getBody(); return claims.getSubject(); } } ``` 在上面的代码中,`generateToken` 方法用于生成 JWT,接受一个 `subject` 参数表示用户 ID,和一个 `expirationTimeMillis` 参数表示过期时间(以毫秒为单位)。`parseToken` 方法用于解析 JWT,返回其中的用户 ID。 接下来,可以编写一个简单的登录接口: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class LoginController { @PostMapping("/login") public ResponseEntity<String> login(@RequestBody User user) { if (authenticate(user)) { String token = JwtUtil.generateToken(user.getId(), 86400000); return ResponseEntity.ok(token); } else { return ResponseEntity.badRequest().build(); } } private boolean authenticate(User user) { // TODO: 实现验证逻辑 return true; } } ``` 在上面的代码中,`User` 是一个简单的 Java 类,包含一个字符串类型的 `id` 属性。`login` 方法接受一个 `User` 对象作为参数,调用 `authenticate` 方法进行验证。如果验证通过,则使用 `JwtUtil.generateToken` 方法生成 JWT 并返回;否则返回错误响应。 最后,可以编写一个使用 JWT 进行身份验证的接口: ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @GetMapping("/user") public ResponseEntity<String> getUser(@RequestHeader("Authorization") String authorizationHeader) { String token = authorizationHeader.substring(7); String userId = JwtUtil.parseToken(token); // TODO: 根据用户 ID 查询用户信息并返回 return ResponseEntity.ok("User ID: " + userId); } } ``` 在上面的代码中,`getUser` 方法接受一个名为 `Authorization` 的请求头,其中包含 JWT。首先从请求头中获取 JWT,并调用 `JwtUtil.parseToken` 方法解析其中的用户 ID。然后根据用户 ID 查询用户信息并返回。 注意,在实际应用中,需要对 JWT 进行安全性考虑,比如使用 HTTPS 协议传输、设置较短的过期时间、使用更复杂的密钥等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值