SpringSecurityStep 1: Verify and authorize memory permissions

Build dependenciespom.xml


      
<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>

    <groupId>com.shaojie.authority</groupId>
    <artifactId>authority</artifactId>
    <version>1.0 the SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0. RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-cloud.version>Hoxton.RC1</spring-cloud.version>
    </properties>

    <! Manage dependencies -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <! --lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</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>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <! -- Spring Security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <! --spring-data-jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <! --lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <! -- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <! -- druid connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
    </dependencies>

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

</project>
Copy the code

Build permission validation

package com.shaojie.authority.security;

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.crypto.bcrypt.BCryptPasswordEncoder;

/ * * *@author ShaoJie
 * @Date2019/10/25 * /
@Configuration
// Start SpringSecurity's filter chain
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder(a) {
        return new BCryptPasswordEncoder();
    }

    /** * authorized **@param auth
     * @throws Exception
     */
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Older roles cannot be set this way after SpringBoot 2.0
// auth.inMemoryAuthentication()
// .withUser("shaojie").password("123456")
// .authorities("PRODUCT_ADD");

        // inMemoryAuthentication Memory authentication
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser("shaojie")
                .password(passwordEncoder().encode("123456"))
                // .roles("PRODUCT_ADD","PRODUCT_LIST");
                // roles is not available for 403
                .authorities("PRODUCT_ADD"."PRODUCT_LIST");

    }

    /** * verify **@param http
     * @throws Exception
     */
    // Replace configuration file 
      
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // antMatchers set interception request hasAnyAuthority set the role access permissions it has
                .antMatchers("/product/add").hasAnyAuthority("PRODUCT_ADD")
                .antMatchers("/product/update").hasAnyAuthority("PRODUCT_UPDATE")
                .antMatchers("/product/list").hasAnyAuthority("PRODUCT_LIST")
                .antMatchers("/product/delete").hasAnyAuthority("PRODUCT_DELETE")
                // permitAll all permissions can be accessed
                .antMatchers("/login").permitAll()
                .antMatchers("/ * *")
                // fullyAuthenticated does not allow anonymous users to view it
                .fullyAuthenticated()
                .and()
                / / httpbasic login
                // .httpBasic();
                // Form login Page for login request
                .formLogin().loginPage("/login")
                // Change the default login parameters provided by Spring
                // .usernameParameter("name")
                // .passwordParameter("password")
                .and()
                // Enable the Remember me function
                .rememberMe()
            	.and()
                // Enable logout
                .logout()
                .and()
                // Disable cross-domain protection.csrf().disable(); }}Copy the code

Build the error page configuration

Verify jump when no permission is available

package com.shaojie.authority.security;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/ * * *@author ShaoJie
 * @Date2019/10/25 * /
@Configuration
public class ErrorPageConfig {

    / / use replace EmbeddedServletContainerCustomizer WebServerFactoryCustomizer interface components complete configuration of embedded Servlet container
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(a){
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN,"/ 403")); }}; }}Copy the code
login.html
<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>The login page</h2>
    <form th:action="@{/userlogin}" method="post">Account:<input type="text" name="username"><br>Password:<input type="password" name="password"><br>
        <button type="submit">The login</button>
    </form>
</body>
</html>
Copy the code

Note the attribute name here

The default is username and password

	 * protected void configure(HttpSecurity http) throws Exception {
     * 		http.authorizeRequests().antMatchers(&quot;/**") .hasRole(" USER") .and().formLogin() * .usernameParameter(" username") // default is username * .passwordParameter(" password") // default is password * .loginPage(" /authentication/login") // default is /login with an HTTP get * .failureUrl(" /authentication/login? failed") // default is /login? error * .loginProcessingUrl(" /authentication/login/process") ; // default is /login * // with an HTTP * // post * }Copy the code
index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My page</title>
</head>
<body>Here are the features of the site<br>
    <a href="" th:href="@{product/add}">Addition of goods</a><br>
    <a href="" th:href="@{product/update}">Goods change</a><br>
    <a href="" th:href="@{product/list}">Product enquiry</a><br>
    <a href="" th:href="@{product/delete}">Deletion of goods</a>
</body>
</html>
Copy the code
403.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error page</title>
</head>
<body>You don't have access</body>
</html>
Copy the code
add.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Increase in product</title>
</head>
<body>Increase in product</body>
</html>
Copy the code
delete.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product deletion</title>
</head>
<body>Product deletion</body>
</html>

Copy the code
list.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product inquiry</title>
</head>
<body>Product inquiry</body>
</html>
Copy the code
update.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Product modification</title>
</head>
<body>Product modification</body>
</html>
Copy the code

The whole use of memory to do authorization verification, the subsequent arrangement based on JDBC to do authorization, the whole set of words, basically have a basic understanding of SpringSecurity, pit the first step recommended to start with the basics, most of the configuration recommended to view the official source code, for logout and remember the password, The details are explained in the source HttpSecurity class, which is not explained too much here. Only basic Demo examples are provided

If you like programming, please follow my blog at www.lzmvlog.top/