[英]How JSON web token works in Spring boot?
I want to write REST service and I choose JWT for securing this rest service. 我想编写REST服务,并且选择JWT来保护此Rest服务。
I declare 1 min for token, afterwards what I must do? 我声明1分钟的令牌,之后该怎么办?
I must refresh token or something else? 我必须刷新令牌或其他内容吗?
If I must refresh token, user can call service's method with this token? 如果必须刷新令牌,用户可以使用此令牌调用服务的方法吗?
Token code 代币代码
package com.example.demo.config;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.ArrayList;
import java.util.Arrays;
public class TokenAuthenticationService {
//field of conf
static final long EXPIRATIONTIME = 60_000; // 1 min
static final String SECRET = "msg";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
//generate token
public static void addAuthentication(HttpServletResponse res, Authentication auth) {
String concattedRoles = "";
for (GrantedAuthority ga : auth.getAuthorities()) {
if (!"".equals(concattedRoles))
concattedRoles += "," + ga.getAuthority();
else
concattedRoles += ga.getAuthority();
}
String JWT = Jwts.builder().setSubject(auth.getName()).claim("roles", concattedRoles)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET).compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}
//get token from request header.
public static Authentication getAuthentication(HttpServletRequest request) {
try {
System.out.println("(Authentication getAuthentication(HttpServletRequest request)");
String token = request.getHeader(HEADER_STRING);
System.out.println("token=>"+token);
if (token != null) {
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
String user = claims.getSubject();
String roles = (String) claims.get("roles");
if(claims.getExpiration().before(new Date(System.currentTimeMillis())))
throw new Exception(); //Here trow exception.
List<String> roleList = Arrays.asList(roles.split("\\s*,\\s*"));
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
for (int i = 0; i < roleList.size(); i++) {
System.out.println(roleList.get(i));
SimpleGrantedAuthority abv = new SimpleGrantedAuthority(roleList.get(i));
grantedAuths.add(abv);
}
System.out.println(grantedAuths);
return user != null ? new UsernamePasswordAuthenticationToken(user, null, grantedAuths) : null;
}
return null;
}catch (Exception e){
System.out.println(e);
return null;
}
}
}
How we implemented is - 我们的实施方式是-
Hope this helps. 希望这可以帮助。
Basically refresh_token
is used for giving back a valid access_token
to the user upon request. 基本上,
refresh_token
用于根据请求将有效的access_token
返还给用户。 And refresh_tokens
are usually long-lived rather than short-lived. 而且
refresh_tokens
通常是长期的,而不是短期的。
Personally, my design for securing a RESTful API is just to let them request the access_token
to my endpoint ie https://api.example.com/oauth/token
every time , I don't provide a refresh_token
because the idea for me is just to let them in into the resource, nothing else. 就我个人而言,我保护RESTful API的设计只是让他们每次都向我的端点(即
https://api.example.com/oauth/token
请求access_token
,我不提供refresh_token
因为对我来说这个想法是只是为了让他们进入资源,别无其他。 And usually, the requesting resource will not be staying for so long on a particular session. 通常,请求资源在特定会话中不会停留太长时间。 For the other concerns of the server getting too many requests on the same user/session, you can implement a
rate-limiting
to your servers or token endpoint. 对于服务器在同一用户/会话上收到太多请求的其他问题,您可以对服务器或令牌端点实施
rate-limiting
。
I based my API security implementations on PayPal and JHipster . 我的API安全性实现基于PayPal和JHipster 。 They do not provide
refresh_tokens
to their respective RESTful API implementations, because in the end, refresh_tokens
are optional to be used, and it's just a matter of what you want to achieve upon securing your RESTful endpoints. 他们没有为各自的RESTful API实现提供
refresh_tokens
,因为最后, refresh_tokens
是可选使用的,而这只是在保护RESTful端点时要实现的问题。
For more information about refresh_token
you can these links: When to use JWT Tokens and Understanding refresh tokens . 有关
refresh_token
更多信息,您可以通过以下链接: 何时使用JWT令牌和了解刷新令牌 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.