一分鐘帶你瞭解下Spring Security!

1、什麼是Spring Security?

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

Spring Security是一個框架,致力於爲Java應用程序提供身份驗證和受權。與全部Spring項目同樣,Spring Security的真正強大之處在於能夠輕鬆擴展以知足自定義要求。git

更多信息能夠查看官網:https://spring.io/projects/spring-securitygithub

2、Spring Security的主要功能

  • 認證:驗證用戶名和密碼是否合法(是否系統中用戶)
  • 受權:是系統用戶不表明你能使用某些功能,由於你可能沒有權限
  • 防護會話固定,點擊劫持,跨站點請求僞造等攻擊
  • Servlet API集成
  • 與Spring Web MVC的可選集成

3、快速入門

新建一個SpringBoot的web項目spring-boot-security。web

案例1:接口不添加保護

pom文件中不引入Spring Security,而後新建一個controller:spring

@RestController
public class AppController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello,spring security!";
    }
}

而後打開瀏覽器訪問:http://localhost:8080/hello,成功後返回:瀏覽器

Hello,spring security!

案例2:接口添加保護

  1. pom文件添加依賴

pom文件中引入Spring Security的starter:springboot

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
  1. 訪問接口

打開瀏覽器再次訪問http://localhost:8080/hello,會被重定向到登陸頁http://localhost:8080/login,截圖以下:mybatis

默認登陸頁

要登陸系統,咱們須要知道用戶名和密碼,Spring Security默認的用戶名是user,項目啓動的時候會生成默認密碼(在啓動日誌中能夠看到),輸入用戶名和密碼後就能夠訪問/hello接口了。架構

固然也能夠自定義用戶名密碼,在配置文件添加以下內容便可:app

spring.security.user.name=java_suisui
spring.security.user.password=123456

4、自定義認證和受權

上面說過Spring Security的功能有「認證」和「受權」,下面經過一個簡單的例子實現下自定義的認證和受權。

假設系統中有兩個角色:

  • ADMIN 能夠訪問/admin下的資源
  • USER 能夠訪問/user下的資源

按照下面步驟操做便可。

  1. 新建一個配置類

對於用戶名、密碼、登陸頁面、訪問權限等均可以在 WebSecurityConfigurerAdapter 的實現類中配置。

WebSecurityConfig代碼以下:

/**
 * 配置類
 * @Author java_suisui
 *
 */
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置內存中的 用戶名、密碼和角色
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("user").password("123456").roles("USER");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/user").hasRole("USER") //訪問 /user這個接口,須要有USER角色
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated() //剩餘的其餘接口,登陸以後就能訪問
                .and()
                .formLogin().defaultSuccessUrl("/hello");
    }
}
  1. 建立PasswordEncorder的實現類

內存用戶驗證時,Spring Boot 2.0以上版本引用的security 依賴是 spring security 5.X版本,此版本須要提供一個PasswordEncorder的實例。

MyPasswordEncoder代碼以下:

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encodedPassword.equals(rawPassword);
    }
}
  1. 登陸驗證

瀏覽器打開http://localhost:8080/login,

  • 使用user登陸,能夠訪問/user
  • 使用admin登陸,能夠訪問/admin

若是使用user登陸後訪問/admin,會報403錯誤,具體錯誤信息以下:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Nov 19 16:26:28 CST 2019
There was an unexpected error (type=Forbidden, status=403).
Forbidden

結果和咱們預期的一致,說明簡單的自定義認證和受權功能已經實現了。

完整源碼地址: https://github.com/suisui2019/springboot-study

推薦閱讀

1.一分鐘帶你學會利用mybatis-generator自動生成代碼!

2.手把手帶你實戰下Spring的七種事務傳播行爲

3.SpringBoot系列-整合Mybatis(註解方式)

4.SpringBoot系列-整合Mybatis(XML配置方式)

5.Java中打印日誌,這4點很重要!


Java碎碎念,一個堅持原創的公衆號,爲您提供一系列系統架構、微服務、Java、SpringBoot、SpringCloud等高質量技術文章。
若是以爲文章不錯,但願能夠隨手轉發或者」在看「哦,很是感謝哈!
關注下方公衆號後回覆「1024」,有驚喜哦!

本文由博客一文多發平臺 OpenWrite 發佈!

相關文章
相關標籤/搜索