springsecurity登陆失败_Spring Security

4自定义登录失败处理器(续上一篇文章)

4.1源码分析

failureForwardUrl()内部调用的是failureHandler()方法

v2-5770f9c30f905cf5a810e16bcdd2f709_b.jpg

ForwardAuthenticationFailureHandler中也是一个请求转发,并在

request作用域中设置SPRING_SECURITY_LAST_EXCEPTION的key,内

容为异常对象。

v2-8b3e16deec5c59fa760c68daddabe7a4_b.jpg

4.2代码实现

4.2.1新建控制器

新建com.bjsxt.handler.MyForwardAuthenticationFailureHandler实

现AuthenticationFailureHandler。在方法中添加重定向语句

package com.bjsxt.springsecuritydemo.handler;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {private String url;public MyAuthenticationFailureHandler(String url) {this.url = url;
}
@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendRedirect(url);
}
}

4.2.2修改配置类

修改配置类中表单登录部分。设置失败时交给失败处理器进行操

作。failureForwardUrl和failureHandler不可共存。

package com.bjsxt.springsecuritydemo.config;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationFailureHandler;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationSuccessHandler;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")//loginProcessingUrl 登录页面表单提交地址,此地址可以不真实存在
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/login.html") //配置登陆页面// .successForwardUrl("/toMain") //此处是post请求 重定向到百度。这只是一个示例,具体需要看项目业务需求
.successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))// .failureForwardUrl("/fail"); //登陆失败跳转地址
.failureHandler(new MyAuthenticationFailureHandler("/fail.html"));//url 拦截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被认证
.antMatchers("/fail.html").permitAll()
.anyRequest().authenticated(); //所有的请求都必须被认证。必须登陆后才能访问 //关闭csrf防护
http.csrf().disable();
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

这样之后项目还是可以做到登陆失败的时候重定向到fail.html

八、访问控制url匹配

在前面讲解了认证中所有常用配置,主要是对http.formLogin()

进行操作。而在配置类中http.authorizeRequests()主要是对url进行控

制,也就是我们所说的授权(访问控制)。http.authorizeRequests()

也支持连缀写法,总体公式为:

url匹配规则.权限控制方法

通过上面的公式可以有很多url匹配规则和很多权限控制方法。

这些内容进行各种组合就形成了SpringSecurity中的授权。

在所有匹配规则中取所有规则的交集。配置顺序影响了之后授权

效果,越是具体的应该放在前面,越是笼统的应该放到后面。

1anyRequest()

在之前认证过程中我们就已经使用过anyRequest(),表示匹配所

有的请求。一般情况下此方法都会使用,设置全部内容都需要进行认

证。

代码示例:anyRequest().authenticated();

2antMatcher()

方法定义如下:

publicCantMatchers(String...antPatterns)

参数是不定向参数,每个参数是一个ant表达式,用于匹配URL

规则。

规则如下:

?匹配一个字符

*匹配0个或多个字符*

*匹配0个或多个目录

在实际项目中经常需要放行所有静态资源,下面演示放行js文件

夹下所有脚本文件。

.antMatchers("/js/**").permitAll()

还有一种配置方式是只要是.js文件都放行

antMatchers("/**/*.js").permitAll()

代码体现:

我们在项目中的static下创建images目录,放一张a.jpg,b.png,修改SecurityConfig类:

package com.bjsxt.springsecuritydemo.config;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationFailureHandler;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationSuccessHandler;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")//loginProcessingUrl 登录页面表单提交地址,此地址可以不真实存在
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/login.html") //配置登陆页面// .successForwardUrl("/toMain") //此处是post请求 重定向到百度。这只是一个示例,具体需要看项目业务需求
.successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))// .failureForwardUrl("/fail"); //登陆失败跳转地址
.failureHandler(new MyAuthenticationFailureHandler("/fail.html"));//url 拦截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被认证
.antMatchers("/fail.html").permitAll()//1.下面这种方式表示是js,css,images目录下的所有都不用认证了// .antMatchers("/js/**","/css/**","/images/**").permitAll() //2.下面这种是放行什么类型的文件
.antMatchers("/**/*.jpg").permitAll()
.anyRequest().authenticated(); //所有的请求都必须被认证。必须登陆后才能访问 //关闭csrf防护
http.csrf().disable();
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

