SpringBoot學習(二)—— springboot快速整合使用spring security組

Spring Security

簡介

spring security的核心功能爲認證(Authentication),授權(Authorization),即認證用戶是否能訪問該系統,和授權用戶可以在系統中進行哪些操作。

引入spring security組件

在 pom.xml 中加入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

驗證組件是否起到作用,現在不更改框架內的任何內容,啓動項目,瀏覽器中依舊輸入 http://localhost:8080 ,可看到如下界面,之前可以直接進入spring boot的初始界面,現在已經看不見了,spring security 導入後默認已經開啓了驗證,必須先登錄驗證通過後才能訪問。

\[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-4UZ4rXKM-1573807374683)(assets/1573802625147.png)\]

如果代碼中不做任何設置,默認的賬戶是 user,默認的密碼隨着項目的啓動,會打印在控制檯中。
在這裏插入圖片描述

輸入賬號密碼,即可進入默認的初始界面。
在這裏插入圖片描述

代碼實戰

爲了最快最簡單最直接的認識這個組件,直接把用戶密碼寫入內存中,項目啓動即存在,避免還有建表,實體類,數據庫操作等與之無關的內容。命名使用最爲簡單粗暴的方式,排除一切干擾,用最少的精力掌握該組件的使用。

新增代碼目錄
在這裏插入圖片描述

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    SPRING BOOT !!!
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    錯誤
</body>
</html>

UserController

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("/addUser")
    @ResponseBody
    String addUser() {
        return "這是添加用戶!!!";
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    String deleteUser() {
        return "這是刪除用戶!!!";
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    String updateUser() {
        return "這是修改用戶!!!";
    }

    @RequestMapping("/findAllUsers")
    @ResponseBody
    String findAllUsers() {
        return "這是查詢用戶!!!";
    }

}

UserSecurityConfig

package com.example.config;

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;

//註解開啓 Spring Security 安全認證與授權
@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    //用戶認證
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //內存裏面放着
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                //添加用戶,密碼,角色
                .withUser("zs").password("123456").roles("AAA")
                //鏈式編程
                .and()
                .withUser("ls").password("123456").roles("BBB")
                .and()
                .withUser("ww").password("123456").roles("CCC", "primary")
                .and()
                .withUser("zl").password("123456").roles("primary");
    }

    //用戶授權
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * permitAll():允許一切用戶訪問
         * hasRole():url請求允許訪問的角色
         * hasAnyRole() : url請求允許訪問的多個角色
         * access():允許訪問的角色,permitAll、hasRole、hasAnyRole 底層都是調用 access 方法
         * access("permitAll") 等價於 permitAll()
         */
        http.authorizeRequests().antMatchers("/").permitAll(); // "/":應用首頁所以用戶都可以訪問
        http.authorizeRequests()
                .antMatchers("/user/addUser").hasRole("AAA") // 首斜槓"/"表示應用上下文,/user/addUser 請求允許 AAA 角色訪問
                .antMatchers("/user/deleteUser/**").hasAnyRole("AAA", "BBB") //"/user/deleteUser/**"允許 "AAA", "BBB" 角色訪問,/**匹配任意
                .antMatchers("/user/updateUser").hasAnyRole("AAA", "BBB", "CCC")//除了這種鏈式編程,也可以分開寫
                .antMatchers("/user/findAllUsers").access("permitAll");

        http.authorizeRequests().anyRequest().authenticated();

        /**
         * formLogin:指定支持基於表單的身份驗證
         * 當用戶沒有登錄、沒有權限時就會自動跳轉到登錄頁面(默認 /login)
         * 當登錄失敗時,默認跳轉到 /error
         * 登錄成功時會放行
         */
        http.formLogin();
    }

}

MyPasswordEncoder

package com.example.config;

import org.springframework.security.crypto.password.PasswordEncoder;

//密碼編碼,Spring Security 高版本必須進行密碼編碼,否則報錯
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}

親測效果是

以用戶名 zs 登錄(其角色權限爲AAA),可以進入系統,瀏覽器輸入地址可以訪問, localhost:8080,localhost:8080/user/addUser,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用戶名 ls 登錄(其角色權限爲BBB),可以進入系統,瀏覽器輸入地址可以訪問, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用戶名 ww 登錄(其角色權限爲CCC),可以進入系統,瀏覽器輸入地址可以訪問, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用戶名 zl 登錄(其角色權限爲CCC),可以進入系統,瀏覽器輸入地址可以訪問, localhost:8080,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

以用戶名 admin 登錄,不可以進入系統,因爲系統中還沒有該用戶。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章