1、访问http://start.spring.io/,实现快速搭建项目
图中圈出来的地方你可以根据自己的需要进行修改,也可以都默认;然后点击
zip包下载完成后,解压并用idea打开,就是一个已经建好的项目了
启动项目,去访问 localhost:8080,会出现如下结果,就说明spring security生效了
2、创建SpringSecurityConfig类
package com.spring_security;
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 SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
@RequestMapping("/")
public String home(){
return "hello spring security";
}
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
}
package com.spring_security;
import org.springframework.context.annotation.Configuration;
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 SpringSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 放过静态文件
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**","/css/**","/image/**");
}
/**
* http请求的拦截【特别要注意的一个方法,这个方法决定了哪些请求会被拦截】
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll() //默认路径可以访问
.anyRequest().authenticated() //其他请求要经过验证
.and()
.logout().permitAll() //注销可以访问
.and()
.formLogin(); //允许表单登陆
http.csrf().disable(); //关闭csrf验证
}
}
启动项目,访问localhost:8080可以输出结果,但访问localhost:8080/hello会跳转登陆页面