上面有两种方式,都试了一下:

第一种:

因为图片都在images目录下

  • 启动项目
  • 访问http://localhost:8080/images/a.jpg
  • 访问http://localhost:8080/images/b.png
  • 都能看到图片

第二种:

  • 启动项目
  • 访问http://localhost:8080/images/a.jpg
  • 访问http://localhost:8080/images/b.png
  • 只有jpg能看到,png的不能看到

现在来看一下项目结构:

v2-99c0933363bb496640b71e9be5833baf_b.jpg

3regexMatchers()

3.1介绍

使用正则表达式进行匹配。和antMatchers()主要的区别就是参

数,antMatchers()参数是ant表达式,regexMatchers()参数是正则表

达式。

演示所有以.js结尾的文件都被放行。

.regexMatchers(".+[.]js").permitAll()

3.2两个参数时使用方式

无论是antMatchers()还是regexMatchers()都具有两个参数的方

法,其中第一个参数都是HttpMethod,表示请求方式,当设置了

HttpMethod后表示只有设定的特定的请求方式才执行对应的权限设

置。

枚举类型HttpMethod内置属性如下:

v2-d1724e6857b66b702b75e55577d3ca72_b.jpg

4mvcMatchers()

mvcMatchers()适用于配置了servletPath的情况。

servletPath就是所有的URL的统一前缀。在SpringBoot整合

SpringMVC的项目中可以在application.properties中添加下面内容设

置ServletPath

spring.mvc.servlet.path=/bjsxt

在SpringSecurity的配置类中配置.servletPath()是mvcMatchers()

返回值特有的方法,antMatchers()和regexMatchers()没有这个方法。

在servletPath()中配置了servletPath后,mvcMatchers()直接写Spring

MVC中@RequestMapping()中设置的路径即可。

.mvcMatchers("demo").servletPath("/bjsxt").permitAll()

如果不习惯使用mvcMatchers()也可以使用antMatchers(),下面

代码和上面代码是等效的

antMatchers("/bjsxt/demo").permitAll()

九、内置访问控制方法介绍

SpringSecurity匹配了URL后调用了permitAll()表示不需要认证,

随意访问。在SpringSecurity中提供了多种内置控制。

1permitAll()

permitAll()表示所匹配的URL任何人都允许访问。

v2-919d7d9a87fd651acc2b1bcc11c52de9_b.jpg

2 authenticated()

authenticated()表示所匹配的 URL 都需要被认证才能访问。

v2-30b7796e9196f1da73484c7357f73061_b.jpg

3 anonymous()

anonymous()表示可以匿名访问匹配的 URL。和 permitAll()效果类

似,只是设置为 anonymous()的 url 会执行 filter 链中

官方源码定义如下:

v2-320a38735ddc3f42365d6e0fca3668e5_b.jpg

4 denyAll()

denyAll()表示所匹配的 URL 都不允许被访问。

v2-8dd4f14fe1d2810915cd98bfb4abd2e3_b.jpg

5 rememberMe()

被“remember me”的用户允许访问

v2-bacd057d904482bb43b6bc466bde8ca3_b.jpg

6 fullyAuthenticated()

如果用户不是被 remember me 的,才可以访问。

v2-5c0462013d39412bdcd8e7508b0e5aa7_b.jpg

十、 角色权限判断

除了之前讲解的内置权限控制。Spring Security 中还支持很多其

他权限控制。这些方法一般都用于用户已经被认证后,判断用户是否

具有特定的要求。

1 hasAuthority(String)

判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑

中创建 User 对象时指定的。

下图中 admin 就是用户的权限。admin 严格区分大小写。

v2-a48fa3f96028975cd4978941ef54b95e_b.jpg

