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();
  }
}
目录
相关文章
|
2月前
|
JSON 安全 Java
什么是JWT?如何使用Spring Boot Security实现它?
什么是JWT?如何使用Spring Boot Security实现它?
461 5
|
4天前
|
监控 Java Spring
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
33 16
|
1月前
|
XML JavaScript Java
SpringBoot集成Shiro权限+Jwt认证
本文主要描述如何快速基于SpringBoot 2.5.X版本集成Shiro+JWT框架,让大家快速实现无状态登陆和接口权限认证主体框架,具体业务细节未实现,大家按照实际项目补充。
80 11
|
1月前
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
342 12
|
1月前
|
Web App开发 安全 前端开发
一个接口4个步骤轻松搞定最新版Chrome、Edge、Firefox浏览器集成ActiveX控件
目前的浏览器市场,谷歌浏览器占据了半壁江山,因此,谷歌也是最有话语权的,2015年开始取消支持 NPAPI 插件,2022 年10月停止支持 PPAPI 插件;而曾经老大哥IE浏览器也已停止服务,退出历史舞台,导致大量曾经安全、便捷的ActiveX控件无法使用。为了解决这个难题,本人特研发出allWebPlugin中间件,重新让所有ActiveX控件能在谷歌、火狐等浏览器使用。
|
3月前
|
JSON 安全 算法
Spring Boot 应用如何实现 JWT 认证?
Spring Boot 应用如何实现 JWT 认证?
108 8
|
3月前
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
77 0
|
3月前
|
JavaScript NoSQL Java
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
CC-ADMIN后台简介一个基于 Spring Boot 2.1.3 、SpringBootMybatis plus、JWT、Shiro、Redis、Vue quasar 的前后端分离的后台管理系统
90 0
|
24天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的留守儿童爱心网站设计与实现(计算机毕设项目实战+源码+文档)
博主是一位全网粉丝超过100万的CSDN特邀作者、博客专家,专注于Java、Python、PHP等技术领域。提供SpringBoot、Vue、HTML、Uniapp、PHP、Python、NodeJS、爬虫、数据可视化等技术服务,涵盖免费选题、功能设计、开题报告、论文辅导、答辩PPT等。系统采用SpringBoot后端框架和Vue前端框架,确保高效开发与良好用户体验。所有代码由博主亲自开发,并提供全程录音录屏讲解服务,保障学习效果。欢迎点赞、收藏、关注、评论,获取更多精品案例源码。
59 10
|
24天前
|
JavaScript Java 测试技术
基于SpringBoot+Vue实现的家政服务管理平台设计与实现(计算机毕设项目实战+源码+文档)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
43 8

热门文章

最新文章