Spring Security的简单使用

推荐 Java 常见面试题

简介

  • SSM 整合 Security 是比较麻烦的,虽然Security的功能比 Shiro 强大,相反却没有Shiro的使用量多
  • SpringBoot出现后简化了Spring系列的配置文件,因此SpringSecurity的使用逐渐增加

一、创建项目

查看代码

在 SpringBoot 中直接引入 Spring Security 依赖即可

创建项目的启动类

创建 SecurityController 类

  • 启动后访问 localhost:8080/hello
  • 会自动跳到 localhost:8080/login
  • 需要登录后才能访问 /hello

二、用户名配置

查看代码

  • 默认情况下用户名是 user ,而密码会在项目启动时 控制台 打印出一串随机 字符串,这就是密码.每次启动项目,密码都不一样

  • 对登录的用户名/密码进行配置,有三种不同的方式
  1. application 配置文件中声明
  2. java 代码配置在内存里
  3. 通过获取 数据库

第一种方式 application.yml 文件中

第二种方式 创建一个SecurityConfig配置类,继承 WebSecurityConfigurerAdapter

第三种方法没有进行演示,就是在数据库中取出usernamepassword配置到内存中

三、忽略拦截

查看代码

在配置类中重写 configure(WebSecurity web) 方法,然后直接访问即可

pom.xml文件

返回阅读

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--Web项目 需引入web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
启动类文件
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* @author https://www.cnblogs.com/beixuan/
*/
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
SecurityController 文件
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; /**
* @author https://www.cnblogs.com/beixuan/
*/
@RestController
public class SecurityController { /**
* 不用登录就可访问
* @return
*/
@RequestMapping("/hi")
public String sayHi(){
return "Hi bro!";
} @RequestMapping("/hello")
public String sayHello(){
return "Hello bro!";
}
}
application.yml 配置文件

返回阅读

spring:
security:
user:
name: beixuan
password: beixuan
SecurityConfig Java配置文件

此方法配置用户与配置 yml 文件效果一致

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.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* @author https://www.cnblogs.com/beixuan/
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
//Spring Security5之后 官方需要密码强制加密,如不想加密可创建一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,但不安全
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String password = bCryptPasswordEncoder.encode("beixuan");
//添加一个用户[beixuan] 角色为[admin] 密码是[beixuan加密后的密钥]
auth.inMemoryAuthentication()
.withUser("beixuan")
.roles("admin")
.password(password);
} @Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
  • 具体的登录配置 下面代码借鉴于 江南一点雨 随笔的代码,有兴趣可以看看
  • VerifyCodeFilter 一次性验证码,可以查看资料了解其使用方法,这里不再叙述
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
VerifyCodeFilter verifyCodeFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);
http
.authorizeRequests()//开启登录配置
.antMatchers("/hello").hasRole("admin")//表示访问 /hello 这个接口,需要具备 admin 这个角色
.anyRequest().authenticated()//表示剩余的其他接口,登录之后就能访问
.and()
.formLogin()
//定义登录页面,未登录时,访问一个需要登录之后才能访问的接口,会自动跳转到该页面
.loginPage("/login_p")
//登录处理接口
.loginProcessingUrl("/doLogin")
//定义登录时,用户名的 key,默认为 username
.usernameParameter("uname")
//定义登录时,用户密码的 key,默认为 password
.passwordParameter("passwd")
//登录成功的处理器
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("success");
out.flush();
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("fail");
out.flush();
}
})
.permitAll()//和表单登录相关的接口统统都直接通过
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("logout success");
out.flush();
}
})
.permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
忽略拦截分两步

返回阅读

增加访问路径/hi

/**
* 不用登录就可访问
* @return
*/
@RequestMapping("/hi")
public String sayHi(){
return "Hi bro!";
}

增加配置代码

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/hi");
}

即可不用登录访问/hi路径

END

本文就先说到这里,有问题欢迎留言讨论