在配置类中通过 hasAuthority(“admin”)设置具有 admin 权限时才能访问。

.antMatchers("/main1.html").hasAuthority("admin")

上面这句话的意思是:有admin权限的用户在登陆之后是可以访问到/main1.html的

2 hasAnyAuthority(String ...)

如果用户具备给定权限中某一个,就允许访问。

下面代码中由于大小写和用户的权限不相同,所以用户无权访问

/main1.html

.antMatchers("/main1.html").hasAnyAuthority("adMin","admiN")

意思是:在用户登陆之后,只要用户具有adMin或者admiN中的一个权限,就可以访问main1.html

3 hasRole(String)

如果用户具备给定角色就允许访问。否则出现 403。

参数取值来源于自定义登录逻辑 UserDetailsService 实现类中创

建 User 对象时给 User 赋予的授权。

在给用户赋予角色时角色需要以:ROLE_ 开头,后面添加角色名

称。例如:ROLE_abc 其中 abc 是角色名,ROLE_是固定的字符开头。

使用 hasRole()时参数也只写 abc 即可。否则启动报错。

给用户赋予角色:

v2-8c936f23e1bc8fb3dbc0c783cddd8e30_b.jpg

在配置类中直接写 abc 即可。

v2-5ed9707d0968123461f06c395f51d097_b.jpg

4 hasAnyRole(String ...)

如果用户具备给定角色的任意一个,就允许被访问

.antMatchers("/main1.html").hasAnyRole("abc","aaa")

5 hasIpAddress(String)

如果请求是指定的 IP 就运行访问。可以通过request.getRemoteAddr()获取 ip 地址。

需要注意的是在本机进行测试时 localhost 和 127.0.0.1 输出的 ip地址是不一样的。

当浏览器中通过 localhost 进行访问时控制台打印的内容:

v2-22c25d32b441bf109f61e153328918f8_b.jpg

当浏览器中通过 127.0.0.1 访问时控制台打印的内容:

v2-60b75f60f3a8bc28cdf03a10cbd355dd_b.jpg

当浏览器中通过具体 ip 进行访问时控制台打印内容:

v2-9fe2f2040967808680ac523f05e366c0_b.jpg

十一、自定义 403 处理方案

使用 Spring Security 时经常会看见 403(无权限),默认情况下

显示的效果如下:

v2-fb55f235bc325f72e5cafe92c3b95e5a_b.jpg

而在实际项目中可能都是一个异步请求,显示上述效果对于用户

就不是特别友好了。Spring Security 支持自定义权限受限。

1 新建类

新建类实现 AccessDeniedHandler,实现接口,重写方法即可

package com.bjsxt.springsecuritydemo.handler;import org.springframework.security.access.AccessDeniedException;import org.springframework.security.web.access.AccessDeniedHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;
@Componentpublic class MyAccessDeniedHandler implements AccessDeniedHandler {
@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print("{code:"权限不足,请联系管理员"}");
}
}

2 修改配置类

配置类中重点添加异常处理器。设置访问受限后交给哪个对象进

行处理。

myAccessDeniedHandler 是在配置类中进行自动注入的。

@Autowiredprivate AccessDeniedHandler deniedHandler;

//异常处理
http.exceptionHandling()
.accessDeniedHandler(deniedHandler);

十二、基于表达式的访问控制

1 access()方法使用

之前学习的登录用户权限判断实际上底层实现都是调用

access(表达式)

v2-f13223fceb952f438247065dafe4dd19_b.jpg

可以通过 access()实现和之前学习的权限控制完成相同的功能

1.1以 hasRole 和 permitAll 举例

下面代码和直接使用 permitAll()和 hasRole()是等效的。

v2-76d0ca7271c69da2e98a8608e118ef9b_b.jpg

2 使用自定义方法

虽然这里面已经包含了很多的表达式(方法)但是在实际项目中很

有可能出现需要自己自定义逻辑的情况。

判断登录用户是否具有访问当前 URL 权限。

