Home > Java > javaTutorial > body text

How to use SpringBoot SpringSecurity

WBOY
Release: 2023-05-19 17:20:08
forward
801 people have browsed it

SpringBoot has adopted the default configuration for users, and only needs to introduce pom dependencies to quickly start Spring Security.
Purpose: Verify the identity of the requesting user and provide secure access
Advantages: Based on Spring, easy to configure, reduce a lot of code

How to use SpringBoot SpringSecurity

Built-in access control method

  • permitAll() means that anyone is allowed to access the matched URL.

  • authenticated() means that the matched URLs need to be authenticated before they can be accessed.

  • anonymous() indicates that the matching URL can be accessed anonymously. The effect is similar to permitAll(), except that the URL set to anonymous() will execute

  • denyAll() in the filter chain, which means that the matched URLs are not allowed to be access.

  • rememberMe() Users who are "remember me" are allowed to access this website, which is similar to many websites. There is no need to log in for ten days. You can remember you after logging in once. Then you don’t need to log in for a while.

  • fullyAuthenticated() Access is only possible if the user is not remembered me. That is to say, you must log in step by step.

Role permissions judgment

  • hasAuthority(String) Determines whether the user has specific permissions. The user's permissions are Custom login logic

  • hasAnyAuthority(String ...) If the user has one of the given permissions, access is allowed

  • hasRole(String) Allow access if the user has the given role. Otherwise, 403

  • hasAnyRole(String ...) If the user has any one of the given roles, access is allowed

  • hasIpAddress(String) If the request is for the specified IP, the access will be run. You can get the ip address through request.getRemoteAddr()

Reference Spring Security

Add in the Pom file

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Copy after login
<?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">
    <parent>
        <artifactId>vipsoft-parent</artifactId>
        <groupId>com.vipsoft.boot</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>vipsoft-security</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.7</version>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy after login

The password default user will be automatically generated after running Named: user

How to use SpringBoot SpringSecurity

#The default configuration will regenerate the password every time the project is started. At the same time, the user name and interception requests cannot be customized. In actual applications, customized configuration is often required. , so next perform custom configuration of Spring Security.

Configuring Spring Security (Getting Started)

Configure two user roles (admin and user) in memory (to simplify the process and understand the logic), and set different passwords;
Set role access at the same time Permissions, where admin can access all paths (i.e. /*), and user can only access all paths under /user.

Custom configuration class, implements the WebSecurityConfigurerAdapter interface, WebSecurityConfigurerAdapter There are two configure() methods used in the interface, one of which configures the user identity and the other configures User permissions:

configure() method to configure user identity:

SecurityConfig

package com.vipsoft.web.config;
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 配置用户身份的configure()方法
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin")
                .password(passwordEncoder.encode("888"))
                .roles("ADMIN")
                .and()
                .withUser("user")
                .password(passwordEncoder.encode("666"))
                .roles("USER");
    }
    /**
     * 配置用户权限的configure()方法
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置拦截的路径、配置哪类角色可以访问该路径
                .antMatchers("/user").hasAnyRole("USER")
                .antMatchers("/*").hasAnyRole("ADMIN")
                //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面
                .and().formLogin();
    }
}
Copy after login

Add interface testing

package com.vipsoft.web.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DefaultController {
    @GetMapping("/")
    @PreAuthorize("hasRole(&#39;ADMIN&#39;)")
    public String demo() {
        return "Welcome";
    }
    @GetMapping("/user/list")
    @PreAuthorize("hasAnyRole(&#39;ADMIN&#39;,&#39;USER&#39;)")
    public String getUserList() {
        return "User List";
    }
    @GetMapping("/article/list")
    @PreAuthorize("hasRole(&#39;ADMIN&#39;)")
    public String getArticleList() {
        return "Article List";
    }
}
Copy after login

How to use SpringBoot SpringSecurity

The above is the detailed content of How to use SpringBoot SpringSecurity. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!