文章目录

  • 指定依赖
  • 安全配置
  • 添加controller测试代码
  • 测试

源码地址:

https://github.com/pony-maggie/spring-security-learn

指定依赖

spring boot工程是需要引入spring-boot-starter-security即可

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

安全配置

我们需要自己实现一个类(类名无关)继承WebSecurityConfigurerAdapter ,然后重写里面的方法

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/anon1", "/anon2").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/user").permitAll().and().logout().permitAll();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("111111")).roles("USER");}
}

对于上面的配置说明如下:

@EnableWebSecurity是必须的,表示开启spring security功能。不加这个注解的话你的应用启动也没问题,但是在configure配置的规则不会生效。

configure这里的配置意思是/anon1,/anon2两个路径访问不受权限保护,可以任意访问。其它路径都要进行身份认证,认证的方式formlogin表单登录。然后接着又指定表单登录的时候用到的登录页面地址
是"/login"。defaultSuccessUrl指明了登录成功后跳转的页面("/user"),当然可以不用指定defaultSuccessUrl,这种情况下spring security会默认跳转到"/"页面。

下面会通过例子演示上面的规则是否生效。

configureGlobal不是必须的,但是它可以在内存中创建了一个用户,方便进行演示说明(真实的项目中账户信息是存入数据库的)。因为是入门教程,我们先不把问题复杂化,第一章我并不打算引入UserDetailsService的概念(后面章节会详细讲)。

该用户的名称为user,密码为password,用户角色为USER

在spring security 5.0之前你也可以这样写:

 spring security 5之后就不能用这种方式了,一定要指定密码的加密方法@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throwsException {auth.inMemoryAuthentication().withUser("user").password("111111").roles("USER");}

但是spring security 5.0之后一定要指明密码的加密方法(BCryptPasswordEncoder),所以需要写成下面这种方式:

@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").password(new BCryptPasswordEncoder().encode("111111")).roles("USER");}

Spring security 5.0中新增了多种加密方式,也改变了密码的格式。以下是官方文档原话:

The general format for a password is:
{id}encodedPassword
Such that id is an identifier used to look up which PasswordEncoder should be used and encodedPassword is the original encoded password for the selected PasswordEncoder. The id must be at the beginning of the password, start with { and end with }. If the id cannot be found, the id will be null. For example, the following might be a list of passwords encoded using different id. All of the original passwords are "password".
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
{noop}password
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0

另外需要注意的是,必须至少指定一个角色,否则会报错

java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection

添加controller测试代码

首先我们再controller里定义几个接口,方便我们一会再浏览器进行测试,添加几个网页,只显示基本的提示信息,能让你明白基本的跳转流程即可。

@Controller
public class TestController {@RequestMapping({"/anon1","/anon2"})public String anon() {return "anon";}@RequestMapping("/login")public String login() {return "login";}@RequestMapping("/")public String index() {return "index";}@RequestMapping("/user")public String user() {return "user";}}

测试

启动工程,进行如下测试:

  1. 访问首页,http://localhost:9090,需要授权,会自动跳入登录页:http://localhost:9090/login
  2. 访问,http://localhost:9090/anon1和http://localhost:9090/anon2,可以不用登录直接访问
  3. 访问用户页:http://localhost:9090/user,也需要授权,会自动跳入登录页:http://localhost:9090/login
  4. 从登录页输入用户名和密码(user/111111),进入用户主页

