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();
  }
}
目录
相关文章
|
4天前
|
Java 数据库连接 Maven
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
|
3天前
|
Java
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
|
3天前
|
JSON 安全 Java
Spring Boot中使用JWT进行安全认证
Spring Boot中使用JWT进行安全认证
|
3天前
|
文字识别 Java Python
文本,文识10,springBoot提供RestTemplate以调用Flask OCR接口,调用flask实现ocr接口,用paddleocr进行图片识别云服务技术,单个paddleocr接口有影响
文本,文识10,springBoot提供RestTemplate以调用Flask OCR接口,调用flask实现ocr接口,用paddleocr进行图片识别云服务技术,单个paddleocr接口有影响
|
3天前
|
文字识别 Java
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
|
3天前
|
文字识别 Java Spring
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
|
4天前
|
消息中间件 Java 测试技术
【RocketMQ系列八】SpringBoot集成RocketMQ-实现普通消息和事务消息
【RocketMQ系列八】SpringBoot集成RocketMQ-实现普通消息和事务消息
11 1
|
6天前
|
监控 负载均衡 Java
Spring Boot与微服务治理框架的集成
Spring Boot与微服务治理框架的集成
|
6天前
|
负载均衡 Java Nacos
Spring Boot与微服务治理框架的集成策略
Spring Boot与微服务治理框架的集成策略
|
7天前
|
存储 安全 Java
Spring Security与OAuth2集成开发
Spring Security与OAuth2集成开发