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

 更新时间:2021年06月19日 14:47:34   作者:别团等shy哥发育  
本文给大家分享SpringSecurity配置403权限访问页面的完整代码,配置之前和配置之后的详细介绍,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

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权限访问页面的资料请关注脚本之家其它相关文章!

相关文章

  • springboot开启声明式事务的方法

    springboot开启声明式事务的方法

    本篇文章主要介绍了springboot开启声明式事务的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • 微服务Spring Boot 整合Redis 阻塞队列实现异步秒杀下单思路详解

    微服务Spring Boot 整合Redis 阻塞队列实现异步秒杀下单思路详解

    这篇文章主要介绍了微服务Spring Boot 整合Redis 阻塞队列实现异步秒杀下单,使用阻塞队列实现秒杀的优化,采用异步秒杀完成下单的优化,本文给大家分享详细步骤及实现思路,需要的朋友可以参考下
    2022-10-10
  • Micronaut框架的简单使用介绍

    Micronaut框架的简单使用介绍

    这篇文章主要介绍了Micronaut框架的简单使用介绍,帮助大家更好的理解和学习使用Micronaut,感兴趣的朋友可以了解下
    2021-04-04
  • 解析ConcurrentHashMap: put方法源码分析

    解析ConcurrentHashMap: put方法源码分析

    ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成。Segment的结构和HashMap类似,是一种数组和链表结构,今天给大家普及java面试常见问题---ConcurrentHashMap知识,一起看看吧
    2021-06-06
  • Java多线程之异步Future机制的原理和实现

    Java多线程之异步Future机制的原理和实现

    这篇文章主要为大家详细介绍了Java多线程之异步Future机制的原理和实现,感兴趣的小伙伴们可以参考一下
    2016-08-08
  • 关于@Entity和@Table注解的用法详解

    关于@Entity和@Table注解的用法详解

    这篇文章主要介绍了关于@Entity和@Table注解的用法详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • Java集合WeakHashMap源码分析

    Java集合WeakHashMap源码分析

    这篇文章主要介绍了Java集合WeakHashMap源码分析,和HashMap一样,WeakHashMap 也是一个散列表,它存储的内容也是键值对(key-value)映射,而且键和值都可以是null,需要的朋友可以参考下
    2023-09-09
  • java对接微信支付之JSAPI支付(微信公众号支付)

    java对接微信支付之JSAPI支付(微信公众号支付)

    这篇文章主要给大家介绍了关于java对接微信支付之JSAPI支付(微信公众号支付)的相关资料,微信JSAPI支付是近年来非常流行的一种支付方式,它使用了微信支付的SDK和demo来实现支付接口的对接,需要的朋友可以参考下
    2023-07-07
  • org.apache.zookeeper.KeeperException.BadVersionException异常的解决

    org.apache.zookeeper.KeeperException.BadVersionException异常的解

    在使用Apache ZooKeeper进行分布式协调时,你可能会遇到org.apache.zookeeper.KeeperException.BadVersionException异常,本文就来介绍一下解决方法,感兴趣的可以了解一下
    2024-03-03
  • maven打包插件的使用(maven-compiler-plugin、maven-dependency-plugin、maven-jar-plugin、maven-resources-plugin)

    maven打包插件的使用(maven-compiler-plugin、maven-dependency-plugin、m

    本文主要介绍了maven打包插件的使用(maven-compiler-plugin、maven-dependency-plugin、maven-jar-plugin、maven-resources-plugin),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06

最新评论