Spring Security入门教程 通俗易懂 超详细 【内含案例】的更多相关文章

  1. SVN入门图解教程(超详细)

    SVN入门图解教程(超详细) 一.总结 一句话总结: 二.SVN入门教程 1. 什么是SVN SVN全名Subversion,即版本控制系统.SVN与CVS一样,是一个跨平台的软件,支持大多数常见的操 ...

  2. Spring Cloud 入门教程(十):和RabbitMQ的整合 -- 消息总线Spring Cloud Netflix Bus

    在本教程第三讲Spring Cloud 入门教程(三): 配置自动刷新中,通过POST方式向客户端发送/refresh请求, 可以让客户端获取到配置的最新变化.但试想一下, 在分布式系统中,如果存在很 ...

  3. Spring Cloud 入门教程(四): 分布式环境下自动发现配置服务

    前一章, 我们的Hello world应用服务,通过配置服务器Config Server获取到了我们配置的hello信息“hello world”. 但自己的配置文件中必须配置config serve ...

  4. Spring Cloud入门教程(二):客户端负载均衡(Ribbon)

    对于大型应用系统负载均衡(LB:Load Balancing)是首要被解决一个问题.在微服务之前LB方案主要是集中式负载均衡方案,在服务消费者和服务提供者之间又一个独立的LB,LB通常是专门的硬件,如 ...

  5. Spring MVC 入门教程示例 (一)

    今天和大家分享下  Spring MVC  入门教程 首先还是从 HelloWorld  web 工程开始 -------------------------- 1.首先创建一个Maven Web工程 ...

  6. Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序

    一.前言 什么是Spring Boot?Spring Boot就是一个让你使用Spring构建应用时减少配置的一个框架.约定优于配置,一定程度上提高了开发效率.https://zhuanlan.zhi ...

  7. Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版

    一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...

  8. Spring Boot 入门教程

    Spring Boot 入门教程,包含且不仅限于使用Spring Boot构建API.使用Thymeleaf模板引擎以及Freemarker模板引擎渲染视图.使用MyBatis操作数据库等等.本教程示 ...

  9. Spring Cloud 入门教程 - 搭建配置中心服务

    简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...

  10. Spring Cloud 入门教程(七): 熔断机制 -- 断路器

    对断路器模式不太清楚的话,可以参看另一篇博文:断路器(Curcuit Breaker)模式,下面直接介绍Spring Cloud的断路器如何使用. SpringCloud Netflix实现了断路器库 ...

随机推荐

  1. CentOS上安装telnet

    客户端 yum -y intall telnet 服务端 yum -y install xinetd #telnet服务依赖于xinetd yum -y install telnet-server # ...

  2. 2019 南昌区域赛 CEGLM 题解 & lagrange 插值

    B. A Funny Bipartite Graph 状压 dp ,利用了原题中选完左边点集,那么右边在 左边编号最大的那个数 之前的所有点都要选的性质,可以优化到 \(O(n \cdot 2^n)\ ...

  3. ​Chrome插件:Postman Interceptor 调试的终极利器

    今天给大家介绍一款非常实用的工具--Postman Interceptor. 这个工具可以捕捉任何网站的请求,并将其发送到Postman客户端. 对于经常和API打交道的程序员来说,Postman I ...

  4. 【基础推导】MPC控制器及其车辆模型详细推导 (附代码链接及详细推导说明)

    0. 参考与前言 Python 代码:github AtsushiSakai/PythonRobotics C++ 代码:github jchengai/gpir/mpc_controller 相关参 ...

  5. Java中final用法与详解

    final作为Java中经常用到的关键字,了解final的使用方法是非常有必要的. 这里从final关键字在数据域.方法和类中三个方面分析final关键字的主要用法. final应用于基本数据类型 1 ...

  6. HBase 在统一内容平台业务的优化实践

    作者:来自 vivo 互联网服务器团队-Leng Jianyu.Huang Haitao HBase是一款开源高可靠性.扩展性.高性能和灵活性的分布式非关系型数据库,本文围绕数据库选型以及使用HBas ...

  7. Pytorch功能库留存

    初始化 首先,介绍我们导入的包和基础的网络结构 import torch import torch.nn as nn #可替代网络结构部分 ''' 神经网络类的定义 1. 输入卷积: in_chann ...

  8. 零代码教你安装部署Stable Diffusion 3,一键生成高质量图像

    本文分享自华为云社区<重磅![支持中文]stable-diffusion-3安装部署教程-SD3 来了>,作者:码上开花_Lancer. 正如承诺的那样,Stability AI在6月12 ...

  9. 拥抱未来:GPT-4将如何改变我们的世界

    随着人工智能技术的迅猛发展,我们正迎来一个全新的智能时代.在这个时代的前沿,GPT-4作为开拓者和领航者,正在重新定义人机交互.创意创新和个性化服务的标准.无论是在商业领域.教育场景还是科研领域,GP ...

  10. 创建数据库时排序规则utf8_general_ci与utf8_bin的区别

    在MySQL数据库中,字符集(如utf8)定义了字符如何存储,而排序规则(Collation)则定义了字符如何比较.排序和区分大小写.utf8_general_ci和utf8_bin是两种常用的UTF ...