Spring Security环境快速搭建与验证

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会跳转登陆页面




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值