持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情
什么是认证
简单来说,就是对于需要登陆之后才能访问的接口进行访客的身份认证,这里是通过JWT携带用户信息进行认证工作的。
什么是授权
用户的身份是不同的,并不是每个用户都可以访问所有的接口,需要对用户的权限进行校验,对于没有相应权限的用户,进行禁止访问。
怎么实现认证与授权
引入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
使用JWT技术
将用户身份加密之后作为令牌返回给客户端,同时规定失效时间来限制用户登录时长,过期后需要重新登录,保证登录的安全性。
这里我们就需要一个工具类来创建加密的JWT,以及对JWT进行解析和验证。
配置文件
首先在配置项中,添加对应的配置信息,通过@Value的方式在代码中进行引用。
emos:
jwt:
#密钥
secret: abc123456
#令牌过期时间(天)
expire: 5
#令牌缓存时间(天数)
cache-expire: 10
创建JWT工具类
@Component
@Slf4j
public class JwtUtil {
//密钥
@Value("${emos.jwt.secret}")
private String secret;
//过期时间(天)
@Value("${emos.jwt.expire}")
private int expire;
public String createToken(int userId) {
Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, expire).toJdkDate();
Algorithm algorithm = Algorithm.HMAC256(secret); //创建加密算法对象
JWTCreator.Builder builder = JWT.create();
String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
return token;
}
public int getUserId(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("userId").asInt();
} catch (Exception e) {
throw new EmosException("令牌无效");
}
}
public void verifierToken(String token) {
Algorithm algorithm = Algorithm.HMAC256(secret); //创建加密算法对象
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
}
}