本文介绍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. mysql的bin或者sbin目录可执行文件

    一. mysql服务和myql服务启动程序 1. mysqld mysqld就是mysql server,负责管理对mysql数据的访问. 当mysql server启动后,它会监听来自客户端的网络连 ...

  2. IOS-导航路线

    1.可以将需要导航的位置丢给系统自带的APP进行导航 2.发送网络请求到公司服务器获取导航数据, 然后自己手动绘制导航 3.利用三方SDK实现导航(百度) >当点击开始导航时获取用户输入的起点和 ...

  3. QT Designer 的汉化

    Designer是很好用的设计器,通过 pip 安装PyQt5之后,一般都是英文的 所以给有需要的人带来汉化的包(这个是通过替换  translations 文件夹来实现的) translations ...

  4. Prism开发人员指南5-WPF开发 文档翻译(纯汉语版)

    2014四月       Prism以示例和文档的形式帮助你更简单的设计丰富灵活易维护的WPF程序.其中使用的设计模式体现了一些重要的设计原则,例如分离关注点和松耦合,Prism帮助你利用松耦合组件设 ...

  5. EL标签

    1.EL的作用 jsp的核心语法: jsp表达式 <%=%>和 jsp脚本<%  %>. 开发jsp的原则: 尽量在jsp页面中少写甚至不写java代码. 使用EL表达式替换掉 ...

  6. dubbo-monitor安装、 监控中心 配置过程

    简单介绍下monitor: Simple Monitor挂掉不会影响到Consumer和Provider之间的调用,所以用于生产环境不会有风险. 配置好了之后可以结合admin管理后台使用,可以清晰的 ...

  7. react-redux: async promise

    1.the simple sample action: 事实上,只是返回个一个至少包含type的对象{ },用于reducer接收. import {RECEIVE_DATA} from " ...

  8. eclipse 不能启动虚拟机

    在eclipse文件下有个eclipse.ini文件打开它.现在如果没有-vm 这个参数那么就在最后新起一行写上 -vm+空格+参数 参数是你安装的jdk目录比如我的 -vm d:/java/jdk1 ...

  9. angualr4 环境搭建

    不得不说现在很流行前端MVC框架,angularjs算是一种.以前也用过angularjs感觉还不错,刷新了我对前端的认知.特别是因为我本身是个java开发.但是感觉还是有很多缺点的,直到angula ...

  10. 高级C/C++编译技术之读书笔记(一)之编译/链接

    最近有幸阅读了<高级C/C++编译技术>深受启发,该书深入浅出地讲解了构建过程(编译.链接)中的各种细节,从多个角度展示了程序与库文件或代码的集成方法,提出了面向代码复用和系统集成的软件架 ...