Spring Boot安全管理—Spring Security基本配置

这篇具有很好参考价值的文章主要介绍了Spring Boot安全管理—Spring Security基本配置。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Spring Security的基本配置

1. 基本用法

1.1 创建项目,添加依赖

创建一个Spring Boot Web 项目,然后添加spring-boot-starter-security依赖。

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

1.2 添加hello接口

在项目中添加一个简单的/hello接口,内容如下:

@RestController
public class HelloController {
   @GetMapping("/hello")
   public String hello(){
       return "Hello";
   }
}

1.3 启动项目测试

访问/hello接口会自动跳转到登录页面,这个页面有Spring Security提供的。
Spring Boot安全管理—Spring Security基本配置

默认的用户名是user,默认的登录密码在每次启动项目随机生成,查看项目日志:

Spring Boot安全管理—Spring Security基本配置

2. 配置用户名和密码

在application。properties中配置默认的用户名、密码以及用户角色。

spring.security.user.name=chen
spring.security.user.password=123456
spring.security.user.roles=admin

3. 基于内存的认证

开发者可以自定义类继承WebSecurityConfigurerAdapter,进而实现对Spring Security更多的自定义配置。例如基于内存的认证。

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("ADMIN","USER")
                .and()
                .withUser("chen").password("123456").roles("USER");
    }
}

代码解释:

  • 自定义MyWebSecurityConfig继承WebSecurityConfigurerAdapter,并重写configure(AuthenticationManagerBuilder auth)方法,在该方法中配直两个用户,一个用户名是adnin ,密码123456 ,具备两个角色 ADMIN 和 USER;另一个用户名是chen ,密码是123456 ,具备一个角色 USER。

4. HttpSecurity

虽然现在可以实现认证功能,但是受保护的资源都是默认的,而且不能根据实际情况进行角色管理。如果要实现这些功能,就需要重写WebSecurityConfigurerAdapter中的另一个方法,代码如下:

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("ADMIN","USER")
                .and()
                .withUser("chen").password("123456").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .access("hasAnyRole('ADMIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('admin') and hasRole('DBA')")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .permitAll()
                .and()
                .csrf()
                .disable();
    }
}

配置完成后,接下来在Controller中添加如下接口进行测试:

@RestController
public class HelloController {
    @GetMapping("/admin/hello")
    public String admin(){
        return "hello admin";
    }
    
    @GetMapping("/user/hello")
    public String user(){
        return "hello user";
    }
    
    @GetMapping("db/hello")
    public String dba(){
        return "hello dba";
    }
    
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

"admin/hello"接口root和admin用户具有访问权限,“/user/hello”接口admin和chen用户具有访问权限,“/db/hello”只有root用户具有访问权限。

5. 登录表单详细配置

在前后端分离的开发方式中,前后端的数据交互通过JSON进行,要实现这些功能,需要继续完成上文配置。

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("ADMIN","USER")
                .and()
                .withUser("chen").password("123456").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .access("hasAnyRole('ADMIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('admin') and hasRole('DBA')")
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/login_page")
                .loginProcessingUrl("/login")
                .usernameParameter("name")
                .passwordParameter("passwd")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        Object principal = authentication.getPrincipal();
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        response.setStatus(200);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("status",200);
                        map.put("msg",principal);
                        ObjectMapper om = new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter out = response.getWriter();
                        response.setStatus(401);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("status",401);
                        if(e instanceof LockedException){
                            map.put("msg","账户被锁定,登录失败");
                        }else if(e instanceof BadCredentialsException){
                            map.put("msg","账户或密码输入错误,登录失败");
                        }else if (e instanceof DisabledException){
                            map.put("msg","账户被禁用,登录失败");
                        }else if(e instanceof AccountExpiredException){
                            map.put("msg","账户过期,登录失败");
                        }else if(e instanceof CredentialsExpiredException){
                            map.put("msg","密码过期,登录失败");
                        }else {
                            map.put("msg","登录失败");
                        }
                       ObjectMapper om= new ObjectMapper();
                        out.write(om.writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and();
    }
}

6. 注销登录

如果想要注销登录,也只需提供简单的配置即可。文章来源地址https://www.toymoban.com/news/detail-473939.html

      .and()
                .logout()
                .logoutUrl("/logout")
                .clearAuthentication(true)
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication){
                       
                    }
                })
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.sendRedirect("/login_page");
                    }
                })
                .and();

