iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >关于SpringSecurity配置403权限访问页面的完整代码
  • 501
分享到

关于SpringSecurity配置403权限访问页面的完整代码

2024-04-02 19:04:59 501人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录1、未配置之前2、开始配置 2.1 新建一个unauth.html2.2 在继承WEBSecurityConfigurerAdapter的配置类中设置2.3 继承Use

1、未配置之前

在这里插入图片描述

2、开始配置

 2.1 新建一个unauth.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>没有访问的权限</h1>
</body>
</html>

2.2 在继承WebSecurityConfigurerAdapter的配置类中设置

关键代码:


//配置没有权限访问自定义跳转的页面
  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();

        //配置没有权限访问自定义跳转的页面
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.fORMLogin()             //自定义自己编写的登陆页面
            .loginPage("/login.html")    //登录页面设置
            .loginProcessingUrl("/user/login") //登录访问路径
            .defaultSuccessUrl("/success.html").permitAll()    //登录成功之后,跳转路径
            .and().authorizeRequests()
               //设置哪些路径可以直接访问,不需要认证
                .antMatchers("/","/test/hello","/user/login").permitAll()
                //当前登录的用户,只有具有admins权限才可以访问这个路径
               //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();    //关闭csrf防护
    }
}

2.3 继承UserDetailsService接口的实现类


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 {

        //调用userMapper中的方法,根据用户名查询数据库
        QueryWrapper<Users> wrapper=new QueryWrapper<>();//条件构造器
        //where username=?
        wrapper.eq("username",username);
        Users users= usersMapper.selectOne(wrapper);
        //判断
        if(users==null){    //数据库没有用户名,认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }

        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        //从查询数据库返回user对象,得到用户名和密码,返回
        return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }

}

3、测试

现在我故意将原先的sale改为sale1制造错误

在这里插入图片描述

启动项目并访问http://localhost:8111/test/index

在这里插入图片描述

输入lucy 123

在这里插入图片描述

成功实现

以上就是SpringSecurity配置403权限访问页面的详细内容,更多关于SpringSecurity权限访问页面的资料请关注编程网其它相关文章!

--结束END--

本文标题: 关于SpringSecurity配置403权限访问页面的完整代码

本文链接: https://www.lsjlt.com/news/128585.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作