本文介绍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. pipenv安装库使用国内镜像

    pipenv install django超级慢,卡住不动,最后不得不CTRL+C中止 这时有必要改成国内源了,打开Pipfile文件,发现内容是: [[source]] verify_ssl = t ...

  2. 009——VUE中watch监听属性变化实现类百度搜索栏功能

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. laravel利用composer安装

    composer create-project laravel/laravel --prefer-dist blog prefer:提升,提拔 dist:距离 blog 创建的项目文件夹名称 lara ...

  4. ComBox绑定枚举

    (转自:http://blog.csdn.net/chao88552828/article/details/9903159) /// <summary> /// 参数枚举 /// < ...

  5. 内存保护机制及绕过方案——利用未启用SafeSEH模块绕过SafeSEH

    前言:之前关于safeSEH保护机制的原理等信息,可在之前的博文(内存保护机制及绕过方案中查看). 利用未启用SafeSEH模块绕过SafeSEH ⑴.  原理分析: 一个不是仅包含中间语言(1L)且 ...

  6. Struts03---参数传递

    package cn.bdqn.bean; /** * *用户的实体类 */ public class User { private String name; private String passw ...

  7. Lua学习---编译生成lua和luac

    众所周知,Lua是一种强大的脚本语言,并且这种语言是用C语言实现的.为什么要学习这门语言?因为它可以增强我看C语言代码的功底. 我下的Lua版本是Lua5.3,关于Lua5.3的简介如下: http: ...

  8. 从微软官网下载VS离线安装包的方法

    这里描述是包括所有版本,截图以下载VS2017社区版为例: ①登入VS官网下载页面,选择需要的版本点击下载,下载页点此进入. ②下载完成后,打开下载文件所在文件夹,Windows 8.1及以上版本用户 ...

  9. 重读tcp-ip详解三卷:1

    应用层 Http.Telnet.FTP和e-mail等 负责把数据传输到传输层或接收从传输层返回的数据传输层 TCP和UDP 主要为两台主机上的应用程序提供端到端的通信,TCP为两台主机提供高可靠性的 ...

  10. php服务端setcookie()原理

    1.什么是 Cookie? cookie 常用于识别用户.cookie 是服务器留在用户计算机中的小文件.每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie.通过 PHP,您能够创建并取 ...