前言
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";
}
}
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
输入用户名:terry,密码:terry123,即可访问接口。
后端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'
}
});