最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security注解方式權(quán)限控制過(guò)程

 更新時(shí)間:2025年03月12日 17:07:26   作者:今天的接口寫完了嗎?  
這篇文章主要介紹了Spring Security注解方式權(quán)限控制過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、摘要

Spring Security除了可以在配置文件中配置權(quán)限校驗(yàn)規(guī)則,還可以使用注解方式控制類 中方法的調(diào)用。

例如Controller中的某個(gè)方法要求必須具有某個(gè)權(quán)限才可以訪問(wèn),此時(shí)就 可以使用Spring Security框架提供的注解方式進(jìn)行控制。

二、實(shí)現(xiàn)步驟

2.1 在配置類中添加權(quán)限注解的支持

package com.by.config;

//import com.by.service.UserService;
import com.by.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security 核心配置
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//開(kāi)啟權(quán)限注解支持
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private UserService userService;
  @Autowired
  private PasswordEncoder passwordEncoder;
    /**
     * 配置認(rèn)證信息的來(lái)源
     * AuthenticationManagerBuilder認(rèn)證管理器
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置認(rèn)證提供者
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);//配置認(rèn)證提供者
        super.configure(auth);//密碼
    }

    /**
     * 配置web的安全(忽略的靜態(tài)資源)
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring().antMatchers("/pages/a.html","/pages/b.html");
         //web.ignoring().antMatchers("/pages/**");
        //指定login.html頁(yè)面可以匿名訪問(wèn)
        web.ignoring().antMatchers("/login.html");
    }

    /**
     * 配置HTTP請(qǐng)求的安全(認(rèn)證、授權(quán)、退出)
     * HttpSecurity 用于構(gòu)建一個(gè)安全過(guò)濾器鏈 SecurityFilterChain
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()
                .loginPage("/login.html")// 默認(rèn)頁(yè)面
                .loginProcessingUrl("/login")//請(qǐng)求
                .usernameParameter("username")
                .passwordParameter("password")
                // 請(qǐng)求成功后訪問(wèn)哪個(gè)路徑
                .defaultSuccessUrl("/index.html",true);
        //權(quán)限配置
        http.authorizeRequests()
               //.antMatchers("pages/a.html").authenticated()
                .antMatchers("/pages/b.html").hasAuthority("add")
                /**
                 * 擁有ROLE_ADMIN可以訪問(wèn)d頁(yè)面
                 * 注意:此處雖然寫的是ADMIN,但是框架會(huì)自動(dòng)添加前綴ROLE_
                 */
                .antMatchers("pages/c.html").hasRole("ADMIN")
//                其他資源均需要登錄后訪問(wèn)
                .anyRequest().authenticated();
//        super.configure(http);
        //關(guān)閉跨站請(qǐng)求防護(hù)
        http.csrf().disable();
    }

    /**
     * 配置加密對(duì)象
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

2.2 創(chuàng)建Controller類

在Controller的方法上加入注解進(jìn)行權(quán)限控制

package com.by.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/add")
    /**
     * 表示用戶要擁有add權(quán)限 才能訪問(wèn)該方法
     */
    @PreAuthorize("hasAuthority('add')")
    public String add(){
        System.out.println("add");
        return "success";
    }

}

2.3 UserService類

package com.by.service;

import com.by.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class UserService implements UserDetailsService {
    @Autowired
   private PasswordEncoder passwordEncoder;


    //模擬向數(shù)據(jù)庫(kù)中插入數(shù)據(jù)
    public Map<String, UserInfo> map = new HashMap<>();

    public void init() {
        UserInfo u1 = new UserInfo();
        u1.setUsername("admin");
        u1.setPassword(passwordEncoder.encode("123"));
        UserInfo u2 = new UserInfo();
        u2.setUsername("user");
        u2.setPassword(passwordEncoder.encode("123"));
        map.put(u1.getUsername(), u1);
        map.put(u2.getUsername(), u2);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        System.out.println("username:" + username);
        //模擬從數(shù)據(jù)庫(kù)中查詢用戶
        UserInfo userInfo = map.get(username);
        if (userInfo == null) {
            return null;
        }
        //模擬查詢數(shù)據(jù)庫(kù)中用戶的密碼  去掉明文標(biāo)識(shí){noop}
        String password = userInfo.getPassword();
        List<GrantedAuthority> list = new ArrayList<>();
        //授權(quán),后期需要改為查詢數(shù)據(jù)庫(kù)動(dòng)態(tài)獲得用戶擁有的權(quán)限和角色
        if (username.equals("admin")) {
            list.add(new SimpleGrantedAuthority("add"));
            list.add(new SimpleGrantedAuthority("delete"));
        }
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        User user = new User(username, password, list);
        return user;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            String password="123456";
            /**
             * BCryptPasswordEncoder是Spring Security
             * 提供的一個(gè)加密的API
             */
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String hashPassWord = bCryptPasswordEncoder.encode(password);
            System.out.println(hashPassWord);
            boolean flag = bCryptPasswordEncoder.matches("123456", hashPassWord);
            System.out.println(flag);

        }
    }
}

