首頁  >  文章  >  Java  >  SpringBoot SpringSecurity怎麼使用

SpringBoot SpringSecurity怎麼使用

WBOY
WBOY轉載
2023-05-19 17:20:08792瀏覽

SpringBoot已經為使用者採用預設配置,只需要引入pom依賴就能快速啟動Spring Security。
目的:驗證請求使用者的身份,提供安全存取
優勢:基於Spring,配置方便,減少大量程式碼

SpringBoot SpringSecurity怎麼使用

內建存取控制方法

  • permitAll() 表示所符合的URL 任何人都允許存取。

  • authenticated() 表示所符合的 URL 都需要被認證才能存取。

  • anonymous() 表示可以匿名存取符合的 URL 。和permitAll() 效果類似,只是設定為anonymous() 的url 會執行filter 鏈中

  • denyAll() 表示所符合的URL 都不允許被訪問。

  • rememberMe() 被「remember me」的用戶允許訪問這個有點類似於很多網站的十天內免登錄,登陸一次即可記住你,然後未來一段時間不用登入。

  • fullyAuthenticated() 如果使用者不是被 remember me 的,才可以存取。也就是必須一步一步按部就班的登入才行。

角色權限判斷

  • #hasAuthority(String) 判斷使用者是否具有特定的權限,使用者的權限是在自訂登入邏輯

  • hasAnyAuthority(String ...) 如果使用者擁有給定權限中某一個,就允許存取

  • hasRole(String) 如果使用者俱備給定角色就允許存取。否則出現403

  • hasAnyRole(String ...) 如果使用者俱備給定角色的任一個,就允許被存取

  • #hasIpAddress(String) 如果請求是指定的IP 就執行存取。可以透過request.getRemoteAddr() 取得ip 位址

引用Spring Security

Pom 檔案中新增

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<?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>

運行後會自動產生password 預設用戶名稱為: userSpringBoot SpringSecurity怎麼使用

預設配置每次都啟動專案都會重新產生密碼,同時使用者名稱和攔截要求也不能自訂,在實際應用程式中往往需要自訂配置,因此接下來對Spring Security進行自訂配置。

配置Spring Security (入門)

在記憶體中(簡化環節,了解邏輯)配置兩個使用者角色(admin和user),設定不同密碼;

同時設定角色訪問權限,其中admin可以存取所有路徑(即/*),user只能存取/user下的所有路徑。 自訂配置類,實現WebSecurityConfigurerAdapter接口,

WebSecurityConfigurerAdapter

接口中有兩個用到的configure()方法,其中一個配置用戶身份,另一個配置使用者權限:

設定使用者身分的configure()方法:

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();
    }
}

新增介面測試用SpringBoot SpringSecurity怎麼使用

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";
    }
}

#######

以上是SpringBoot SpringSecurity怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除