Spring Security 学习笔记(一)

一、起步

在SpringBoot工程中pom.xml 添加依赖(最好在idea创建SpringBoot工程的时候就把这些打勾就好了)
我这里用的版本是 5.1.6.RELEASE(注意!!!)

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

当然还有SpringBoot的一些依赖

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

二、例子

把上面的依赖引入的时候security基础部分就完成了,然后我们通过一个例子来看一下效果。

  1. 创建一个SecurityConfig类,要继承 WebSecurityConfigurerAdapter 类进行配置
    注意:password这里不能直接写密码,要把密码通过new BCryptPasswordEncoder().encode()加密
/**
 * 1.@EnableWebSecurity是Spring Security用于启用Web安全的注解
 *
 * @author CH
 * @date 2021-08-05 10:54
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root")
                .password(new BCryptPasswordEncoder().encode("root"))
                .authorities("ROLE_USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}
  1. 创建一个控制类IndexController
/**
 * @author CH
 * @date 2021-08-05 10:43
 */
@RestController
public class IndexController {

    @RequestMapping(value = "/")
    public String test(){
        return LocalDateTime.now().toString();
    }
}

然后输入地址访问则会转到默认登录页面。

在这里插入图片描述
待完善。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值