2.1新建接口及实现类

新建接口 com.bjsxt.service.MyService 后新建实现类。

package com.bjsxt.springsecuritydemo.service;import org.springframework.security.core.Authentication;import javax.servlet.http.HttpServletRequest;public interface MyService {boolean hasPermission(HttpServletRequest request, Authentication authentication);
}

实现类:

package com.bjsxt.springsecuritydemo.service;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;import java.util.Collection;
@Componentpublic class MyServiceImpl implements MyService {
@Overridepublic boolean hasPermission(HttpServletRequest request, Authentication authentication) {//看看它分配的权限里面是否包含它访问的url
Collection<? extends GrantedAuthority> obj = authentication.getAuthorities();return obj.contains(new SimpleGrantedAuthority(request.getRequestURI()));
}
}

2.2修改配置类

在 access 中通过@bean 的 id 名.方法(参数)的形式进行调用

配置类中修改如下:

package com.bjsxt.springsecuritydemo.config;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationFailureHandler;import com.bjsxt.springsecuritydemo.handler.MyAuthenticationSuccessHandler;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.access.AccessDeniedHandler;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowiredprivate AccessDeniedHandler deniedHandler;
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")//loginProcessingUrl 登录页面表单提交地址,此地址可以不真实存在
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/login.html") //配置登陆页面
.successHandler(new MyAuthenticationSuccessHandler("/main1.html"))
.failureHandler(new MyAuthenticationFailureHandler("/fail.html"));//url 拦截
http.authorizeRequests()
.antMatchers("/login.html").access("permitAll")
.antMatchers("/fail.html").permitAll()
.regexMatchers(".+[.]png").permitAll()
.anyRequest().access("@myServiceImpl.hasPermission(request,authentication)");//关闭csrf防护
http.csrf().disable();//异常处理
http.exceptionHandling()
.accessDeniedHandler(deniedHandler);
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

这时对于任何请求都会进行判断,你是否有当前访问url的权限

权限可以在UserDetailsServiceImpl中添加

package com.bjsxt.springsecuritydemo.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;
@Servicepublic class UserDetailsServiceImpl implements UserDetailsService {
@Autowiredprivate PasswordEncoder encoder;
@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//1.查询数据库判断用户名是否存在,如果不存在抛出UsernameNotFoundExceptionif(!username.equals("admin")){throw new UsernameNotFoundException("用户名不存在!");
}//把查询出来的密码进行编码,或直接把password(已经编码好的了)放到构造方法中。 //理解:password就是数据库中查询出来的密码,查询出来的内容不是123,因为数据库不能明文保存数据
String password = encoder.encode("123");//用“,”分隔多个权限,例如:admin,nomalreturn new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_abc,/main1.html"));
}
}

十三、基于注解的访问控制

在 Spring Security 中提供了一些访问控制的注解。这些注解都是

默认是都不可用的,需要通过@EnableGlobalMethodSecurity 进行开启后使用。

如果设置的条件允许,程序正常执行。如果不允许会报 500

v2-f087eac68cb98f2ead041d18ac4e6d02_b.jpg

这些注解可以写到 Service 接口或方法上上也可以写到 Controller或 Controller 的方法上。通常情况下都是写在控制器方法上的,控制接口 URL 是否允许被访问。

1 @Secured

@Secured 是专门用于判断是否具有角色的。能写在方法或类上。

参数要以 ROLE_开头。

v2-7eee0abe05ae4d4edec2afe39da16ee8_b.jpg

1.1实现步骤

1.1.1 开启注解

在启动类(也可以在配置类等能够扫描的类上)上添加@EnableGlobalMethodSecurity(securedEnabled = true)

package com.bjsxt.springsecuritydemo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@EnableGlobalMethodSecurity(securedEnabled = true)
@SpringBootApplicationpublic class SpringsecuritydemoApplication {public static void main(String[] args) {
SpringApplication.run(SpringsecuritydemoApplication.class, args);
}
}

