spring boot项目引入Spring Security

1、在pom文件中引入<!-- Spring Security -->

   <!-- 添加Spring Security依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

引入之后,记得刷新加载!!!

2、自定义配置类,将Spring Security应用于项目中

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;



@Configuration
@EnableWebSecurity  //开启SpringSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //权限应用于方法级别
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    String[] urls = {
            "/test/test01",
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers(urls).permitAll() // 放行的接口
                .anyRequest() .authenticated()//所有请求都需要认证
                .and()
                .formLogin()  //启用表单认证
                .and()
                .httpBasic();

    }
}

 该配置类中接口为/test/test01的接口会被放行;

3、在controlle的包中书写对应的访问方法

package com.example.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/test01")
    public String test01(){
        return "1111";
    }

    @GetMapping("/test02")
    public String test02(){
        return "2222";
    }

}

之启动该项目,项目启动时,记得不要清除控制台的日志;

 SpringSecurity的默认用户名是User,密码会通过控制台打印出来

4、访问接口

访问/test/test01时,不需要验证,直接进入

访问/test/test02时,需要验证,输入用户名,密码进入

输入用户名user,密码:ed451932-944f-4cfb-8bb2-06767c444564

登录成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值