Spring Security 基礎教程 -- 自定義用戶名密碼


Spring Security 簡介

Spring Security 是一個功能強大且高度可定制的身份驗證和訪問控制框架。 它是用於保護基於 Spring 的應用程序的實際標准。

Spring Security 是一個框架,致力於為 Java 應用程序提供身份驗證和授權。 像所有 Spring 項目一樣,Spring Security 的真正強大之處在於可以輕松擴展以滿足自定義要求。

特點

  • 對身份驗證和授權的全面且可擴展的支持

  • 防御會話固定,點擊劫持,跨站點請求偽造等攻擊

  • Servlet API 集成

  • 與 Spring Web MVC 的可選集成

Spring Security 官網:

https://spring.io/projects/spring-security

https://github.com/spring-projects/spring-security

Spring Security 初體驗

添加依賴:

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

寫一個 Controller 類:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "Hello Security!";
    }
}

運行項目,訪問http://localhost:8080/hello,回車,如下圖:

只要在項目中間加入了 Spring Security 依賴,所有的地址請求都受到訪問控制。

在沒有手動設置用戶名和密碼的時候,默認用戶名為 user,默認密碼是一個隨機字符串,被打印在控制台中:

輸入默認用戶名和默認密碼,就能訪問 /hello 接口了:

每次使用默認密碼,十分麻煩。接下來就自定義用戶名和密碼。

Spring Security 手動設置用戶名和密碼

有兩種方式來設置用戶名和密碼,一是在 application.properties 文件中配置,二是寫一個 config 類,繼承 WebSecurityConfigurerAdapter ,重寫方法 configure(AuthenticationManagerBuilder auth) 來設置。

方法一:application.properties 文件中配置

配置如下:

spring.security.user.name=user
spring.security.user.password=123456
# 指定用戶角色
spring.security.user.roles=admin

三行配置搞定。需要注意的是,需要給用戶指定角色,在 Spring Security 中,是通過用戶的角色進行訪問權限控制的。

方法二:寫一個 config 類

寫一個 config 類,繼承 WebSecurityConfigurerAdapter ,重寫方法 configure(AuthenticationManagerBuilder auth) :

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 這是一個過期的方法
     * 指明密碼不用加密
     */
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 定義兩個用戶,並設置密碼和角色
     * 從 Spring5.0 開始,密碼必須要加密
     * 基於內存的用戶認證
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("123456")
                .roles("admin")
                .and()
                .withUser("user1")
                .password("123")
                .roles("user");
    }
}

上面,創建了兩個用戶:admin、user1,並分別賦予角色 admin 和 user 。

每天學習一點點,每天進步一點點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM