【封装】token的生成使用与密码加密操作

【封装】token的使用与密码加密操作

token封装

引入 jsonwebtoken模块

let jwt = require("jsonwebtoken")

封装生成签名与校验签名的方法

module.exports = {
  //生成签名
  sign:({username,_id})=>{
    return jwt.sign({username,_id},"NZ1906",{expiresIn:60*60*24})
  },
  //校验签名
  verify:token=>{
    return new Promise((resolve,reject)=>{
      jwt.verify(token,"NZ1906",(err,decode)=>{
        if(!err){
          resolve(decode)  //decode={username,_id}
        }else{
          reject(err.message)
        }
      })
    })
  }
}

以上代码可以封装为jwt.js文件


加密封装

引入bcrypt模块

let bcrypt = require("bcrypt")

封装加密与解密方法

module.exports = {
  //加密  const hash = bcrypt.hashSync(用户未加密的密码, salt);
  hashSync:password=>{
    return bcrypt.hashSync(password,10)
  },
  //解密校验 bcrypt.compareSync(用户未加密的密码, 用户加密之后的hash密码);
  compareSync:(password,hash)=>bcrypt.compareSync(password,hash)
}

以上代码可以封装为bcrypt.js文件


注意:在使用的时候可能会遇到安装不上的问题,这里可以选择安装 bcryptjs 模块,

bcryptjs是一个第三方密码加密库,是对原有bcrypt的优化,优点是不需要安装任何依赖
在纯JavaScript中优化了 bcrypt,兼容 bcrypt ,也就是说,与上面的用法一致

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以使用基于token的请求验证来保护你的API。下面是一个简单的实现步骤: 1. 生成token:首先,你需要生成一个token并将其分发给客户端。可以使用JWT(JSON Web Token)来生成token。JWT包含了加密的信息,比如用户ID、角色等。 2. 配置Spring Security:在你的Spring Boot项目中,你需要配置Spring Security来处理请求验证。可以通过添加`spring-boot-starter-security`依赖来引入Spring Security。 3. 创建Security配置类:创建一个继承自`WebSecurityConfigurerAdapter`的配置类,并覆盖`configure(HttpSecurity http)`方法。在该方法中,可以定义哪些请求需要进行验证。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll() .and() .addFilterBefore(new JwtTokenFilter(), UsernamePasswordAuthenticationFilter.class) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } } ``` 在上面的示例中,我们通过`antMatchers("/api/**").authenticated()`来定义了需要进行验证的请求。你可以根据实际需求修改这个配置。 4. 创建JwtTokenFilter:创建一个自定义的`JwtTokenFilter`类,继承自`OncePerRequestFilter`,用于解析和验证token。 ```java public class JwtTokenFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = extractToken(request); // 提取token if (token != null && validateToken(token)) { // 验证token Authentication auth = createAuthentication(token); SecurityContextHolder.getContext().setAuthentication(auth); } filterChain.doFilter(request, response); } // 提取token的逻辑 private String extractToken(HttpServletRequest request) { // 从请求头或请求参数中获取token // ... } // 验证token的逻辑 private boolean validateToken(String token) { // 验证token的合法性 // ... } // 创建认证对象 private Authentication createAuthentication(String token) { // 根据token信息创建认证对象 // ... } } ``` 在上面的示例中,我们通过`extractToken`方法从请求中提取token,然后通过`validateToken`方法验证token的合法性,最后通过`createAuthentication`方法创建一个认证对象,将其设置到`SecurityContextHolder`中。 5. 配置认证提供者:创建一个实现了`AuthenticationProvider`接口的认证提供者类,用于验证token的有效性。 ```java @Component public class JwtAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String token = (String) authentication.getCredentials(); if (validateToken(token)) { return new JwtAuthenticationToken(token, true); } else { throw new BadCredentialsException("Invalid token"); } } @Override public boolean supports(Class<?> authentication) { return JwtAuthenticationToken.class.isAssignableFrom(authentication); } // 验证token的逻辑 private boolean validateToken(String token) { // 验证token的合法性 // ... } } ``` 在上面的示例中,我们通过`authenticate`方法验证token的有效性,如果有效则返回一个认证对象,否则抛出异常。`supports`方法用于指定该认证提供者支持哪种类型的认证对象。 6. 创建JwtAuthenticationToken:创建一个继承自`AbstractAuthenticationToken`的认证对象,用于封装token信息。 ```java public class JwtAuthenticationToken extends AbstractAuthenticationToken { private final String token; private final boolean authenticated; public JwtAuthenticationToken(String token, boolean authenticated) { super(null); this.token = token; this.authenticated = authenticated; } @Override public Object getCredentials() { return token; } @Override public Object getPrincipal() { return null; } @Override public boolean isAuthenticated() { return authenticated; } } ``` 在上面的示例中,我们通过`getCredentials`方法返回token,`getPrincipal`方法返回null,`isAuthenticated`方法返回认证状态。 7. 使用token进行请求验证:当客户端发送请求时,需要在请求头或请求参数中携带token。在后端的API方法中,你可以通过`@AuthenticationPrincipal`注解获取当前用户的信息。 ```java @RestController public class ApiController { @GetMapping("/api/user") public String getUserInfo(@AuthenticationPrincipal JwtAuthenticationToken authToken) { String token = (String) authToken.getCredentials(); // 根据token获取用户信息 // ... return "User Info"; } } ``` 在上面的示例中,我们通过`@AuthenticationPrincipal`注解获取`JwtAuthenticationToken`对象,然后从中获取token,并根据token获取用户信息。 这样,你就实现了基于token的请求验证。请注意,这只是一个简单的示例,你可以根据实际需求进行更复杂的配置和实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值