SpringSecurity学习日记 一

SpringSecurity认证

Maven依赖

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

创建测试资源

一、创建一个Controller 里面包含两个路径用以测试

    @RequestMapping("/admin")
    @ResponseBody
    public String admin(){
        return "admin用户可见";
    }

    @RequestMapping("/user")
    @ResponseBody
    public String user(){
        return "user用户可见";
    }

二、启动测试

访问localhost:8080 发现程序自动跳转到 /login

在这里插入图片描述
这是SpringSecurity自带登录页面,现在我们登录不了,因为没有用户名密码。

创建SpringSecurity配置类

一、配置类继承WebSecurityConfigurerAdapter 并加上@Configuration注解

@Configuration
public class WebSecutityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   		auth.inMemoryAuthentication() //在内存中创建一个用户
                .withUser("username")//用户名
                .password("password")//密码
                .roles("admin");//角色
    }
}

或者在yml中加入

spring:
  security:
    user:
      name: username
      password: password

二、再次启动测试


用户名密码为我们创建的 username password。
登录发现报bad credentials 。
同时控制台打印出

2021-08-26 09:32:17.428  WARN 7372 --- [nio-8080-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt

三、密码加密

在启动类加上

	@Bean
	PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

修改配置类 为密码加密

@Configuration
public class WebSecutityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication() //在内存中创建一个用户
                .withUser("username")//用户名
                .password(passwordEncoder.encode("password"))//密码
                .roles("admin");//角色
    }
}

四、再次启动测试 登录成功

正常访问两个页面,因为没有添加权限控制

配置权限控制

一、继续在配置类中添加

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin").hasRole("admin") //必须拥有admin角色才能访问/home
                .antMatchers("/user").hasRole("user") //必须拥有user角色才能访问/hello
                .anyRequest().permitAll() //其他请求放通
                .and() 	
                .formLogin()	//允许表单登录
                .defaultSuccessUrl("/admin"); //登录成功页面

    }

二、启动测试

登录发现 /admin 正常 /user 无法访问
在这里插入图片描述

以上就是一个简单的权限控制

下面还有从数据库中读取用户配置权限

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值