SpringSecurity学习日记 一

SpringSecurity学习日记 一

  • SpringSecurity认证
    • Maven依赖
    • 创建测试资源
      • 一、创建一个Controller 里面包含两个路径用以测试
      • 二、启动测试
    • 创建SpringSecurity配置类
      • 一、配置类继承WebSecurityConfigurerAdapter 并加上@Configuration注解
      • 二、再次启动测试
      • 三、密码加密
      • 四、再次启动测试 登录成功
    • 配置权限控制
      • 一、继续在配置类中添加
      • 二、启动测试
    • 以上就是一个简单的权限控制
    • 下面还有从数据库中读取用户配置权限

SpringSecurity认证

Maven依赖

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

创建测试资源

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

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

二、启动测试

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

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

创建SpringSecurity配置类

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

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

或者在yml中加入

spring:security:user:name: usernamepassword: 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

三、密码加密

在启动类加上

	@BeanPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}

修改配置类 为密码加密

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

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

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

配置权限控制

一、继续在配置类中添加

    @Overrideprotected 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 无法访问
在这里插入图片描述

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

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