编程知识 cdmana.com

Getting started with spring security (1)

I feel now Java Developers can't do without Spring frame , It's good or bad not to discuss such things , But it works , But some things are still very difficult to get started , The progress of groping is a little slow , It can only be updated slowly , Let's update it slowly today SpringSecurity Introduction to , Complete the complete system , It can be directly put into production, development and use .

How to start

  1. There is a certain Java Basics , Meeting Spring BootSpring SecurityMyBatis plus
  2. First , Understand what is token
  3. token What kind of role
  4. Understand the basic role permission verification

Token

Let's experience what is token

package com.shaojie.authority.jwt;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.shaojie.authority.exception.TokenException;
import com.shaojie.authority.service.impl.AuthorityServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.sql.Date;

/**
 * @author: ShaoJie
 * @data: 2020 year 02 month 22 Japan  18:17
 * @Description: jwt  Generate check  token
 */
@Slf4j
@Configuration
public class JwtUtil {

    /**
     *  Certification key key
     */
    String signingKey = "SigningKey";

    /**
     *  Create build  token
     *
     * @return
     */
    public String createToken() {
        //30 Seconds expired 
        long now = System.currentTimeMillis();
        long exp = now + 1000 * 60;
        // builder  structure  token
        String token = Jwts.builder()
                //  Set unique  id
                .setId(IdUtil.simpleUUID())
                //  Set the theme 
                .setSubject("token")
                //  Set up characters 
                .claim("authorities", "admin")
                //  Set up character sets 
//                .addClaims()
                //  Set expiration time 
                .setExpiration(new Date(exp))
                //  Set up  token  Time of issue 
                .setIssuedAt(new DateTime())
                //  Set signature   Use HS256 Algorithm , And set up SecretKey( character string )   Signature algorithm and secret key 
                .signWith(SignatureAlgorithm.HS256, signingKey)
                //  The following constructs JWT And serialize it into compact ,URL Safe string 
                .compact();
        log.info("token:{}", token);
        return token;
    }

    /**
     *  analysis  token
     *
     * @param token  User  token
     */
    public void parseToken(String token) throws TokenException {
        Claims claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody();
        if (claims.equals(null))
            throw new TokenException();
        log.info(" Parsed data :{}", claims);
    }

    public static void main(String[] args) {
        JwtUtil jwtUtil = new JwtUtil();
        String token = jwtUtil.createToken();
        try {
            jwtUtil.parseToken(token);
        } catch (TokenException e) {
            log.info("token  Be overdue ");
        }
        System.out.println(token);
    }

}
 Generated token:
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiZmNjYzRlOWQ5OWY0Mzc3YTI1MjBmNjkxZDM1NzkyMiIsInN1YiI6InRva2VuIiwiYWRtaW4iOiJTaGFvSmllIiwiZXhwIjoxNTk1NDA0MTU4LCJpYXQiOjE1OTU0MDQwOTh9.AjPDjf40BnAzgnU3mCpjMI8KYggEVR8264JATKg4cFc

 Resolved to token:
{jti=bfccc4e9d99f4377a2520f691d357922, sub=token, admin=ShaoJie, exp=1595404158, iat=1595404098}

Parse the created token It's not hard to find the information : Current creation token The theme of 、 role 、 Expiration time, etc.

This is only the first step in learning to use , Experience the convenience of this certification , And convenience . Then get to the point , Start updating such an issue Spring Boot Integrate SpringSecurity

The foundation depends on

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>top.lzmvlog</groupId>
    <artifactId>authority</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>authority</name>
    <description>Spring Boot  Integrate  JWT  Do authorization Certification </description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR4</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

JwtUtil Create a verification tool

package top.lzmvlog.authority.util.jwt;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpStatus;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.lzmvlog.authority.exception.TokenException;
import top.lzmvlog.authority.util.date.DateUtil;

/**
 * @author ShaoJie
 * @Date 2020 year 05 month 12 15:16
 * @Description:  Build resolution  token  Tool class of 
 */
@Component
@Slf4j
public class JwtUtil {

    /**
     *  Signature key 
     */
    @Value("${auth.token.signingKey}")
    private String signingKey;

    /**
     *  Create build  token
     *
     * @return String  Generated  token
     */
    public String createToken(String account) {
        log.info(" account number :{}  Login successful ", account);
        return Jwts.builder()
                //  Set unique  ida
                .setId(IdUtil.simpleUUID())
                //  The setting mainly contains information 
                .setSubject(account)
                //  Set expiration time 
                .setExpiration(new DateUtil().getNowDateOneTime())
                //  Set up  token  Time of issue 
                .setIssuedAt(new DateTime())
                //  Set signature   Use HS256 Algorithm , And set up SecretKey( character string )   Signature algorithm and secret key 
                .signWith(SignatureAlgorithm.HS256, signingKey)
                //  The following constructs JWT And serialize it into compact ,URL Safe string 
                .compact();
    }

    /**
     *  Resolve current  token
     *
     * @param token token  Information 
     * @return String token A kind of parsed information 
     */
    public String parseToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody();
        if (claims.equals(null))
            throw new TokenException(HttpStatus.HTTP_INTERNAL_ERROR, "token  Wrong information   Reauthorize ");
        return claims.getSubject();
    }

}

Current JwtUtil Didn't add any information about the role , Simply authorize the account , Make such a token, Of course, you can also authorize your permission information , Self divergent thinking .

Build permission verification

package top.lzmvlog.authority.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.web.authentication.UsernamePasswordAuthenticationFilter;
import top.lzmvlog.authority.filter.JwtAuthenticationFilter;
import top.lzmvlog.authority.handler.JwtAccessDeniedHandler;

/**
 * @author ShaoJie
 * @Date 2020 year 05 month 12 14:36
 * @Description:  Security authentication configuration 
 */
@Configuration
@EnableWebSecurity
public class SecurityVerificationConfiguration extends WebSecurityConfigurerAdapter {

    /**
     *  Password encryption 
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     *  Interceptor 
     */
    @Autowired
    public JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * jwt  Verify the processor 
     */
    @Autowired
    public JwtAccessDeniedHandler jwtAccessDeniedHandler;

    /**
     * toekn  To configure 
     */
    @Autowired
    public TokenConfiguration tokenConfiguration;

    /**
     *  to grant authorization  、  verification 
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                //  The authorized address does not need to be verified 
                .antMatchers("/auth/token").permitAll()
                //  User registration address 
                .antMatchers("/user/registered").permitAll()
                //  The rest need to be verified 
                .anyRequest().authenticated()
                .and()
                //  Add post-processing interceptor 
                .addFilterAfter(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                //  Access denial handler 
                .accessDeniedHandler(jwtAccessDeniedHandler)
                .and()
                .apply(tokenConfiguration)
                .and()
                //  Cancel  session  The state of 
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable();
    }

}

BCryptPasswordEncoder The official password encryption class , Encrypt the registered user information , For example, the user's login password .

JwtAuthenticationFilter Authority blocker , Used to intercept user information , Verify authority .

JwtAccessDeniedHandler Access to the processor is denied .

TokenConfiguration Adapter Configuration , Used to modify the default authentication processor , Implement custom validation

The next update will focus on the implementation of these classes , For a taste experience, visit my GitHub see authority project clone

$ git clone https://github.com/lzmvlog/authority.git

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600803y.html

Scroll to Top