spring security - 快速整合 springboot

这篇具有很好参考价值的文章主要介绍了spring security - 快速整合 springboot。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>


2.配置 application.properties

server.port=8086
#
spring.application.name=security-sample
spring.main.allow-bean-definition-overriding=true
spring.mvc.static-path-pattern=/static/**
# thymeleaf 配置
spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# 数据库配置
spring.datasource.name=defaultDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_plain?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root123
# 连接池配置
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=8
spring.datasource.hikari.minimum-idle=4
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=50000
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.pool-name=HikariCP
# mybatis 配置
mybatis.mapper-locations=classpath:mappers/*xml
mybatis.type-aliases-package=com.sky.biz.entity
mybatis.configuration.map-underscore-to-camel-case=true


3.定制开发 - 认证流程的 UserDetailsService

说明:UserDetailsService 负责在 Security 框架中从数据源中查询出2大主要信息,
分别为:认证信息(账号、密码)、授权信息(角色列表、权限列表)。随后将这些信息封装为 UserDetails 对象返回
留作后续进行登录认证以及权限判断。

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermsService permsService;

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

        BizUser bizUser = userService.queryByUserName(username);
        // 用户存在,查询封装用户的"角色与权限"信息到 UserDetails中,通常自定义封装对象,继承 UserDetails的子类 User
        if(bizUser != null) {
            // 使用 authorityList 封装角色权限信息
            List<GrantedAuthority> authorityList = new ArrayList<>();
            // 查询当前用户 - 角色信息
            List<Role> roleList = roleService.getRoleListByUserId(bizUser.getId());
            for (Role role : roleList) {
                authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
            }
            // 查询当前用户 - 权限信息
            List<Perms> permsList = permsService.getPermsListByUserId(bizUser.getId());
            for (Perms perm : permsList) {
                authorityList.add(new SimpleGrantedAuthority(perm.getPermCode()));
            }
            return new SecurityUser(bizUser, authorityList);
        }

        return null;
    }

}

4.定义封装安全信息的实体类:SecurityUser

public class SecurityUser extends User {

    private BizUser bizUser;

    public SecurityUser(BizUser user, Collection<? extends GrantedAuthority> authorities) {
        super(user.getUserName(), user.getPassword(), true,true, true, true, authorities);
        this.bizUser = user;
    }

    public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    // get && set
    public BizUser getBizUser() {
        return bizUser;
    }

    public void setBizUser(BizUser bizUser) {
        this.bizUser = bizUser;
    }
}

5.自定义密码校验的类:PasswordEncoder,这里自由发挥,根据各自公司安全需要自定义

主要就是重写 encode(CharSequence rawPassword)  和  matches(CharSequence rawPassword, String encodedPassword) 方法
如果不想自定义就配置成spring-security提供的 BCryptPasswordEncoder 来处理密码加密与校验

6.配置Security

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的细粒度权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    // 配置对 HTTP 请求的安全拦截处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin()
                .and().csrf().disable()
                .formLogin().loginPage("/login").loginProcessingUrl("/doLogin")
                .defaultSuccessUrl("/main") 
                .failureUrl("/fail")  
                .permitAll();

        // "/login","/main"与"/fail",都是对应 html页面访问controller跳转路径
        // 用户权限不够,处理并返回响应
        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

                String header = request.getHeader("X-Requested-With");

                if("XMLHttpRequest".equals(header)) {
                    response.getWriter().print("403"); // 返回ajax 请求对应的 json格式
                } else {
                    request.getRequestDispatcher("/error403").forward(request, response);
                }
            }
        });

    }


    @Bean
    public MyPasswordEncoder passwordEncoder() {
        return new MyPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(new passwordEncoder());
        // 或者:auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

    }
}


7.使用加密时:
    @Autowired
    private MyPasswordEncoder passwordEncoder;

    // 方法1:
    String encodePwd = passwordEncoder.encode(user.getPassword());
    // 方法2:
    String encodePwd = new BCryptPasswordEncoder().encode(user.getPassword());

    user.setPassword(encodePwd);

    userMapper.save(user);

大体整合完成!

文章来源地址https://www.toymoban.com/news/detail-695577.html

到了这里,关于spring security - 快速整合 springboot的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot整合Spring Security实现权限控制

    要对Web资源进行保护,最好的办法莫过于Filter 要想对方法调用进行保护,最好的办法莫过于AOP。 Spring Security进行认证和鉴权的时候,就是利用的一系列的Filter来进行拦截的。 如图所示,一个请求想要访问到API就会从左到右经过蓝线框里的过滤器,其中 绿色部分是负责认证的

    2024年02月15日
    浏览(30)
  • spring-security-oauth2-authorization-server(一)SpringBoot3.1.3整合

    因为SpringBoot3.x是目前最新的版本,整合spring-security-oauth2-authorization-server的资料很少,所以产生了这篇文章,主要为想尝试SpringBoot高版本,想整合最新的spring-security-oauth2-authorization-server的初学者,旨在为大家提供一个简单上手的参考,如果哪里写得不对或可以优化的还请大家

    2024年02月03日
    浏览(33)
  • 快速上手Spring Boot整合,开发出优雅可靠的Web应用!

    SpringBoot 是由 Pivotal 团队提供的全新框架,其设计目的是用来 简化 Spring 应用的 初始搭建 以及 开发过程 。 使用了 Spring 框架后已经简化了我们的开发。而 SpringBoot 又是对 Spring 开发进行简化的,可想而知 SpringBoot 使用的简单及广泛性。既然 SpringBoot 是用来简化 Spring 开发的,

    2024年02月21日
    浏览(31)
  • Springboot 实践(13)spring boot 整合RabbitMq

    前文讲解了RabbitMQ的下载和安装,此文讲解springboot整合RabbitMq实现消息的发送和消费。 1、创建web project项目,名称为“SpringbootAction-RabbitMQ” 2、修改pom.xml文件,添加amqp使用jar包    !--  RabbitMQ --         dependency             groupIdorg.springframework.boot/groupId         

    2024年02月09日
    浏览(42)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 gateway 完成授权认证(拥抱 springboot 3.1)

    目录 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基础 spring security OAuth2 模块构成 授权方式 认证方式 集成过程 官方demo 代码集成 依赖 授权服务AuthorizationServerConfig配置 重要组件 测试 查看授权服务配置 访问授权服务 授权 回调 获取 access_token 获取用户信息 个性

    2024年02月08日
    浏览(47)
  • Spring Security Oauth2.1 最新版 1.1.0 整合 (基于 springboot 3.1.0)gateway 完成授权认证

    目录 背景 demo地址 版本 Spring Boot 3.1 Spring Authorization Server 1.1.0 基础 spring security OAuth2 模块构成 授权方式 认证方式 集成过程 官方demo 代码集成 依赖 授权服务AuthorizationServerConfig配置 重要组件 测试 查看授权服务配置 访问授权服务 授权 回调 获取 access_token 获取用户信息 个性

    2024年02月11日
    浏览(41)
  • 【SpringBoot】Spring Boot 项目中整合 MyBatis 和 PageHelper

    目录 前言         步骤 1: 添加依赖 步骤 2: 配置数据源和 MyBatis 步骤 3: 配置 PageHelper 步骤 4: 使用 PageHelper 进行分页查询 IDEA指定端口启动 总结         Spring Boot 与 MyBatis 的整合是 Java 开发中常见的需求,特别是在使用分页插件如 PageHelper 时。PageHelper 是一个针对 MyBat

    2024年04月25日
    浏览(34)
  • 【Spring Boot】SpringBoot 优雅整合Swagger Api 自动生成文档

    Swagger 是一套 RESTful API 文档生成工具,可以方便地生成 API 文档并提供 API 调试页面。 而 Spring Boot 是一款非常优秀的 Java Web 开发框架,它可以非常方便地构建 Web 应用程序。 在本文中,我们将介绍如何使用 Swagger 以及如何在 Spring Boot 中整合 Swagger 。 首先,在 pom.xml 文件中添

    2023年04月22日
    浏览(34)
  • SpringBoot-1-Spring Boot实战:快速搭建你的第一个应用,以及了解原理

    SpringBootWeb入门 我们在之前介绍Spring的时候,已经说过Spring官方(Spring官方)提供很多开源项目,点击projects,看到spring家族旗下的项目 Spring发展到今天已经形成了一种开发生态圈,Spring提供了若干个子项目,每个项目用于完成特定的功能。而我们在项目开发时,一般会偏向于选

    2024年02月12日
    浏览(41)
  • Spring Boot学习随笔-第一个SpringBoot项目快速启动(org.springframework.boot、@SpringBootApplication、application.yml)

    学习视频:【编程不良人】2021年SpringBoot最新最全教程 创建第一个Module 环境要求 jdk1.8+ maven3.2+ Spring Framework 5.x+ Tomcat 9.0+ IDEA 2021 自动保存刷新pom 在resources下添加application.yml文件后,即可启动springboot应用 由于tomcat内嵌在springboot里面了,所以我们在修改端口号等设置也在配置

    2024年02月05日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包