springboot中登录功能这块如何给前端返回token

1.建一个名为JwtProperties的类,这个类中主要是放一些关于jwt中用到配置信息,将application.yml中jwt相关配置映射到这里

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {

    /**
     * 管理端员工生成jwt令牌相关配置
     */
    private String adminSecretKey;
    private long adminTtl;
    private String adminTokenName;


}

这里可以设置对应的过期时间和加密的密钥,以及令牌的名字

2.准备一个jwt工具类,负责将token中数据进行加密和解密。

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    /**
     * 生成jwt
     * 使用Hs256算法, 私匙使用固定秘钥
     *
     * @param secretKey jwt秘钥
     * @param ttlMillis jwt过期时间(毫秒)
     * @param claims    设置的信息
     * @return
     */
    public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims) {
        // 指定签名的时候使用的签名算法,也就是header那部分
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        // 生成JWT的时间
        long expMillis = System.currentTimeMillis() + ttlMillis;
        Date exp = new Date(expMillis);

        // 设置jwt的body
        JwtBuilder builder = Jwts.builder()
                // 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的
                .setClaims(claims)
                // 设置签名使用的签名算法和签名使用的秘钥
                .signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8))
                // 设置过期时间
                .setExpiration(exp);

        return builder.compact();
    }

    /**
     * Token解密
     *
     * @param secretKey jwt秘钥 此秘钥一定要保留好在服务端, 不能暴露出去, 否则sign就可以被伪造, 如果对接多个客户端建议改造成多个
     * @param token     加密后的token
     * @return
     */
    public static Claims parseJWT(String secretKey, String token) {
        // 得到DefaultJwtParser
        Claims claims = Jwts.parser()
                // 设置签名的秘钥
                .setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))
                // 设置需要解析的jwt
                .parseClaimsJws(token).getBody();
        return claims;
    }

}

3..自定义一个拦截器JwtTokenAdminInterceptor,用来拦截请求获取请求头中的token数据,然后进.行校验,这里面有用到一个类叫JwtClaimsConstant是自己定义的主要是为了规范。