到了这里,关于Spring Boot安全管理—Spring Security基本配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • Spring Boot 优雅集成 Spring Security 5.7(安全框架)与 JWT(双令牌机制)

    本章节将介绍 Spring Boot 集成 Spring Security 5.7(安全框架)。 🤖 Spring Boot 2.x 实践案例(代码仓库) Spring Security 是一个能够为基于 Spring 的企业应用系统提供声明式的安全访问控制解决方案的安全框架。 它提供了一组可以在 Spring 应用上下文中配置的 Bean,充分利用了 Spring

    2024年02月12日
    浏览(34)
  • 快速上手Spring Cloud 十一:微服务架构下的安全与权限管理

    快速上手Spring Cloud 一:Spring Cloud 简介 快速上手Spring Cloud 二:核心组件解析 快速上手Spring Cloud 三:API网关深入探索与实战应用 快速上手Spring Cloud 四:微服务治理与安全 快速上手Spring Cloud 五:Spring Cloud与持续集成/持续部署(CI/CD) 快速上手Spring Cloud 六:容器化与微服务化

    2024年04月22日
    浏览(32)
  • spring boot中常用的安全框架 Security框架 利用Security框架实现用户登录验证token和用户授权(接口权限控制)

    spring boot中常用的安全框架 Security 和 Shiro 框架 Security 两大核心功能 认证 和 授权 重量级 Shiro 轻量级框架 不限于web 开发 在不使用安全框架的时候 一般我们利用过滤器和 aop自己实现 权限验证 用户登录 Security 实现逻辑 输入用户名和密码 提交 把提交用户名和密码封装对象

    2024年02月06日
    浏览(39)
  • Spring Boot 3 + JWT + Security 联手打造安全帝国:一篇文章让你掌握未来!

    Spring Security 已经成为 java 后台权限校验的第一选择.今天就通过读代码的方式带大家深入了解一下Security,本文主要是基于开源项目spring-boot-3-jwt-security来讲解Spring Security + JWT(Json Web Token).实现用户鉴权,以及权限校验. 所有代码基于 jdk17+ 构建.现在让我们开始吧! Springboot 3.0 Spri

    2024年02月07日
    浏览(39)
  • 云原生可观察性的基本理念和方法论:可观察性(Observability)是指系统内部的运行过程可以被检测、分析、记录和展示出来,从而对系统行为、资源利用、健康状况、安全情况等进行监控和管理

    作者:禅与计算机程序设计艺术 可观察性(Observability)是指系统内部的运行过程可以被检测、分析、记录和展示出来,从而对系统行为、资源利用、健康状况、安全情况等进行监控和管理。可观察性是云原生时代的一个重大发展方向,也是机器学习、微服务、容器技术、D

    2024年02月13日
    浏览(48)
  • Spring Boot开发Spring Security

            这里我对springboot不做过多描述,因为我觉得学这个的肯定掌握了springboot这些基础 Spring Security为我们提供了登录页面,这里我是将 \\\"/\\\",路径设置为登陆页面的路径,方便测试, 也可以自定义登录页面,我会在后面说明         至于为什么不是yml,这完全不是这里

    2024年01月25日
    浏览(34)
  • Spring Boot 与 Spring Security

    Spring Security最初是由Ben Alex开发的,他是Acegi Security的创始人之一。Acegi Security是一个基于Spring框架的安全框架,它提供了一套完整的安全解决方案,包括认证、授权、攻击防护等功能,可以轻松地集成到Spring应用程序中,保护应用程序的安全性。 2008年,SpringSource收购了Aceg

    2024年02月08日
    浏览(31)
  • Mikrotik Ros 安全基本配置

    基本概述 Mikrotik路由器是一种基于Linux内核的网络操作系统,常用于构建企业级网络和个人网络。为了确保网络的安全性,对Mikrotik RouterOS进行适当的安全加固是至关重要的。本文将介绍一些Mikrotik RouterOS的基本安全配置,以帮助您提高网络的安全性。 Mikrotik系列路由器也成

    2024年02月04日
    浏览(26)
  • 安全生产管理平台——革新传统安全生产管理方式,重塑企业安全文化

    安全生产管理在现代企业中占据着至关重要的地位。传统的安全生产管理方式虽然在一定程度上能够保障企业的生产安全,但随着企业规模的不断扩大和生产环境的日益复杂,其局限性也愈发凸显。而安全生产管理平台的出现,正是为了解决这一问题。 平台功能与特点 安全

    2024年01月18日
    浏览(38)
  • 安全生产管理系统助力企业安全细化管理

    安全生产管理系统利用完整的安全生产管理体系,结合信息化、数字化和智能化等技术手段,将安全生产过程中的各个环节进行有效整合,使安全管理更加科学、规范和高效。 安全生产管理系统可以对企业安全生产进行全面、细致的管理。它能够实现对企业安全生产活动的全

    2024年02月06日
    浏览(39)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包