摘要: 原创出处 https://www.cnkirito.moe/spring-security-2/ 「老徐」欢迎转载,保留摘要,谢谢!



上一篇文章《Spring Security(一)–Architecture Overview》,我们介绍了Spring Security的基础架构,这一节我们通过Spring官方给出的一个guides例子,来了解Spring Security是如何保护我们的应用的,之后会对进行一个解读。

2 Spring Security Guides

2.1 引入依赖

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

2.2 创建一个不受安全限制的web应用由于我们集成了springboot,所以不需要显示的引入Spring Security文档中描述core,config依赖,只需要引入spring-boot-starter-security即可。

这是一个首页,不受安全限制

src/main/resources/templates/home.html

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1> <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>

src/main/resources/templates/hello.html这个简单的页面上包含了一个链接,跳转到”/hello”。对应如下的页面

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
 @Configuration
public class MvcConfig extends WebMvcConfigurerAdapter { @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
} }

2.3 配置Spring Security接下来配置Spring MVC,使得我们能够访问到页面。

一个典型的安全配置如下所示:

 @Configuration
@EnableWebSecurity <1>
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { <1>
@Override
protected void configure(HttpSecurity http) throws Exception {
http <2>
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
} @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth <3>
.inMemoryAuthentication()
.withUser("admin").password("admin").roles("USER");
}
}

<2> configure(HttpSecurity)定义了哪些URL路径应该被拦截,如字面意思所描述:”/“, “/home”允许所有人访问,”/login”作为登录入口,也被允许访问,而剩下的”/hello”则需要登陆后才可以访问。<1> @EnableWebSecurity注解使得SpringMVC集成了Spring Security的web安全支持。另外,WebSecurityConfig配置类同时集成了WebSecurityConfigurerAdapter,重写了其中的特定方法,用于自定义Spring Security配置。整个Spring Security的工作量,其实都是集中在该配置类,不仅仅是这个guides,实际项目中也是如此。

<3> configureGlobal(AuthenticationManagerBuilder)在内存中配置一个用户,admin/admin分别是用户名和密码,这个用户拥有USER角色。

我们目前还没有登录页面,下面创建登录页面:

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

最后,我们为hello.html添加一些内容,用于展示用户信息。这个Thymeleaf模板提供了一个用于提交用户名和密码的表单,其中name=”username”,name=”password”是默认的表单值,并发送到“/ login”。 在默认配置中,Spring Security提供了一个拦截该请求并验证用户的过滤器。 如果验证失败,该页面将重定向到“/ login?error”,并显示相应的错误消息。 当用户选择注销,请求会被发送到“/ login?logout”。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>

2.4 添加启动类我们使用Spring Security之后,HttpServletRequest#getRemoteUser()可以用来获取用户名。 登出请求将被发送到“/ logout”。 成功注销后,会将用户重定向到“/ login?logout”。

@SpringBootApplication
public class Application { public static void main(String[] args) throws Throwable {
SpringApplication.run(Application.class, args);
} }

访问首页http://localhost:8080/:2.5 测试

home.html

点击here,尝试访问受限的页面:/hello,由于未登录,结果被强制跳转到登录也/login

login.html

输入正确的用户名和密码之后,跳转到之前想要访问的/hello:

hello.html

点击Sign out退出按钮,访问:/logout,回到登录页面:

logout.html

Spring Security 无法登陆,报错:There is no PasswordEncoder mapped for the id “null”

网上百度了一下发现这是因为Spring security 5.0中新增了多种加密方式,也改变了密码的格式。

要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密,spring security 官方推荐的是使用bcrypt加密方式。那么如何对密码加密呢,只需要在configure方法里面指定一下。

修改后是这样的:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//inMemoryAuthentication 从内存中获取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user1").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
}

在inMemoryAuthentication()后面多了".passwordEncoder(new BCryptPasswordEncoder())",这相当于登陆时用BCrypt加密方式对用户密码进行处理。以前的".password("123456")" 变成了 ".password(new BCryptPasswordEncoder().encode("123456"))" ,这相当于对内存中的密码进行Bcrypt编码加密。比对时一致,说明密码正确,允许登陆。

如果你现在用的也是从内存中取密码,那么按照上面这么修改后应该会成功登录没有问题的。

如果你用的是在数据库中存储用户名和密码,那么一般是要在用户注册时就使用BCrypt编码将用户密码加密处理后存储在数据库中。并且修改configure()方法,加入".passwordEncoder(new BCryptPasswordEncoder())",保证用户登录时使用bcrypt对密码进行处理再与数据库中的密码比对。如下:

//注入userDetailsService的实现类
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());

最新文章

  1. Dubbo_异常_Service启动时默认将方法注册到内网IP
  2. C#矩阵运算类库
  3. 用VBS实现公司自动打卡
  4. EF6+MVC5之Oracleo数据库的Code First方式实现
  5. linux部署的java应用,浏览器访问时,报域名解析错误
  6. HDFS+MapReduce+Hive+HBase十分钟快速入门
  7. 【jmeter】参数化User Defined Variables与User Parameters
  8. VS2012环境设置
  9. jquery easyui from 表单返回乱码!
  10. Ubuntu10.04下载并编译Android4.3源代码
  11. KP 佛学禅语
  12. Attributes(1):反射Attribute并输出
  13. Oculus Rift DK2 安装所需电脑配置
  14. Detours信息泄漏漏洞
  15. IP:网际协议
  16. centos7搭建SVN+Apache+IF.svnadmin实现web管理SVN
  17. 如何判断Linux 是32位还是64位
  18. MVC 框架
  19. kubernetes Auto Install Guide
  20. 【aardio】]SQL创建、读写 excel

热门文章

  1. Java实现 LeetCode 738 单调递增的数字(暴力)
  2. Java实现 LeetCode 665 非递减数列(暴力)
  3. Java实现 LeetCode 659 分割数组为连续子序列 (哈希)
  4. Java实现 蓝桥杯VIP 算法训练 完数
  5. StringBuilder的线程为什么不安全
  6. Java实现 蓝桥杯 算法提高 歌唱比赛
  7. java算法集训代码填空题练习1
  8. 从linux源码看socket的阻塞和非阻塞
  9. PAT A除以B
  10. css背景图片加载失败,页面部分图标无法显示