SpringBoot集成Swagger实现JWT验证token

前言

最近有个项目涉及用户权限管理,然后之前也有看到的一个小技术JWT,简单学习了解以后结合SpringBoot Swagger实现了一个简单的demo,这个demo主要是实现用户通过用户名和密码登录系统,登录成功以后系统给一个token,之后的用户操作需要验证token,只有token符合要求才能进行其他系统资源访问操作,否则提示权限不够或者token过期有误等提示信息,现将实现过程进行简单记录。

参考链接

1. Swagger了解:https://www.jianshu.com/p/349e130e40d5

2. SpringBoot集成Swagger:https://www.jianshu.com/p/be1e772b089a

3. JWT了解:https://www.cnblogs.com/wangshouchang/p/9551748.html

4. SpringBoot实现JWT:https://blog.csdn.net/cf535261933/article/details/102603490

5. SpringBoot拦截器实现:https://blog.csdn.net/qq_30745307/article/details/80974407

实现过程

1. SpringBoot集成Swagger

1.1 导入依赖

 <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

1.2 配置Swagger(SwaggerConfiguration)

@Configuration //SpringBoot中配置类不可少此注释
@EnableSwagger2
public class SwaggerConfiguration {
    /**
     * 注册Bean实体
     * @return
     */
    @Bean
    public Docket createRestApi(){

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //当前包名
                .apis(RequestHandlerSelectors.basePackage("com.practice.tokendemo"))
                .paths(PathSelectors.any())
                .build()
                //Lists工具类的newArrayList方法将对象转为ArrayList
                .securitySchemes(Lists.newArrayList(apiKey()));//结果是Swagger-ui上出现Authorize,可以手动点击输入token
    }

    /**
     * 构建Authorization验证key
     * @return
     */
    private ApiKey apiKey() {
        return new ApiKey(Constant.TOKEN_HEADER_STRING,Constant.TOKEN_HEADER_STRING,"header");//配置输入token的备注 TOKEN_HEADER_STRING = "Authorization"
    }

    /**
     * 构建API文档的详细信息方法
     * @return
     */
    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                //API页面标题
                .title("Spring Boot继承Swagger2实现JWT")
                //创建者
                .contact(new Contact("ciery","https://mp.csdn.net/console/article",""))
                //版本
                .version("1.0")
                //描述
                .description("API描述")
                .build();
    }
}

1.3 Swagger简单介绍

Swagger UI提供了一个可视化的UI页面展示描述文件。接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。

Springfox-swagger可以通过扫描代码去生成swagger定义的描述文件(通过维护这个描述文件可以去更新接口文档),所有的信息都在代码中。代码即接口文档,接口文档即代码。

2. 基本功能的实现(用户登录)

写法和普通的controller层一致,只不过多了API的注释完成与swagger的集成。

@Api("用户操作接口") //配置swagger页面api名称
//@Controller("user") //如果controller中有多个方法ResponseMapping,那么直接使用@RestController注释,底下的所有方法都不需要再加@ReponseMapping注释,直接使用@XXXMapping表明获取参数的方式(PUT/GET/POST&
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个简单的 Spring Boot 集成 JWT 的示例代码: 1. 添加依赖 ```xml <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 2. 创建 JWT 工具类 ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; @Component public class JwtUtils { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String generateToken(String username) { Date now = new Date(); Date expireDate = new Date(now.getTime() + expiration * 1000); return Jwts.builder() .setSubject(username) .setIssuedAt(now) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, TextCodec.BASE64.encode(secret)) .compact(); } public Claims getClaimsFromToken(String token) { return Jwts.parser() .setSigningKey(TextCodec.BASE64.encode(secret)) .parseClaimsJws(token) .getBody(); } public boolean isTokenExpired(String token) { Date expirationDate = getClaimsFromToken(token).getExpiration(); return expirationDate.before(new Date()); } } ``` 3. 创建一个 JWT 认证过滤器 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.web.util.WebUtils; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class JwtAuthenticationFilter extends BasicAuthenticationFilter { @Autowired private JwtUtils jwtUtils; public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String token = WebUtils.getCookie(request, "token").getValue(); if (token != null && jwtUtils.isTokenExpired(token)) { Authentication authentication = getAuthentication(token); SecurityContextHolder.getContext().setAuthentication(authentication); } chain.doFilter(request, response); } private Authentication getAuthentication(String token) { String username = jwtUtils.getClaimsFromToken(token).getSubject(); if (username != null) { return new UsernamePasswordAuthenticationToken(username, null, null); } return null; } } ``` 4. 配置 Spring Security ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/swagger-ui.html/**", "/webjars/**", "/v2/**", "/swagger-resources/**"); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 5. 创建登录接口 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @RestController public class AuthController { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private JwtUtils jwtUtils; @Autowired private PasswordEncoder passwordEncoder; @PostMapping("/login") public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request, HttpServletResponse response) { String username = request.get("username"); String password = request.get("password"); Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(username); String token = jwtUtils.generateToken(username); Cookie cookie = new Cookie("token", token); cookie.setPath("/"); response.addCookie(cookie); Map<String, Object> data = new HashMap<>(); data.put("user", userDetails); data.put("token", token); return ResponseEntity.status(HttpStatus.OK).body(data); } } ``` 这样就完成了 Spring Boot 集成 JWT 的代码。当用户登录成功后,生成一个 JWT Token 并存储到 Cookie 中,后续的请求都需要携带该 Token,服务端通过解析 Token 来进行用户认证。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值