import com.zds.constant.JwtClaimsConstant;
import com.zds.context.BaseContext;
import com.zds.properties.JwtProperties;
import com.zds.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法,直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //取出用户id
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前员工id:{}", userId);
            //保存到线程类中的userId
            BaseContext.setCurrentId(userId);
            //3、通过,放行
            return true;
        } catch (Exception ex) {
            //4、不通过,响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
public class JwtClaimsConstant {
    public static final String USER_ID = "userId";
  
}

4.在config包下定义一个全局的配置类WebMvcConfiguration中,将自定义的拦截器注册到里面,设置需要拦截的请求路径和需要放行的路径

import com.zds.interceptor.JwtTokenAdminInterceptor;
import com.zds.interceptor.JwtTokenUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.List;

/**
 * 配置类,注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {


    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/user/**")//拦截的路径
                .addPathPatterns("/hello")
              .excludePathPatterns("/user/login")
              .excludePathPatterns("/user/register");  //放行的路径
    }

    /**
     * 设置静态资源映射
     * @param registry
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }


}

5.controller运用:当前端发送请求给登录接口时候,验证成功后生成一串token数据返回给前端,在拦截器中,只拦截除了登录和注册外的其他请求,进行token校验,没有token请求头活token过期都无法访问这些资源

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zds.entity.User;
import com.zds.constant.JwtClaimsConstant;
import com.zds.dto.UserLoginDTO;
import com.zds.mapper.UserMapper;
import com.zds.properties.JwtProperties;
import com.zds.result.Result;
import com.zds.service.UserService;
import com.zds.utils.JwtUtil;
import com.zds.vo.UserLoginVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sound.sampled.Line;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private  UserMapper userMapper;
    @PostMapping("/register")
    @CrossOrigin
    @ApiOperation("注册用户")
    public Result<String> save(@RequestBody User user){
        log.info("用户信息:{}",user);
        //1.注册时候将密码进行md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //2.判断数据库中是否有该用户
         LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<>();
         wrapper.eq(User::getName,user.getName());
         User user2 = userService.getOne(wrapper);
         if(null!=user2)
             return Result.error("用户已存在");
         //3.不存在该用户则之直接插入到数据库中
         userService.save(user);
       return Result.success();
   }
   @PostMapping("/login")
   @ApiOperation("登录")
   public Result<UserLoginVO>login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("userLoginDTO:{}",userLoginDTO);
        //0.将密码进行md5加密,然后再到数据库查询
       String password= DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
       LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<>();
       wrapper.eq(User::getName,userLoginDTO.getUsername());
       wrapper.eq(User::getPassword,password);
       User user = userService.getOne(wrapper);
       //1.验证密码和账户没问题,则进行下一步的返回数据
       if(null==user)return Result.error("登录失败");
       //2.登录成功后,生成jwt令牌
       Map<String,Object> claims=new HashMap<>();
       claims.put(JwtClaimsConstant.USER_ID,user.getId());
       String token= JwtUtil.createJWT(jwtProperties.getAdminSecretKey(),
                                       jwtProperties.getAdminTtl(),
                                       claims);
       //3.将账户信息和token一同返回给前端
       UserLoginVO userLoginVO=UserLoginVO.builder()
               .id(user.getId())
               .name(user.getName())
               .token(token)
               .build();
        return Result.success(userLoginVO);
   }

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,您可以参考以下步骤实现: 1. 添加依赖: 在 `pom.xml` 文件添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 配置 Security: 新建一个继承 `WebSecurityConfigurerAdapter` 的类,并且重写其的方法: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() .antMatchers(HttpMethod.POST, "/login").permitAll() .anyRequest().authenticated() .and().addFilter(new JWTAuthenticationFilter(authenticationManager())) .addFilter(new JWTAuthorizationFilter(authenticationManager())); } } ``` 3. 创建 User 实体类: 创建一个 User 实体类,用于存储用户信息。 ``` @Entity @Table(name = "users") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Collections.emptyList(); } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } ``` 4. 创建 UserDetailsService 实现类: 创建一个 UserDetailsService 实现类,用于从数据库获取用户信息。 ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException(username); } return user; } } ``` 5. 创建 UserRepository 接口: 创建一个 UserRepository 接口,用于操作数据库。 ``` @Repository public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } ``` 6. 创建 JWTAuthenticationFilter 和 JWTAuthorizationFilter: 创建 JWTAuthenticationFilter 和 JWTAuthorizationFilter,用于实现 JWT 认证和授权功能。 JWTAuthenticationFilter: ``` public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; setFilterProcessesUrl("/login"); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { User user = new ObjectMapper().readValue(request.getInputStream(), User.class); return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())); } catch (IOException e) { throw new RuntimeException(e); } } } ``` JWTAuthorizationFilter: ``` public class JWTAuthorizationFilter extends BasicAuthenticationFilter { public JWTAuthorizationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String header = request.getHeader("Authorization"); if (header == null || !header.startsWith("Bearer ")) { chain.doFilter(request, response); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(request); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request, response); } private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { String token = request.getHeader("Authorization"); if (token != null) { String user = Jwts.parser() .setSigningKey("secret".getBytes()) .parseClaimsJws(token.replace("Bearer ", "")) .getBody() .getSubject(); if (user != null) { return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList()); } return null; } return null; } } ``` 7. 创建 TokenController: 创建一个 TokenController,用于实现登录接口。 ``` @RestController public class TokenController { @PostMapping("/login") public ResponseEntity<?> login(@RequestBody User user) { try { Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()); authentication = new JWTAuthenticationFilter(authenticationManager()).attemptAuthentication(new HttpServletRequestWrapper(null) { @Override public String getHeader(String name) { return "Bearer " + Jwts.builder() .setSubject(user.getUsername()) .setExpiration(new Date(System.currentTimeMillis() + 86400000)) .signWith(SignatureAlgorithm.HS512, "secret".getBytes()) .compact(); } }, new HttpServletResponseWrapper(null)); SecurityContextHolder.getContext().setAuthentication(authentication); return ResponseEntity.ok().header("Authorization", authentication.getCredentials().toString()).build(); } catch (AuthenticationException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } } } ``` 至此,就完成了一个简单的登录接口并且返回 token 的实现。当用户发送 POST 请求到 `/login` 接口时,若用户名和密码正确,则会返回一个包含 token 的响应头。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值