【SpringSecurity教程】认证 1.Basic认证

前言

Basic 认证是在请求接口之前要输入账号密码,是简单的Http验证模式。

本章主要描述:SpringBoot如何整合Basic认证、后端Okhttp和前端Vue Axios如何请求Basic认证的接口。

SpringBoot整合Basic认证

pom.xml

    <dependencies>
        <!-- spring boot security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- spring boot web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- spring boot 单元测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App{
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

控制层

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

/**
 * test 控制层
 * @author terry
 * @version 1.0
 * @date 2022/6/10 11:26
 */
@RestController
public class TestCtrl {

    @RequestMapping("/test")
    public String test(){
        return "success";
    }
}

Basic基本验证配置类。

import org.springframework.context.annotation.Bean;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

/**
 * Basic 基本验证
 * @author terry
 * @date 2022/6/10
 */
@Configuration
@EnableWebSecurity
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 设置拦截的资源
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
               // 代表拦截所有请求,另外一种方式:(antMatchers("/**"))
               .anyRequest()
               .authenticated()
               .and()
               .httpBasic();

    }

    /**
     * 设置授权账户
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("terry").password("terry123").authorities("/");
    }

    /**
     * Basic 验证因为没有加密密码,在Spring security 5 之后需要设置密码解析器,
     * 如果不设置会报错,一般情况下会用Md5.本文采用的无密码验证
     * @return
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

测试

浏览器访问:http://localhost:8080/test

image-20220610143701592

输入用户名:terry,密码:terry123,即可访问接口。

image-20220610144015863

后端Okhttp请求Basic认证的接口

以Okhttp为例

默认情况下请求会报错401无权限,如下:

{"timestamp":"2022-06-10T06:55:01.619+00:00","status":401,"error":"Unauthorized","message":"","path":"/test"}

OkHttpTest整合Basic如下:

/**
 * Okhttp 请求 测试
 * @author terry
 * @version 1.0
 * @date 2022/6/10 14:51
 */
public class OkHttpTest {

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new BasicAuthInterceptor("terry", "terry123"))
                .build();
        final Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/test")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }

    static class BasicAuthInterceptor implements Interceptor {
        private String credentials;
        public BasicAuthInterceptor(String user, String password) {
            this.credentials = Credentials.basic(user, password);
        }
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request authenticatedRequest = request.newBuilder()
                    .header("Authorization", credentials).build();
            return chain.proceed(authenticatedRequest);
        }
    }
}

打印如下:

success

前端Vue Axios请求Basic认证的接口

import axios from 'axios';

const service = axios.create({
	auth: {
		username: 'terry',
		password: 'terry123'
	}
});
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

terrybg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值