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

前言

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

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

SpringBoot整合Basic认证

pom.xml

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        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

【SpringSecurity教程】认证 1.Basic认证_第1张图片

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

【SpringSecurity教程】认证 1.Basic认证_第2张图片

后端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'
	}
});

你可能感兴趣的:(SpringBoot,spring,boot,java,前端)