SpringBoot Security 集成JWT实现接口可信赖认证(中)

简介: SpringBoot Security 集成JWT实现接口可信赖认证
开发配置类

用于自定义拦截配置

package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
/**
* @author 小隐乐乐
* @since 2020/11/8 20:20
*/
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Autowired
   private UserDetailsService userDetailsService;
   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http
              .csrf().disable()
              .authorizeRequests()
              .antMatchers("/api/signin").permitAll()
              .anyRequest().authenticated()
              .and()
              .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }
   @Bean
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
  }
   @Bean
   @Override
   public UserDetailsService userDetailsService() {
       UserDetails user = User.withDefaultPasswordEncoder()
              .username("user")
              .password("password")
              .roles("USER")
              .build();
       return new InMemoryUserDetailsManager(user);
  }
}
开发登录实体类

用于完成登录实体

package com.example.demo.dto;
import com.sun.istack.internal.NotNull;
/**
* @author 小隐乐乐
* @since 2020/11/8 20:22
*/
public class SigninDto {
   @NotNull
   private String username;
   @NotNull
   private String password;
   protected SigninDto() {}
   public SigninDto(String username, String password) {
       this.username = username;
       this.password = password;
  }
   public String getUsername() {
       return username;
  }
   public void setUsername(String username) {
       this.username = username;
  }
   public String getPassword() {
       return password;
  }
   public void setPassword(String password) {
       this.password = password;
  }
}
改造controller
package com.example.demo.controller;
import com.example.demo.dto.SigninDto;
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.web.bind.annotation.*;
import javax.validation.Valid;
/**
*
* @author 小隐乐乐
* @since 2020/11/8 19:44
*/
@RestController
@RequestMapping("/api")
public class HelloController {
   @Autowired
   private AuthenticationManager authenticationManager;
   @GetMapping("/hello")
   public String hello() {
       return "hello guys";
  }
   @PostMapping("/signin")
   public Authentication signIn(@RequestBody @Valid SigninDto signInDto) {
       return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(signInDto.getUsername(), signInDto.getPassword()));
  }
}
目录结构

image.png

此时完成了添加端点signin到自定义拦截链中

测试应用

image.png此时接口api/hello,仍然是没有权限的,我们添加jwt的支持。

添加JWT

依赖添加
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.9.1</version>
</dependency>
开发token生成类
package com.example.demo.jwt;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Base64;
import java.util.Date;
/**
* @author 小隐乐乐
* @since 2020/11/8 20:38
*/
@Component
public class JwtProvider {
   private String secretKey;
   private long validityInMilliseconds;
   @Autowired
   public JwtProvider(@Value("${security.jwt.token.secret-key}") String secretKey,
                      @Value("${security.jwt.token.expiration}") long milliseconds) {
       this.secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
       this.validityInMilliseconds = milliseconds;
  }
   public String createToken(String username) {
       //Add the username to the payload
       Claims claims = Jwts.claims().setSubject(username);
       //Build the Token
       Date now = new Date();
       return Jwts.builder()
              .setClaims(claims)
              .setIssuedAt(now)
              .setExpiration(new Date(now.getTime() + validityInMilliseconds))
              .signWith(SignatureAlgorithm.HS256, secretKey)
              .compact();
  }
}
目录
相关文章
|
5月前
|
JSON 分布式计算 大数据
springboot项目集成大数据第三方dolphinscheduler调度器
springboot项目集成大数据第三方dolphinscheduler调度器
289 3
|
5月前
|
缓存 JSON 前端开发
第07课:Spring Boot集成Thymeleaf模板引擎
第07课:Spring Boot集成Thymeleaf模板引擎
552 0
第07课:Spring Boot集成Thymeleaf模板引擎
|
分布式计算 大数据 Java
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
springboot项目集成大数据第三方dolphinscheduler调度器 执行/停止任务
106 0
|
5月前
|
存储 人工智能 Java
Springboot集成AI Springboot3 集成阿里云百炼大模型CosyVoice2 实现Ai克隆语音(未持久化存储)
本项目基于Spring Boot 3.5.3与Java 17,集成阿里云百炼大模型CosyVoice2实现音色克隆与语音合成。内容涵盖项目搭建、音色创建、音频合成、音色管理等功能,适用于希望快速掌握Spring Boot集成语音AI技术的开发者。需提前注册阿里云并获取API Key。
|
设计模式 前端开发 Java
基于Springboot实现专业认证材料管理系统
该知识产权服务平台系统项目采用mvc设计模式, 其中知识产权服务平台系统的视图与知识产权服务平台系统业务逻辑进行了分层设计, 特别方便后续知识产权服务平台系统系统的开发 设计这种mvc的架构的好处是完全的可以将业务进行分层, 进行高内聚低耦合, 分为service层, dao层, controller层, 架构清晰 本项目主要基于Springboot 和ruoyi来开发一套专业认证材料管理系统,对各专业相关的文档材料进行管理,主要包含的功能模块有: 系统管理:用户管理、角色管理、菜单管理、操作日志 业务模块:专业管理、认证材料管理、相关网站管理
305 0
基于Springboot实现专业认证材料管理系统
|
2月前
|
JavaScript Java 关系型数据库
基于springboot的项目管理系统
本文探讨项目管理系统在现代企业中的应用与实现,分析其研究背景、意义及现状,阐述基于SSM、Java、MySQL和Vue等技术构建系统的关键方法,展现其在提升管理效率、协同水平与风险管控方面的价值。
|
2月前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
2月前
|
JavaScript Java 关系型数据库
基于springboot的古树名木保护管理系统
本研究针对古树保护面临的严峻挑战,构建基于Java、Vue、MySQL与Spring Boot技术的信息化管理系统,实现古树资源的动态监测、数据管理与科学保护,推动生态、文化与经济可持续发展。