1.1.2 在控制器方法上添加@Secured 注解

在 LoginController 中方法上添加注解

package com.bjsxt.springsecuritydemo.controller;import org.springframework.security.access.annotation.Secured;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.ResponseBody;
@Controllerpublic class LoginController {
@Secured("ROLE_abc")
@PostMapping("/toMain")public String toMain(){return "redirect:/main.html";
}
@PostMapping("/fail")public String fail(){return "redirect:/fail.html";
}
@GetMapping("/demo")
@ResponseBodypublic String demo(){return "demo";
}
}

1.1.3 配置类

配置类中方法配置保留最基本的配置即可。

package com.bjsxt.springsecuritydemo.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/login.html") //配置登陆页面
.successForwardUrl("/toMain");//url 拦截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被认证
.anyRequest().authenticated();//关闭csrf防护
http.csrf().disable();
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

1.1.4测试

通过UserDetailsServiceImpl来增加或减少用户的权限,然后我们增加ROLE_abc和删除掉这个权限,来看看访问有什么不同。

对比发现,如果分配了这个权限则可以在登陆之后访问到;否则就会在登陆之后报500“不允许访问”的异常

2 @PreAuthorize/@PostAuthorize

@PreAuthorize 和@PostAuthorize 都是方法或类级别注解。

v2-b0ab03273d8a6d59715ac7c1620e144a_b.jpg

@PreAuthorize 表示访问方法或类在执行之前先判断权限,大多

情况下都是使用这个注解,注解的参数和 access()方法参数取值相同,都是权限表达式。

@PostAuthorize 表示方法或类执行结束后判断权限,此注解很少

被使用到。

2.1实现步骤

2.1.1 开启注解

在启动类中开启@PreAuthorize 注解

package com.bjsxt.springsecuritydemo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SpringBootApplicationpublic class SpringsecuritydemoApplication {public static void main(String[] args) {
SpringApplication.run(SpringsecuritydemoApplication.class, args);
}
}

2.1.2 添加@PreAuthorize

在控制器方法上添加@PreAuthorize,参数可以是任何 access()支

持的表达式

package com.bjsxt.springsecuritydemo.controller;import org.springframework.security.access.annotation.Secured;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.ResponseBody;
@Controllerpublic class LoginController {
@PreAuthorize("hasRole('abc')") //hasRole("")不允许以ROLE_开头,在@PreAuthorize中可以以ROLE_开头
@PostMapping("/toMain")public String toMain(){return "redirect:/main.html";
}
@PostMapping("/fail")public String fail(){return "redirect:/fail.html";
}
@GetMapping("/demo")
@ResponseBodypublic String demo(){return "demo";
}
}

2.1.3测试

还是通过修改权限,然后看是否报500的错误

十四、Remember Me 功能实现

Spring Security 中 Remember Me 为“记住我”功能,用户只需要 在登录时添加 remember-me 复选框,取值为 true。Spring Security 会自动把用户信息存储到数据源中,以后就可以不登录进行访问。

1 添加依赖

Spring Security 实 现 Remember Me 功 能 时 底 层 实 现 依 赖Spring-JDBC,所以需要导入 Spring-JDBC。以后多使用 MyBatis 框架而很少直接导入 spring-jdbc,所以此处导入 mybatis 启动器

同时还需要添加 MySQL 驱动

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

2 配置数据源

在 application.properties 中配置数据源。请确保数据库中已经存在 security 数据库

spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/securityspring.datasource.username=rootspring.datasource.password=root

3 编写配置

新建 com.bjsxt.config.RememberMeConfig 类,并创建 Bean 对象

package com.bjsxt.springsecuritydemo.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;import javax.sql.DataSource;
@Configurationpublic class RememberMeConfig {
@Autowiredprivate DataSource dataSource;
@Beanpublic PersistentTokenRepository getPersistentTokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new
JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);//自动建表,第一次启动时需要,第二次启动时注释掉// jdbcTokenRepository.setCreateTableOnStartup(true);return jdbcTokenRepository;
}
}

