本文介绍Basic Auth在spring中的应用

目录结构

依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

入口DemoApplication

package com.springlearn.learn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

验证Authenication

// 主要是验证不成功返回401
package com.springlearn.learn.auth; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component; @Component
public class Authenication extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
} @Override
public void afterPropertiesSet() throws Exception {\
setRealmName("yejiawei");
super.afterPropertiesSet();
}
}

配置WebSecurityConfig

package com.springlearn.learn.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer; @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{ @Autowired
private AuthenticationEntryPoint authEntryPoint; @Autowired
DataSource dataSource; @Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
// 所有的请求都要验证
http.authorizeRequests().anyRequest().authenticated(); // 使用authenticationEntryPoint验证 user/password
http.httpBasic().authenticationEntryPoint(authEntryPoint);
} @Bean
public BCryptPasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
} @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
String password = "234";
String encrytedPassword = this.passwordEncoder().encode(password);
System.out.println("Encoded password = " + encrytedPassword); // 这里使用写死的验证,你可以在这里访问数据库
InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> mngConfig = auth.inMemoryAuthentication(); UserDetails u1 = User.withUsername("yejiawei").password(encrytedPassword).roles("ADMIN").build();
UserDetails u2 = User.withUsername("donglei").password(encrytedPassword).roles("USER").build(); mngConfig.withUser(u1);
mngConfig.withUser(u2);
} @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
}

控制器TestController

package com.springlearn.learn.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
public class TestController { @ResponseBody
@RequestMapping(value = "/AuthTest", method = RequestMethod.GET)
public String AuthTest(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth.getName());
return "OK";
}
}

前端访问

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.get('http://localhost:8888/AuthTest', {
auth: {
username: 'yejiawei',
password: '234'
}
}).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.log(error);
}).then(function () {
});
</script>
</head>
<body>
</body>
</html>

springboot成神之——Basic Auth应用的更多相关文章

  1. springboot成神之——basic auth和JWT验证结合

    本文介绍basic auth和JWT验证结合 目录结构 依赖 config配置文件WebSecurityConfig filter过滤器JWTLoginFilter filter过滤器JWTAuthe ...

  2. springboot成神之——ioc容器(依赖注入)

    springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...

  3. springboot成神之——application.properties所有可用属性

    application.properties所有可用属性 # =================================================================== # ...

  4. springboot成神之——springboot入门使用

    springboot创建webservice访问mysql(使用maven) 安装 起步 spring常用命令 spring常见注释 springboot入门级使用 配置你的pom.xml文件 配置文 ...

  5. springboot成神之——mybatis和mybatis-generator

    项目结构 依赖 generator配置文件 properties配置 生成文件 使用Example 本文讲解如何在spring-boot中使用mybatis和mybatis-generator自动生成 ...

  6. springboot成神之——swagger文档自动生成工具

    本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...

  7. springboot成神之——log4j2的使用

    本文介绍如何在spring-boot中使用log4j2 说明 依赖 日志记录语句 log4j2配置文件 本文介绍如何在spring-boot中使用log4j2 说明 log4j2本身使用是非常简单的, ...

  8. springboot成神之——mybatis在spring-boot中使用的几种方式

    本文介绍mybatis在spring-boot中使用的几种方式 项目结构 依赖 WebConfig DemoApplication 方式一--@Select User DemoApplication ...

  9. springboot成神之——发送邮件

    本文介绍如何用spring发送邮件 目录结构 依赖 MailConfig TestController 测试 本文介绍如何用spring发送邮件 目录结构 依赖 <dependency> ...

随机推荐

  1. 7z压缩gopath的src的批处理

    7zGoPath.bat @echo off pushd "%~dp0" :config for /f "delims=" %%t in ('powershel ...

  2. 【sparkStreaming】kafka作为数据源的生产和消费

    1.建立生产者发送数据 (1)配置zookeeper属性信息props (2)通过 new KafkaProducer[KeyType,ValueType](props) 建立producer (3) ...

  3. LeetCode OJ:Recover Binary Search Tree(恢复二叉搜索树)

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  4. L138 Cryptocurrency Exchanges at Risk of Manipulation

    Several cryptocurrency exchanges are plagued by poor market surveillance, pervasive conflicts of int ...

  5. 【机器学习基石笔记】七、vc Dimension

    vc demension定义: breakPoint - 1 N > vc dimension, 任意的N个,就不能任意划分 N <= vc dimension,存在N个,可以任意划分 只 ...

  6. Mysql中文汉字转拼音的实现(每个汉字转换全拼)

    -- 创建汉字拼音对照临时表 CREATE TABLE IF NOT EXISTS `t_base_pinyin` ( `pin_yin_` varchar(255) CHARACTER SET gb ...

  7. MySQL 进入 导入

    命令行进入时 不能用 ‘;’ 结尾

  8. PHP 去掉文文文件中的回车与空格

    文本文件fff.txt中去除回车与空格: $aa = file_get_contents('./fff.txt'); $bb = str_replace(array("\r\n", ...

  9. 深入了解zookeeper(三)

    一.ZooKeeper 的实现 1.1 ZooKeeper处理单点故障 我们知道可以通过ZooKeeper对分布式系统进行Master选举,来解决分布式系统的单点故障,如图所示. 那么我们继续分析一下 ...

  10. LG3648 [APIO2014]序列分割

    题意 你正在玩一个关于长度为 \(n\) 的非负整数序列的游戏.这个游戏中你需要把序列分成 \(k+1\) 个非空的块.为了得到 \(k+1\) 块,你需要重复下面的操作 \(k\) 次: 选择一个有 ...