跟我学spring security系列文章第一章 实现一个基本的登入相关推荐

  1. spring security系列一:架构概述

    一直以来都想好好写一写spring security 系列文章,每每提笔又不知何处下笔,又赖于spring security体系强大又过于繁杂,且spring security 与auth2.0结合的 ...

  2. Spring Security系列教程03--创建SpringSecurity项目

    前言 在上一章节中,一一哥 已经带大家认识了Spring Security,对其基本概念已有所了解,但是作为一个合格的程序员,最关键的肯定还是得动起手来,所以从本篇文章开始,我就带大家搭建第一个Spr ...

  3. 循序渐进学spring security 第八篇,如何配置密码加密?是否支持多种加密方案?

    文章目录 回顾 密码明文会带来什么问题? 如何加密? PasswordEncoder 加密接口 如何配置? 加密的密码在登录的时候是怎么校验的? 默认的加密是什么? DaoAuthentication ...

  4. 实现账号在一端登入_跟我学spring security 基于数据库实现一个基本的登入登出...

    第一章我们基于内存中的用户信息实现了一个基本的登入功能,不过实际的项目中用户信息一般都是存在数据库中的.本章我们来实现一个比较接近真实项目的登入登出,同时引入UserDetailsService的概念 ...

  5. Spring Security系列之Spring Social实现微信社交登录(九)

    社交登录又称作社会化登录(Social Login),是指网站的用户可以使用腾讯QQ.人人网.开心网.新浪微博.搜狐微博.腾讯微博.淘宝.豆瓣.MSN.Google等社会化媒体账号登录该网站. 前言 ...

  6. ML:MLOps系列讲解之系列知识解读之完整总结系列内容(第一章~第九章)

    ML:MLOps系列讲解之系列知识解读之完整总结系列内容(第一章~第九章) 导读:您将了解如何使用机器学习,了解需要管理的各种变更场景,以及基于ml的软件开发的迭代性质.最后,我们提供了MLOps的定 ...

  7. 摄影知识系列讲座 - 第一章《光圈、快门篇》

    is2is 色廊 摄影交流园地 - 摄影知识系列讲座 - 第一章<光圈.快门篇> hotoboy版权所有,任何媒体转载须得到作者书面授权 摄影知识讲座 光圈.快门篇(一)     首先建议 ...

  8. 路飞学城python电子书_路飞学城-Python开发集训-第一章

    路飞学城-Python开发集训-第一章 1.本章学习心得.体会 我: 间接性勤奋. 我: 学习方法论:输入--输出---纠正 我: 对对对 走出舒适区, 换圈子, 转思路,投资自我加筹码. 我: 圈子 ...

  9. 第一章第一个c#程序上机_我从第一个#100DaysOfCode中学到的东西

    第一章第一个c#程序上机 On May 17th, I completed my first round of #100DaysOfCode. In case you haven't heard, # ...

最新文章

  1. 开放平台鉴权以及OAuth2.0介绍
  2. springboot 控制台输出错误信息_springboot日志详解
  3. Redis是如何写代码注释的?
  4. STM32开发 -- 4G模块开发详解(3)
  5. oracle12c的scott,Oracle12C创建scott账户
  6. [Idea Fragments]2013.08.08
  7. bzoj#3456. 城市规划
  8. 关于缓存使用中的一些看法
  9. 〖Python APP 自动化测试实战篇①〗 - 大话闲扯 APP 自动化
  10. 淘宝标品运营技巧,标品如何实现小单量爆搜索
  11. HTML有哪些浏览器支持,哪些浏览器支持 HTML5?
  12. echarts折线图鼠标悬浮竖线_Echarts折线图问题,鼠标悬停的地方不能正确展示数据怎么回事呢?...
  13. 接口测试 - 构造伪数据/测试数据(Faker)
  14. Kubernetes 的 CI/CD 管道概述
  15. Java中的JVM关闭钩子
  16. 京喜拼拼微信小程序-signStr参数加密
  17. 语雀—好用的文档编写、知识沉淀的工具
  18. springmvc(尚硅谷版)
  19. 大牛都会用的IDEA调试技巧!!!
  20. 照片尺寸怎么调整大小?三个方法,高效、快捷、安全!

热门文章

  1. 物联1131 1132博客链接
  2. AcWing 692. G巴士计数 差分+前缀和
  3. 大乐透号码 及数据库查询语句
  4. VHDL语言逻辑运算学习笔记
  5. Day 01嵌入式学习之Linux基础知识和命令操作
  6. 『tensorflow笔记』tf.argmax()和tf.equal()的使用
  7. 大O表示法和时间复杂度
  8. oracle 00600 kccpb,ora-00600 [kccpb_sanity_check_2] 错误处理
  9. elementui自定义进度条形状
  10. Python 运维自动化之服务器信息采集