Python 官方文档:入门教程 => 点击学习
1.pom.xml <dependencies> <dependency> <groupId>org.springframework.b
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-WEB</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-Jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>Mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastJSON</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
</dependencies>
@Data
public class User {
private String id;
private String username;
private String passWord;
}
@Mapper
public interface UserMapper {
User findByUsername(String username);
User findUserById(String id);
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findByUsername(User user){
return userMapper.findByUsername(user.getUsername());
}
public User findUserById(String userId) {
return userMapper.findUserById(userId);
}
}
@Service
public class TokenService {
public String getToken(User user) {
Date start = new Date();
long currentTime = System.currentTimeMillis() + 60* 60 * 1000;//一小时有效时间
Date end = new Date(currentTime);
String token = "";
token = JWT.create().withAudience(user.getId()).withIssuedAt(start).withExpiresAt(end)
.sign(AlGorithm.HMac256(user.getPassword()));
return token;
}
}
@RestController
public class UserApi {
@Autowired
UserService userService;
@Autowired
TokenService tokenService;
// 登录
@ApiOperation(value = "登陆", notes = "登陆")
@RequestMapping(value = "/login" ,method = RequestMethod.GET)
public Object login(User user, httpservletResponse response) {
jsONObject jsonObject = new JSONObject();
User userForBase = new User();
userForBase.setId(userService.findByUsername(user).getId());
userForBase.setUsername(userService.findByUsername(user).getUsername());
userForBase.setPassword(userService.findByUsername(user).getPassword());
if (!userForBase.getPassword().equals(user.getPassword())) {
jsonObject.put("message", "登录失败,密码错误");
return jsonObject;
} else {
String token = tokenService.getToken(userForBase);
jsonObject.put("token", token);
Cookie cookie = new Cookie("token", token);
cookie.setPath("/");
response.addCookie(cookie);
return jsonObject;
}
}
@UserLoginToken
@ApiOperation(value = "获取信息", notes = "获取信息")
@RequestMapping(value = "/getMessage" ,method = RequestMethod.GET)
public String getMessage() {
// 取出token中带的用户id 进行操作
System.out.println(TokenUtil.getTokenUserId());
return "您已通过验证";
}
}
public class TokenUtil {
public static String getTokenUserId() {
String token = getRequest().getHeader("token");// 从 Http 请求头中取出 token
String userId = JWT.decode(token).getAudience().get(0);
return userId;
}
public static HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
return requestAttributes == null ? null : requestAttributes.getRequest();
}
}
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
UserService userService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
// 如果不是映射到方法直接通过
if(!(object instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod=(HandlerMethod)object;
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);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("401");
}
User user = userService.findUserById(userId);
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("401");
}
return true;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
@Configuration
public class InterceptorConfig implements WebmvcConfigurer {
@Override
public void addInterceptors(InterceptorReGIStry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="findByUsername" resultType="com.example.demo.entity.User">
SELECT id,password
FROM user
WHERE
username=#{username}
</select>
<select id="findUserById" resultType="com.example.demo.entity.User">
SELECT username,password
FROM user
WHERE
id=#{id}
</select>
</mapper>
数据库文件如下所示
到此这篇关于SpringBoot整合token实现登录认证的示例代码的文章就介绍到这了,更多相关SpringBoot token登录认证内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: SpringBoot整合token实现登录认证的示例代码
本文链接: https://lsjlt.com/news/153748.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0