注意:sonarLint会说DataSource不能autowrite,但是没有关系

4 修改 SecurityConfig

在 SecurityConfig 中添加 RememberMeConfig 和 UserDetailsService 实现类对象,并自动注入。

在 configure 中添加下面配置内容。

package com.bjsxt.springsecuritydemo.config;import com.bjsxt.springsecuritydemo.service.UserDetailsServiceImpl;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.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowiredprivate UserDetailsServiceImpl userDetailsService;
@Autowiredprivate PersistentTokenRepository persistentTokenRepository;
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/login.html") //配置登陆页面
.successForwardUrl("/toMain");//url 拦截
http.authorizeRequests()
.antMatchers("/login.html").permitAll() //login.html不需要被认证
.anyRequest().authenticated();//关闭csrf防护
http.csrf().disable();
http.rememberMe()
.tokenValiditySeconds(60)//单位:秒,默认为两周
.userDetailsService(userDetailsService)//登录逻辑交给哪个对象
.tokenRepository(persistentTokenRepository);//持久层对象
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

5 在客户端页面中添加复选框

在客户端登录页面中添加 remember-me 的复选框,只要用户勾选了复选框下次就不需要进行登录了。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
用户名: <input type="text" name="username123"/> <br/>
密码: <input type="password" name="password123"/> <br/>
记住我:<input type="checkbox" name="remember-me" value="true"/><br/>
<input type="submit" value="登陆"/>
</form>
</body>
</html>

注意:这个记住我的checkbox的name只能叫remember-me,除非修改配置http.rememberMe().rememberMeParameter("remember-me")

6 有效时间

默认情况下重启项目后登录状态失效了。但是可以通过设置状态有效时间,即使项目重新启动下次也可以正常登录。

http.rememberMe()
.tokenValiditySeconds(60)//单位:秒
.userDetailsService(userDetailsService)//登录逻辑交给哪个对象
.tokenRepository(persistentTokenRepository);//持久层对象

十五、Thymeleaf 中 Spring Security 的使用

Spring Security 可以在一些视图技术中进行控制显示效果。例如:JSP 或 Thymeleaf。在非前后端分离且使用 Spring Boot 的项目中多使用 Thymeleaf 作为视图展示技术。

Thymeleaf对Spring Security的支持都放在thymeleaf-extras-springsecurityX 中,目前最新版本为 5。所以需要在项目中添加此 jar 包的依赖和 thymeleaf 的依赖。

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在 html 页面中引入 thymeleaf 命名空间和 security 命名空间

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">

1 获取属性

可以在html页面中通过sec:authentication="" 获取UsernamePasswordAuthenticationToken 中所有 getXXX 的内容,包含父类中的 getXXX 的内容。

根据源码得出下面属性:

  • name:登录账号名称
  • principal:登录主体,在自定义登录逻辑中是 UserDetails
  • credentials:凭证
  • authorities:权限和角色
  • details:实际上是WebAuthenticationDetails的实例。可以获取remoteAddress(客户端ip)和sessionId(当前sessionId)

1.1实现步骤:

1.1.1在templates下新建demo.html

在项目resources中新建templates文件夹,在templates中新建demo.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-springsecurity5">
<head>
<meta charset="UTF-8">
<title>DEMO</title>
</head>
<body>
登录账号:<span sec:authentication="name"></span><br/>
登录账号:<span sec:authentication="principal.username"></span><br/>
凭证:<span sec:authentication="credentials"></span><br/>
权限和角色:<span sec:authentication="authorities"></span><br/>
客户端地址:<span sec:authentication="details.remoteAddress"></span><br/>
sessionId:<span sec:authentication="details.sessionId"></span><br/>
</body>
</html>

1.1.2编写demo.html

在demo.html中编写上面内容,测试获取到的值

1.1.3编写控制器

thymeleaf页面需要控制转发,在控制器类中编写下面方法

