溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-03-08 07:29:42 來源:網(wǎng)絡(luò) 閱讀:1245 作者:lgx211 欄目:軟件技術(shù)

Spring Security

簡介

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

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

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

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

如果代碼中不做任何設(shè)置,默認的賬戶是 user,默認的密碼隨著項目的啟動,會打印在控制臺中。
SpringBoot學習(二)—— springboot快速整合spring security組件

輸入賬號密碼,即可進入默認的初始界面。
SpringBoot學習(二)—— springboot快速整合spring security組件

代碼實戰(zhàn)

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

新增代碼目錄
SpringBoot學習(二)—— springboot快速整合spring security組件

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 安全認證與授權(quán)
@EnableWebSecurity
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {

    //用戶認證
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //內(nèi)存里面放著
        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");
    }

    //用戶授權(quán)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * permitAll():允許一切用戶訪問
         * hasRole():url請求允許訪問的角色
         * hasAnyRole() : url請求允許訪問的多個角色
         * access():允許訪問的角色,permitAll、hasRole、hasAnyRole 底層都是調(diào)用 access 方法
         * access("permitAll") 等價于 permitAll()
         */
        http.authorizeRequests().antMatchers("/").permitAll(); // "/":應(yīng)用首頁所以用戶都可以訪問
        http.authorizeRequests()
                .antMatchers("/user/addUser").hasRole("AAA") // 首斜杠"/"表示應(yīng)用上下文,/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:指定支持基于表單的身份驗證
         * 當用戶沒有登錄、沒有權(quán)限時就會自動跳轉(zhuǎn)到登錄頁面(默認 /login)
         * 當?shù)卿浭r,默認跳轉(zhuǎn)到 /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 登錄(其角色權(quán)限為AAA),可以進入系統(tǒng),瀏覽器輸入地址可以訪問, localhost:8080,localhost:8080/user/addUser,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers

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

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

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

以用戶名 admin 登錄,不可以進入系統(tǒng),因為系統(tǒng)中還沒有該用戶。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI