Spring-Security框架学习总结
前提:在做演示之前,我们先创建项目,并将项目导入IDE
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCM581dvRWYoNHLwEzX5xCMx8FesU2cfdGLwATMfRHLGZkRGZkRfJ3bs92YskmNhVTYykVNQJVMRhXVEF1X0hXZ0xiNx8VZ6l2cssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLmhjMjhjMjFTN5YGMwMDMmlzM2M2YiFDM4gTY2IWZiZzLcVjMvwFMxgTMwIzLcd2bsJ2LcNXZnFWbp9CXt92Yu8GdjFTNuITavw1LcpDc0RHaiojIsJye.png)
测试项目是否运行成功,成功后进行正式开始学习
一.Case1:只要能登录即可
目标:我们在访问项目是访问index可以直接进入,不需要拦截,访问其他路径是需要进行登录验证,并且允许登录用户注销和使用表单进行登录,不拦截前台js,css,image等文件,我们在内存中设置了一个admin用户,可以进行登录
直接上代码(代码中会有注释):
SecuDemoApplication:
package com.dhtt.security.SecuDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableAutoConfiguration
public class SecuDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SecuDemoApplication.class, args);
}
@RequestMapping("/index")
public String hello() {
return "hello Spring boot....";
}
@RequestMapping("/home")
public String home() {
return "this my home....";
}
}
SpringSecruityConfig:
package com.dhtt.security.SecuDemo;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecruityConfig extends WebSecurityConfigurerAdapter{
/**
* HTTP请求拦截处理
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index").permitAll() //主路径直接请求
.anyRequest().authenticated() //请他请求都要验证
.and()
.logout().permitAll() //允许注销
.and()
.formLogin(); //允许表单登录
http.csrf().disable(); //关闭csrf的认证
}
/**
* 处理前端文件,拦截忽略
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**","/css/**","/image/**");
}
/**
* 设置内存中的用户admin
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
}
}
然后我们启动项目,在前台访问路径
(1)访问http://localhost:8080/index成功
(2)访问http://localhost:8080/home:
我们发现前台会为我们跳转到登录界面,接下来我们进行登录验证,我们发现登录界面没有跳转,证明登录失败,此时我们观察后台
发现后台报错
(3)报错问题解决:原因是spring boot的版本和Spring Security的版本问题,我们需要提供一个PasswordEncorder实例
MyPasswordEncoder:
package com.dhtt.security.SecuDemo;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder{
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(rawPassword);
}
}
SpringSecruityConfig中修改部分:
/**
* 设置内存中的用户admin
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("admin").password("123456").roles("ADMIN");
}
/**
* 设置内存中的用户admin
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("admin").password("haha1996").roles("ADMIN");
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("zhangsan").password("123456").roles("ADMIN");
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("username1").password("password").roles("USER");
}
package com.dhtt.security.SecuDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecuDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SecuDemoApplication.class, args);
}
@RequestMapping("/index")
public String hello() {
return "hello Spring boot....";
}
@RequestMapping("/home")
public String home() {
return "this my home....";
}
@RequestMapping("/roleAuth")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String role() {
return "HELLO SPRING SECURITY....";
}
}
待续。。。