package com.bjsxt.springsecuritydemo.controller;import org.springframework.security.access.annotation.Secured;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.ResponseBody;
@Controllerpublic class LoginController {// @Secured("ROLE_abc")
@PreAuthorize("hasRole('abc')") //hasRole("")不允许以ROLE_开头,在@PreAuthorize中可以以ROLE_开头
@PostMapping("/toMain")public String toMain(){return "redirect:/main.html";
}
@PostMapping("/fail")public String fail(){return "redirect:/fail.html";
}
@GetMapping("/demo")public String demo(){return "demo";
}
}

1.1.4测试

  • 启动项目
  • 登陆
  • 然后直接进入http://localhost:8080/demo

v2-8f28d289b64ce166a5a441b1ee17139b_b.jpg

2权限判断

在 html 页面中可以使用 sec:authorize=”表达式”进行权限控制,判断是否显示某些内容。表达式的内容和 access(表达式)的用法相同。如果用户具有指定的权限,则显示对应的内容;如果表达式不成立,则不显示对应的元素。

2.1不同权限的用户显示不同的按钮

2.1.1 设置用户角色和权限

修改UserDetailsServiceImpl设定用户具有 admin,/insert,/delete 权限 ROLE_abc 角色。

package com.bjsxt.springsecuritydemo.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.authority.AuthorityUtils;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.stereotype.Service;
@Servicepublic class UserDetailsServiceImpl implements UserDetailsService {
@Autowiredprivate PasswordEncoder encoder;
@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//1.查询数据库判断用户名是否存在,如果不存在抛出UsernameNotFoundExceptionif(!username.equals("admin")){throw new UsernameNotFoundException("用户名不存在!");
}//把查询出来的密码进行编码,或直接把password(已经编码好的了)放到构造方法中。 //理解:password就是数据库中查询出来的密码,查询出来的内容不是123,因为数据库不能明文保存数据
String password = encoder.encode("123");//用“,”分隔多个权限,例如:admin,nomalreturn new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,/main1.html,ROLE_abc" +",/insert,/delete"));
}
}

2.1.2 控制页面显示效果

在页面中根据用户权限和角色判断页面中显示的内容

修改templates/demo.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-springsecurity5">
<head>
<meta charset="UTF-8">
<title>DEMO</title>
</head>
<body>
登录账号:<span sec:authentication="name"></span><br/>
登录账号:<span sec:authentication="principal.username"></span><br/>
凭证:<span sec:authentication="credentials"></span><br/>
权限和角色:<span sec:authentication="authorities"></span><br/>
客户端地址:<span sec:authentication="details.remoteAddress"></span><br/>
sessionId:<span sec:authentication="details.sessionId"></span><br/>
<hr/>
通过权限判断:
<button sec:authorize="hasAuthority('/insert')">新增</button>
<button sec:authorize="hasAuthority('/delete')">删除</button>
<button sec:authorize="hasAuthority('/update')">修改</button>
<button sec:authorize="hasAuthority('/select')">查看</button>
<br/>
通过角色判断:
<button sec:authorize="hasRole('abc')">新增</button>
<button sec:authorize="hasRole('abc')">删除</button>
<button sec:authorize="hasRole('abc')">修改</button>
<button sec:authorize="hasRole('abc')">查看</button>
</body>
</html>

2.1.3测试

  • 启动项目
  • 登陆,然后访问http://localhost:8080/demo

v2-2d75c78157728517a02c0e00b4891bac_b.jpg

因为权限只有/insert和/delete,其他没有;而角色只需要abc即可

十六、退出登录

用户只需要向 Spring Security 项目中发送/logout 退出请求即可。

1 退出实现

实现退出非常简单,只要在页面中添加/logout 的超链接即可。

<a href="/logout">退出登录</a>

为了实现更好的效果,通常添加退出的配置。默认的退出 url 为/logout,退出成功后跳转到/login?logout

v2-28e76f7d5f5c34c067bc93fc70712c49_b.jpg

如果不希望使用默认值,可以通过下面的方法进行修改。

//退出设置
http.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login.html");