三、測(cè)試

可以看出admin有add方法的訪問(wèn)權(quán)限,而user則沒(méi)有add方法的訪問(wèn)權(quán)限

3.1 user測(cè)試

3.2 admin 測(cè)試

四、退出登錄功能

用戶完成登錄后Spring Security框架會(huì)記錄當(dāng)前用戶認(rèn)證狀態(tài)為已認(rèn)證狀態(tài),即表示用 戶登錄成功了。

那用戶如何退出登錄呢?我們可以配置類中進(jìn)行如下 配置:

package com.by.config;

//import com.by.service.UserService;
import com.by.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security 核心配置
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//開(kāi)啟權(quán)限注解支持
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private UserService userService;
  @Autowired
  private PasswordEncoder passwordEncoder;
    /**
     * 配置認(rèn)證信息的來(lái)源
     * AuthenticationManagerBuilder認(rèn)證管理器
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 配置認(rèn)證提供者
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);//配置認(rèn)證提供者
        super.configure(auth);//密碼
    }

    /**
     * 配置web的安全(忽略的靜態(tài)資源)
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring().antMatchers("/pages/a.html","/pages/b.html");
         //web.ignoring().antMatchers("/pages/**");
        //指定login.html頁(yè)面可以匿名訪問(wèn)
        web.ignoring().antMatchers("/login.html");
    }

    /**
     * 配置HTTP請(qǐng)求的安全(認(rèn)證、授權(quán)、退出)
     * HttpSecurity 用于構(gòu)建一個(gè)安全過(guò)濾器鏈 SecurityFilterChain
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()
                .loginPage("/login.html")// 默認(rèn)頁(yè)面
                .loginProcessingUrl("/login")//請(qǐng)求
                .usernameParameter("username")
                .passwordParameter("password")
                // 請(qǐng)求成功后訪問(wèn)哪個(gè)路徑
                .defaultSuccessUrl("/index.html",true);
        //權(quán)限配置
        http.authorizeRequests()
               //.antMatchers("pages/a.html").authenticated()
                .antMatchers("/pages/b.html").hasAuthority("add")
                /**
                 * 擁有ROLE_ADMIN可以訪問(wèn)d頁(yè)面
                 * 注意:此處雖然寫的是ADMIN,但是框架會(huì)自動(dòng)添加前綴ROLE_
                 */
                .antMatchers("pages/c.html").hasRole("ADMIN")
//                其他資源均需要登錄后訪問(wèn)
                .anyRequest().authenticated();
        /**
         * 退出登錄
         */
        http.logout()
                .logoutUrl("/logout")
                        .logoutSuccessUrl("/login.html").invalidateHttpSession(true);



