溫馨提示×

溫馨提示×

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

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

spring security怎么配置403權(quán)限訪問頁面

發(fā)布時(shí)間:2021-06-21 10:03:24 來源:億速云 閱讀:365 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要介紹“spring security怎么配置403權(quán)限訪問頁面”,在日常操作中,相信很多人在spring security怎么配置403權(quán)限訪問頁面問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”spring security怎么配置403權(quán)限訪問頁面”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

1、未配置之前

spring security怎么配置403權(quán)限訪問頁面

2、開始配置

 2.1 新建一個(gè)unauth.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>沒有訪問的權(quán)限</h2>
</body>
</html>

2.2 在繼承WebSecurityConfigurerAdapter的配置類中設(shè)置

關(guān)鍵代碼:

//配置沒有權(quán)限訪問自定義跳轉(zhuǎn)的頁面
  http.exceptionHandling()
  .accessDeniedPage("/unauth.html");

配置類完整代碼:

package com.atguigu.springsecuritydemo1.config;

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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password(){
       return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //退出配置
        http.logout().logoutUrl("/logout")
                .logoutSuccessUrl("/test/hello")
                .permitAll();

        //配置沒有權(quán)限訪問自定義跳轉(zhuǎn)的頁面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin()             //自定義自己編寫的登陸頁面
            .loginPage("/login.html")    //登錄頁面設(shè)置
            .loginProcessingUrl("/user/login") //登錄訪問路徑
            .defaultSuccessUrl("/success.html").permitAll()    //登錄成功之后,跳轉(zhuǎn)路徑
            .and().authorizeRequests()
               //設(shè)置哪些路徑可以直接訪問,不需要認(rèn)證
                .antMatchers("/","/test/hello","/user/login").permitAll()
                //當(dāng)前登錄的用戶,只有具有admins權(quán)限才可以訪問這個(gè)路徑
               //1、hasAuthority方法
               //.antMatchers("/test/index").hasAuthority("admins")
               //2、hasAnyAuthority方法
              // .antMatchers("/test/index").hasAnyAuthority("admins,manager")
              //3、hasRole方法  ROLE_sale
               .antMatchers("/test/index").hasRole("sale")
                //4、hasAnyRole方法

            .anyRequest().authenticated()
            .and().csrf().disable();    //關(guān)閉csrf防護(hù)
    }
}

2.3 繼承UserDetailsService接口的實(shí)現(xiàn)類

package com.atguigu.springsecuritydemo1.service;

import com.atguigu.springsecuritydemo1.entity.Users;
import com.atguigu.springsecuritydemo1.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.stereotype.Service;

import java.util.List;

@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //調(diào)用userMapper中的方法,根據(jù)用戶名查詢數(shù)據(jù)庫
        QueryWrapper<Users> wrapper=new QueryWrapper<>();//條件構(gòu)造器
        //where username=?
        wrapper.eq("username",username);
        Users users= usersMapper.selectOne(wrapper);
        //判斷
        if(users==null){    //數(shù)據(jù)庫沒有用戶名,認(rèn)證失敗
            throw new UsernameNotFoundException("用戶名不存在!");
        }

        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        //從查詢數(shù)據(jù)庫返回user對象,得到用戶名和密碼,返回
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }

}

3、測試

現(xiàn)在我故意將原先的sale改為sale1制造錯(cuò)誤

spring security怎么配置403權(quán)限訪問頁面

啟動(dòng)項(xiàng)目并訪問http://localhost:8111/test/index

spring security怎么配置403權(quán)限訪問頁面

輸入lucy 123

spring security怎么配置403權(quán)限訪問頁面

成功實(shí)現(xiàn)

到此,關(guān)于“spring security怎么配置403權(quán)限訪問頁面”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

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

AI