学习内容:学习接口认证和shiro(Day72)
1、postman接口测试工具
2、认证接口
3、shiro权限框架
1、postman接口测试工具
(1)Postman是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件。postman适用于不同的操作系统,Postman Mac、Windows X32、Windows X64、Linux系统,还支持postman 浏览器扩展程序、postman chrome应用程序等。下载地址:https://www.postman.com/downloads/
(2)collection在postman里面相当于一个文件夹,可以把同一个项目的请求放在一个Collection里方便管理和分享,Collection里面也可以再建文件夹。这里我们做一个普通接口的简单的示例
2、认证接口
(1)basic auth认证
使用postman创建一个接口调用,请求URL:https://postman-echo.com/basic-auth
用户名:postman
密码:password
授权协议:Basic auth
Authorization:用于需要认证的接口。
Basic Auth:最基本的一种认证类型,还有OAuth 1.0/2.0、Digest Auth等认证类型。
Username/Password:这是针对Basic Auth类型的认证的用户名/密码,并非我们认为的系统登录的用户名密码。
(2)在项目中加入添加依赖也可以实现basic auth认证
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后访问页面时会跳转到认证页面,用户名默认是user,密码自动生成显示在控制台。
(3)bearer token认证
为了验证使用者的身份,需要客户端向服务器端提供一个可靠的验证信息,称为Token,这个token通常由Json数据格式组成,通过hash散列算法生成一个字符串,所以称为Json Web Token(Json表示令牌的原始值是一个Json格式的数据,web表示是在互联网传播的,token表示令牌,简称JWT)。
测试带token的接口,首先要进行登录,登录成功会有个token信息,向api接口发送请求的时候必须在header中放入这个token,故需要做2次请求。
(4)Springboot 使用JWT 生成token
JWT意思是Json web token,通过POST参数或者在HTTP header发送,然后进行验证,验证通过之后,就能返回响应的资源给浏览器。通常和权限框架(如shiro)搭配使用。
1.引入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
2.在annotation包下自定义注解
用来跳过验证的@PassToken
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
需要登录才能进行操作的注解UserLoginToken
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
3.封装生成Token的工具类
public class JWTUtils {
public static String getToken(String userCode, String userPassword) {
return JWT.create()
.withAudience(userCode)
.sign(Algorithm.HMAC256(userPassword));
}
}
4.新增一个拦截器AuthenticationInterceptor
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Resource
private UserMapper userMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);