spring boot rest interface Integrated spring security (1) - the most simple configuration


Spring Boot Integration Tutorial


Outline

This tutorial we will introduce an integrated spring security, and is easy to learn, we will try to eliminate independent part, integrated spring security with minimal configuration. Once you learn how to integrate spring security, next we will integrate jwt, in that tutorial, we will further introduce spring security, improve the configuration. Under the rear end of the separation of the former trend, Java back-end REST interfaces are achieved, so In this part only for the REST interface, interface to learn is not the case, refer to the relevant information on their own.

Spring security servlet implemented based filters, each request being processed prior to spring MVC, must first spring security through the filter, thereby achieving access control. Access control in two parts, authentication and authorization, user authentication refers logged in to access some of the interfaces to user login; authorization refers to grant different privileges based on user roles, some interfaces to users with appropriate roles can access, such as the associated management Interface admin role only access.

We will create several interfaces, part of the interface need to be logged in to access part of the interface is fully liberalized, spring security to verify the success of integration.

Project Dependencies

Create a spring boot project

Open Eclipse, create spring starter project spring boot of the project, select the menu: File > New > Project ...pop-up dialog box, select: Spring Boot > Spring Starter Projectwhen configuring dependent, check web, security, such as do not know how to create a spring boot project, referring to the tutorial: [spring boot hello world (restful Interface) examples].

image

Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 http://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.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.qikegu</groupId>
    <artifactId>springboot-security-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-security-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.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.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

Project Configuration

spring security Java Configuration

java spring configuration can also be used xml configuration, spring officially recommended configuration with java, java configuration we use here.

Add java configuration file:

image

a. Add spring security filter

The easiest way to register spring security filters is to add java class configuration @EnableWebSecurity notes:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    // ...
}

b. encrypt the plaintext password which method

When you save a user's password to the database, generally avoided expressly saved by way hash value, we can configure the method used to encrypt the plaintext password as spring security, where the use of official recommended BCryptPasswordEncoder

    @Bean
    public PasswordEncoder myEncoder() {
      return new BCryptPasswordEncoder();
    }

c. Configure user information loading

User authentication / login to load user information than a user name and password, and general user information loaded from the database, here for simplicity, create user information in memory, including user names, passwords, user role information

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
           auth.inMemoryAuthentication()
           .withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
           .and()
           .withUser("user").password(myEncoder().encode("12345")).roles("USER");
    }

d. Configure Interface Access Control

By configuring HttpSecurity, can match different url path to specify different permissions for them, here for /hello3the interfaces were rights restrictions, you must be logged in to access

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        
        // 基于token,不需要csrf
        .csrf().disable() 
        
        // 基于token,不需要session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 
     
        // 下面开始设置权限
        .authorizeRequests()
        
        // 需要登录
        .antMatchers("/hello3").authenticated()
        
        // 除上面外的所有请求全部放开
        .anyRequest().permitAll();      
    }

Complete SecurityConfig.java file

package com.qikegu.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity // 添加security过滤器
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    
    // 密码明文加密方式配置
    @Bean
    public PasswordEncoder myEncoder() {
      return new BCryptPasswordEncoder();
    }
    
    // 认证用户时用户信息加载配置
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
           auth.inMemoryAuthentication()
           .withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
           .and()
           .withUser("user").password(myEncoder().encode("12345")).roles("USER");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        
        // 基于token,不需要csrf
        .csrf().disable() 
        
        // 基于token,不需要session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 
     
        // 下面开始设置权限
        .authorizeRequests()
        
        // 需要登录
        .antMatchers("/hello3").authenticated()
        
        // 除上面外的所有请求全部放开
        .anyRequest().permitAll();      
    }
}

Add code

Add a class control, it implements several test interface.

Add files in the project

image

Add a few interfaces, file reads as follows

package com.qikegu.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    
    @RequestMapping(value="/hello1", method=RequestMethod.GET)
    public String hello1() {
            
        return "Hello1!";
    }
    
    @RequestMapping(value="/hello2", method=RequestMethod.GET)
    public String hello2() {
            
        return "Hello2!";
    }
    
    @RequestMapping(value="/hello3", method=RequestMethod.GET)
    public String hello3() {
            
        return "Hello3!";
    }
}

We achieved three interfaces, which /hello3is configured to require login access, so access /hello3will return an error when rights restricted.

Running the Project

Eclipse on the left, right click on the project root directory pop-up menu, choose: run as -> spring boot apprun the program. Open Postman access interface, results are as follows:

Access /hello1interface is not limited

image

Access /hello3interface is limited. Later in the tutorial will explain the process of login access interface.

image

to sum up

This article describes the process of spring boot project integrated spring security, try a simple way to configure security, next tutorial will describe in more detail the integrated spring security and jwt.

The complete code

Guess you like

Origin www.cnblogs.com/haibianren/p/11570738.html