//        super.configure(http);
        //關(guān)閉跨站請(qǐng)求防護(hù)
        http.csrf().disable();
    }

    /**
     * 配置加密對(duì)象
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

在a.html 設(shè)置一個(gè)退出登錄的超鏈接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我是b.html
<a href="/logout" rel="external nofollow" >退出登錄</a>
</body>
</html>

測(cè)試

登錄后訪問(wèn)localhost:8083/pages/a.html 然后點(diǎn)擊退出登錄。

如果用戶要退出登錄,只需要請(qǐng)求/logout這個(gè)URL地址就 可以,最后頁(yè)面會(huì)跳轉(zhuǎn)到login.html頁(yè)面

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java中對(duì)象調(diào)用成員變量與成員實(shí)例方法

    java中對(duì)象調(diào)用成員變量與成員實(shí)例方法

    在本篇文章里小編給各位分享的是關(guān)于java中對(duì)象調(diào)用成員變量與成員實(shí)例方法,需要的朋友們可以學(xué)習(xí)參考下。
    2020-02-02
  • Java如何根據(jù)實(shí)體指定字段值對(duì)其List進(jìn)行排序詳解

    Java如何根據(jù)實(shí)體指定字段值對(duì)其List進(jìn)行排序詳解

    在Java項(xiàng)目中可能會(huì)遇到給出一些條件,將List元素按照給定條件進(jìn)行排序的情況,這篇文章主要給大家介紹了關(guān)于Java如何根據(jù)實(shí)體指定字段值對(duì)其List進(jìn)行排序的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-07-07
  • 關(guān)于SpringSecurity認(rèn)證邏輯源碼分析

    關(guān)于SpringSecurity認(rèn)證邏輯源碼分析

    這篇文章主要介紹了關(guān)于SpringSecurity認(rèn)證邏輯源碼分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • 快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載)

    快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載)

    這篇文章主要介紹了快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • Springboot錯(cuò)誤頁(yè)面和錯(cuò)誤信息定制操作

    Springboot錯(cuò)誤頁(yè)面和錯(cuò)誤信息定制操作

    這篇文章主要介紹了Springboot錯(cuò)誤頁(yè)面和錯(cuò)誤信息定制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Spring Boot2.0中SpringWebContext找不到無(wú)法使用的解決方法

    Spring Boot2.0中SpringWebContext找不到無(wú)法使用的解決方法

    這篇文章主要給大家介紹了關(guān)于Spring Boot2.0中SpringWebContext找不到無(wú)法使用的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • Java8中創(chuàng)建Stream流的幾種常見(jiàn)方式

    Java8中創(chuàng)建Stream流的幾種常見(jiàn)方式

    在Java 8中,??Stream?? API 是一種新的處理數(shù)據(jù)的方式,它允許以聲明式的方式來(lái)處理數(shù)據(jù)集合,本文將詳細(xì)介紹在Java 8中創(chuàng)建 ??Stream?? 流的幾種常見(jiàn)方式,大家可以根據(jù)需要進(jìn)行選擇
    2025-05-05
  • Mybatis中如何設(shè)置sqlSession自動(dòng)提交

    Mybatis中如何設(shè)置sqlSession自動(dòng)提交

    在MyBatis中,默認(rèn)情況下,獲取的SqlSession對(duì)象不會(huì)自動(dòng)提交事務(wù),這意味著在進(jìn)行更新、刪除或插入等操作后,需要顯式調(diào)用commit方法來(lái)提交事務(wù),但是,可以在獲取SqlSession時(shí)通過(guò)將openSession方法的參數(shù)設(shè)置為true
    2024-09-09
  • JVM:早期(編譯期)優(yōu)化的深入理解

    JVM:早期(編譯期)優(yōu)化的深入理解

    今天小編就為大家分享一篇關(guān)于JVM:早期(編譯期)優(yōu)化的深入理解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • Spring Statemachine 狀態(tài)機(jī)詳解

    Spring Statemachine 狀態(tài)機(jī)詳解

    SpringStatemachine是Spring應(yīng)用中的狀態(tài)機(jī)框架,支持復(fù)雜狀態(tài)轉(zhuǎn)換,適用于訂單系統(tǒng)等場(chǎng)景,核心概念包括狀態(tài)、事件、轉(zhuǎn)換,提供守衛(wèi)、動(dòng)作、并行處理等高級(jí)功能,并支持持久化與可視化,本文給大家介紹Spring Statemachine的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2025-09-09

最新評(píng)論

九寨沟县| 鸡西市| 台南市| 来安县| 通河县| 大连市| 孝义市| 治多县| 鸡西市| 盘山县| 乌拉特后旗| 读书| 德兴市| 上林县| 凤阳县| 襄汾县| 新津县| 淮南市| 邯郸县| 卢氏县| 儋州市| 丽水市| 玉环县| 巩留县| 泸溪县| 潞西市| 望都县| 万年县| 海口市| 台北县| 沂水县| 星子县| 汾阳市| 金寨县| 泾源县| 柘城县| 张家口市| 砀山县| 吴江市| 建德市| 禄丰县|