栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot实战:Security入门体验(附git源码)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot实战:Security入门体验(附git源码)

Security系列教程
  • ①Security入门体验
  • ②Security自定义账号密码验证+thymeleaf登录案例(附带网页案例
  • ③Security+验证码登录案例(附带网页案例)
  • ④Security+jwt 实现无状态认证,前后端分离(附带网页案例))
  • ⑤Security+jwt 短信认证登录,前后端分离(附带网页案例)
  • ⑥Security+oauth2 授权服务器(附带网页案例)

文章目录
  • Security系列教程
  • 简介
    • 1. 环境
    • 2. 开启或关闭Spring Security安全认证
    • 3. 配置表单认证登录
    • 4. 效果演示
    • 5. 源码分享


简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。

  • 本系列文章以实战讲解为主,帮助开发者快速入门并应用到实际开发中。
1. 环境
  • springboot 版本为
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.3
        
    
  • 引入security依赖
     
            org.springframework.boot
            spring-boot-starter-security
        
  • yml 配置端口
server:
  port: 9999
2. 开启或关闭Spring Security安全认证
  • 当我们引入了spring-boot-starter-security依赖的时候,项目就会默认开启安全认证。
  • 若想关闭认证,把security.basic.enabled设为false即可。
security:
  basic:
    # 默认开启,无需配置,关闭设为false即可
    enabled: true
3. 配置表单认证登录
  • 开启Spring Security的认证功能
  • WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 表单方式
        http.formLogin()
                .and()
                // 授权配置
                .authorizeRequests()
                // 所有请求
                .anyRequest()
                // 都需要认证
                .authenticated();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                // 用户名
                .withUser("admin")
                // 密码
                .password(passwordEncoder().encode("123456"))
                // 角色
                .roles("ADMIN");
    }

    
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用BCrypt加密密码
        return new BCryptPasswordEncoder();
    }
}
  • @EnableWebSecurity 开启Security
  • @EnableGlobalMethodSecurity(prePostEnabled = true) 开启Security的注解功能
4. 效果演示
  • 编写测试接口
@RestController
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "请求成功";
    }
    
    @GetMapping("/get")
    public String get() {
        return "神秘代码9527";
    }
}
  • 启动项目
  • 浏览器输入localhost:9999/
  • 账号/密码为我们上一步配置的 admin/123456
  • 登录成功
5. 源码分享

本系列项目已收录
Springboot、SpringCloud全家桶教程+源码,各种常用框架使用案例都有哦,具备完善的文档,致力于让开发者快速搭建基础环境并让应用跑起来,并提供丰富的使用示例供使用者参考,快来看看吧。

  • 项目源码github地址
  • 项目源码国内gitee地址
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号