2 logout 其他常用配置源码解读

2.1addLogoutHandler(LogoutHandler)

默认是 contextLogoutHandler

v2-0795649438f1d8407567b622f1475f36_b.jpg

默认实例内容

v2-54639bbba2622081c6684f7658451671_b.jpg

2.2clearAuthentication(boolean)

是否清除认证状态,默认为 true

v2-246b42d3e895cf9ecb646491d53c9d94_b.jpg

2.3invalidateHttpSession(boolean)

是否销毁 HttpSession 对象,默认为 true

v2-5da5eef77bd8faf9fe185cc1e9f60cc5_b.jpg

2.4logoutSuccessHandler(LogoutSuccessHandler)

退出成功处理器。

v2-728184fd4ae6023069505dcf5e4d7843_b.jpg

也可以自己进行定义退出成功处理器。只要实现了LogoutSuccessHandler 接口。与之前讲解的登录成功处理器和登录失败处理器极其类似。

十七、Spring Security 中 CSRF

从刚开始学习 Spring Security 时,在配置类中一直存在这样一行代码:http.csrf().disable();如果没有这行代码导致用户无法被认证。这行代码的含义是:关闭 csrf 防护

1 什么是 CSRF

CSRF(Cross-site request forgery)跨站请求伪造,也被称为“One Click Attack” 或者 Session Riding。通过伪造用户请求访问受信任站点的非法请求访问。

跨域:只要网络协议,ip 地址,端口中任何一个不相同就是跨域请求。

客户端与服务进行交互时,由于 http 协议本身是无状态协议,所以引入了 cookie 进行记录客户端身份。在 cookie 中会存放 session id用来识别客户端身份的。在跨域的情况下,session id 可能被第三方恶意劫持,通过这个 session id 向服务端发起请求时,服务端会认为这个请求是合法的,可能发生很多意想不到的事情。

2 Spring Security 中 CSRF

q从 Spring Security4 开始 CSRF 防护默认开启。默认会拦截请求。进行 CSRF 处理。CSRF 为了保证不是其他第三方网站访问,要求访问时携带参数名为_csrf 值为 token(token 在服务端产生)的内容,如果token 和服务端的 token 匹配成功,则正常访问。

2.1实现步骤

2.1.1 编写控制器方法

编写控制器方法,跳转到 templates 中 login.html 页面。

@RequestMapping("/showLogin")public String showLogin(){return "login";
}

2.1.2 新建 login.html

在项目 resources 下新建 templates 文件夹,并在文件夹中新建login.html 页面。红色部分是必须存在的否则无法正常登录

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
<input type="hidden" th:value="${_csrf.token}" name="_csrf" th:if="${_csrf}"/>
用户名: <input type="text" name="username123"/> <br/>
密码: <input type="password" name="password123"/> <br/>
<input type="submit" value="登陆"/>
</form>
</body>
</html>

2.1.3 修改配置类

在配置类中注释掉 CSRF 防护失效

package com.bjsxt.springsecuritydemo.config;import com.bjsxt.springsecuritydemo.service.UserDetailsServiceImpl;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.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowiredprivate UserDetailsServiceImpl userDetailsService;
@Autowiredprivate PersistentTokenRepository persistentTokenRepository;
@Overrideprotected void configure(HttpSecurity http) throws Exception {//表单认证
http.formLogin()
.usernameParameter("username123")
.passwordParameter("password123")
.loginProcessingUrl("/login") //当发现是/login时认为是登陆,需要执行UserDetailsServiceImpl中的那个方法
.loginPage("/showLogin") //配置登陆页面
.successForwardUrl("/demo");//url 拦截
http.authorizeRequests()
.antMatchers("/showLogin").permitAll() //login.html不需要被认证
.anyRequest().authenticated();
}
@Beanpublic PasswordEncoder setPasswordEncoder(){return new BCryptPasswordEncoder();
}
}

v2-7e69ee40e3f97c67f5891ee9e8e1b9cd_b.jpg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值