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();
  }
}
目录
相关文章
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
2173 5
|
4月前
|
安全 NoSQL Java
SpringBoot接口安全:限流、重放攻击、签名机制分析
本文介绍如何在Spring Boot中实现API安全机制,涵盖签名验证、防重放攻击和限流三大核心。通过自定义注解与拦截器,结合Redis,构建轻量级、可扩展的安全防护方案,适用于B2B接口与系统集成。
724 3
|
7月前
|
算法 网络协议 Java
Spring Boot 的接口限流算法
本文介绍了高并发系统中流量控制的重要性及常见的限流算法。首先讲解了简单的计数器法,其通过设置时间窗口内的请求数限制来控制流量,但存在临界问题。接着介绍了滑动窗口算法,通过将时间窗口划分为多个格子,提高了统计精度并缓解了临界问题。随后详细描述了漏桶算法和令牌桶算法,前者以固定速率处理请求,后者允许一定程度的流量突发,更符合实际需求。最后对比了各算法的特点与适用场景,指出选择合适的算法需根据具体情况进行分析。
665 56
Spring Boot 的接口限流算法
|
10月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
544 0
|
7月前
|
Java API 网络架构
基于 Spring Boot 框架开发 REST API 接口实践指南
本文详解基于Spring Boot 3.x构建REST API的完整开发流程,涵盖环境搭建、领域建模、响应式编程、安全控制、容器化部署及性能优化等关键环节,助力开发者打造高效稳定的后端服务。
1080 1
|
9月前
|
存储 安全 JavaScript
秘密任务 3.0:如何通过 JWT 认证确保 WebSockets 安全
本文探讨了如何通过JWT认证保障WebSockets通信安全,防止敏感数据泄露和未授权访问。首先介绍了保护WebSockets的重要性,随后详细讲解了JWT与WebSockets的协同工作流程:特工通过API登录获取JWT,建立连接时提供令牌,服务器验证后决定是否授权。还提供了Node.js实现示例及客户端连接方法,并分享了最佳实践,如使用HTTP-only Cookie、短生命周期令牌和WSS加密。最后推荐了Apipost工具助力实时测试与调试,确保构建高效安全的实时网络。
|
11月前
|
监控 Java Spring
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
446 16
|
XML JavaScript Java
SpringBoot集成Shiro权限+Jwt认证
本文主要描述如何快速基于SpringBoot 2.5.X版本集成Shiro+JWT框架,让大家快速实现无状态登陆和接口权限认证主体框架,具体业务细节未实现,大家按照实际项目补充。
878 11
|
JSON 安全 算法
Spring Boot 应用如何实现 JWT 认证?
Spring Boot 应用如何实现 JWT 认证?
1299 8
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
446 0

热门文章

最新文章