然后修改Logincontroller,认证成功后,将用户信息放入当前会话。并增加用户登出方法,登出时将session置为失效。
package com.uncle.security.springmvc.controller; import com.uncle.security.springmvc.model.AuthenticationRequest; import com.uncle.security.springmvc.model.UserDto; import com.uncle.security.springmvc.service.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:33 */ @RestController public class LoginController { @Autowired AuthenticationService authenticationService; @RequestMapping(value = "/login",produces = "text/plain;charset=utf-8") public String login(AuthenticationRequest authenticationRequest, HttpSession session){ UserDto userDto = authenticationService.authentication(authenticationRequest); //存入session session.setAttribute(UserDto.SESSION_USER_KEY,userDto); return userDto.getUsername() +"登录成功"; } @GetMapping(value = "/logout",produces = {"text/plain;charset=UTF-8"}) public String logout(HttpSession session){ session.invalidate(); return "退出成功"; } }
2、增加测试资源
修改Logincontroller ,增加测试资源1 ,它从当前会话session中获取当前登录用户,并返回提示信息给前台。
package com.uncle.security.springmvc.controller; import com.uncle.security.springmvc.model.AuthenticationRequest; import com.uncle.security.springmvc.model.UserDto; import com.uncle.security.springmvc.service.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:33 */ @RestController public class LoginController { @Autowired AuthenticationService authenticationService; @RequestMapping(value = "/login",produces = "text/plain;charset=utf-8") public String login(AuthenticationRequest authenticationRequest, HttpSession session){ UserDto userDto = authenticationService.authentication(authenticationRequest); //存入session session.setAttribute(UserDto.SESSION_USER_KEY,userDto); return userDto.getUsername() +"登录成功"; } @GetMapping(value = "/logout",produces = {"text/plain;charset=UTF-8"}) public String logout(HttpSession session){ session.invalidate(); return "退出成功"; } @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"}) public String r1(HttpSession session){ String fullname = null; Object object = session.getAttribute(UserDto.SESSION_USER_KEY); if(object == null){ fullname = "匿名"; }else{ UserDto userDto = (UserDto) object; fullname = userDto.getFullname(); } return fullname+"访问资源r1"; } }
3、测试
未登录情况下直接访问测试资源/r/r1 :
成功登录的情况下访问测试资源/r/r1 :
退出,访问地址/logout
测试结果说明,在用户登录成功时,该用户信息已被成功放入session ,并且后续请求可以正常从session中获取当前登录用户信息,退出时,session失效,再次访问为匿名访问,符合预期结果。
2.5 实现授权功能
现在我们已经完成了用户身份凭证的校验以及登录的状态保持,并且我们也知道了如何获取当前登录用户(从Session中获取)的信息,接下来,用户访问系统需要经过授权,即需要完成如下功能:
- 匿名用户(未登录用户)访问拦截:禁止匿名用户访问某些资源。
- 登录用户访问拦截:根据用户的权限决定是否能访问某些资源。
1、增加权限数据
为了实现这样的功能,我们需要在UserDto里增加权限属性,用于表示该登录用户所拥有的权限,同时修改 UserDto的构造方法。
package com.uncle.security.springmvc.model; import lombok.AllArgsConstructor; import lombok.Data; import java.util.Set; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:25 */ @Data @AllArgsConstructor public class UserDto { public static final String SESSION_USER_KEY = "_user"; //用户身份信息 private String id; private String username; private String password; private String fullname; private String mobile; /** * 用户权限 */ private Set<String> authorities; }
并在AuthenticationServicelmpI中为模拟用户初始化权限,其中张三给了p1权限,李四给了p2权限。
package com.uncle.security.springmvc.service; import com.uncle.security.springmvc.model.AuthenticationRequest; import com.uncle.security.springmvc.model.UserDto; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:27 */ @Service public class AuthenticationServiceImpl implements AuthenticationService{ /** * 用户认证,校验用户身份信息是否合法 * * @param authenticationRequest 用户认证请求,账号和密码 * @return 认证成功的用户信息 */ @Override public UserDto authentication(AuthenticationRequest authenticationRequest) { //校验参数是否为空 if(authenticationRequest == null || StringUtils.isEmpty(authenticationRequest.getUsername()) || StringUtils.isEmpty(authenticationRequest.getPassword())){ throw new RuntimeException("账号和密码为空"); } //根据账号去查询数据库,这里测试程序采用模拟方法 UserDto user = getUserDto(authenticationRequest.getUsername()); //判断用户是否为空 if(user == null){ throw new RuntimeException("查询不到该用户"); } //校验密码 if(!authenticationRequest.getPassword().equals(user.getPassword())){ throw new RuntimeException("账号或密码错误"); } //认证通过,返回用户身份信息 return user; } //根据账号查询用户信息 private UserDto getUserDto(String userName){ return userMap.get(userName); } //用户信息 private Map<String,UserDto> userMap = new HashMap<>(); { Set<String> authorities1 = new HashSet<>(); authorities1.add("p1");//这个p1我们人为让它和/r/r1对应 Set<String> authorities2 = new HashSet<>(); authorities2.add("p2");//这个p2我们人为让它和/r/r2对应 userMap.put("zhangsan",new UserDto("1010","zhangsan","123","张三","133443",authorities1)); userMap.put("lisi",new UserDto("1011","lisi","456","李四","144553",authorities2)); } }
2、增加测试资源
我们想实现针对不同的用户能访问不同的资源,前提是得有多个资源,因此在Logincontroller中增加测试资源2。
package com.uncle.security.springmvc.controller; import com.uncle.security.springmvc.model.AuthenticationRequest; import com.uncle.security.springmvc.model.UserDto; import com.uncle.security.springmvc.service.AuthenticationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:33 */ @RestController public class LoginController { @Autowired AuthenticationService authenticationService; @RequestMapping(value = "/login",produces = "text/plain;charset=utf-8") public String login(AuthenticationRequest authenticationRequest, HttpSession session){ UserDto userDto = authenticationService.authentication(authenticationRequest); //存入session session.setAttribute(UserDto.SESSION_USER_KEY,userDto); return userDto.getUsername() +"登录成功"; } @GetMapping(value = "/logout",produces = {"text/plain;charset=UTF-8"}) public String logout(HttpSession session){ session.invalidate(); return "退出成功"; } @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"}) public String r1(HttpSession session){ String fullname = null; Object object = session.getAttribute(UserDto.SESSION_USER_KEY); if(object == null){ fullname = "匿名"; }else{ UserDto userDto = (UserDto) object; fullname = userDto.getFullname(); } return fullname+"访问资源r1"; } @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"}) public String r2(HttpSession session){ String fullname = null; Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY); if(userObj != null){ fullname = ((UserDto)userObj).getFullname(); }else{ fullname = "匿名"; } return fullname + " 访问资源2"; } }
3、实现授权拦截器
在interceptor包下定义SimpleAuthenticationlnterceptor拦截器,实现授权拦截:
- 校验用户是否登录
- 校验用户是否拥有操作权限
package com.uncle.security.springmvc.interceptor; import com.uncle.security.springmvc.model.UserDto; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 23:53 */ @Component public class SimpleAuthenticationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //在这个方法中校验用户请求的url是否在用户的权限范围内 //取出用户身份信息 Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY); if(object == null){ //没有认证,提示登录 writeContent(response,"请登录"); } UserDto userDto = (UserDto) object; //请求的url String requestURI = request.getRequestURI(); if( userDto.getAuthorities().contains("p1") && requestURI.contains("/r/r1")){ return true; } if( userDto.getAuthorities().contains("p2") && requestURI.contains("/r/r2")){ return true; } writeContent(response,"没有权限,拒绝访问"); return false; } //响应信息给客户端 private void writeContent(HttpServletResponse response, String msg) throws IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.print(msg); writer.close(); } }
在WebConfig中配置拦截器,匹配/r/**的资源为受保护的系统资源,访问该资源的请求进入SimpleAuthenticationInterceptor 拦截器。
package com.uncle.security.springmvc.config; import com.uncle.security.springmvc.interceptor.SimpleAuthenticationInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 21:34 */ @Configuration//就相当于springmvc.xml文件 @EnableWebMvc @ComponentScan(basePackages = "com.uncle.security.springmvc" ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) public class WebConfig implements WebMvcConfigurer { @Autowired SimpleAuthenticationInterceptor simpleAuthenticationInterceptor; //视频解析器 @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/r/**"); } }
4、测试
未登录情况下,/r/r1与/r/r2均提示"请先登录
张三登录情况下,由于张三有p1权限,因此可以访问/r/r1 ,张三没有p2权限,访问/r/r2时提示"权限不足"。
同理,李四登录情况下,由于李四有p2权限,因此可以访问/r/r2,李四没有p1权限,访问/r/r1时提示"权限不足"。(图略过)
测试结果全部符合预期结果。
2.6 小结
基于Session的认证方式是一种常见的认证方式,至今还有非常多的系统在使用。我们在此小节使用Springmvc技术对它进行简单实现,旨在让大家更清晰实在的了解用户认证、授权以及会话的功能意义及实现套路,也就是它们分别干了哪些事儿?大概需要怎么做?而在正式生产项目中,我们往往会考虑使用第三方安全框架(如spring security ,shiro等安全框架)来实现认证授权功能,因为这样做能一定程度提高生产力,提高软件标准化程度,另外往往这些框架的可扩展性考虑的非常全面。但是缺点也非常明显,这些通用化组件为了提高支持范围会增加很多可能我们不需要的功能,结构上也会比较抽象,如果我们不够了解它,一旦出现问题,将会很难定位。
三、初识Spring Security
3.1 简介
SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。由于它是Spring生态系统中的一员,因此它伴随着整个Spring生态系统不断修正、升级,在springboot项目中加入Spring Security更是十分简单,使用SpringSecurity减少了为企业系统安全控制编写大量重复代码的工作。
Spring Security的前身是Acegi Security,在被收纳为Spring子项目后正式更名为SpringSecurity。笔者在完成这篇文章时,SpringSecurity已经升级到了5.5.1版本(5.3.10.RELEASE),SpringSecurity5.x以后不仅增加了原生的OAuth框架,还支持更加现代化的密码加密方式,可以预见,在java应用安全领域,SpringSecurity会成为首先被推崇的安全解决方案。
3.2 创建工程
3.2.1 创建maven工程
创建maven工程 ,工程结构如下:
引入以下依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.uncle</groupId> <artifactId>spring-security-springmvc</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency> </dependencies> <build> <finalName>security-springmvc</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>utf-8</encoding> <useDefaultDelimiters>true</useDefaultDelimiters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
3.2.2 Spring容器配置
package com.uncle.security.springmvc.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.stereotype.Controller; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 21:26 */ @Configuration @ComponentScan(basePackages = "com.uncle.security.springmvc" ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)}) public class ApplicationConfig { }
3.2.4 Servlet Context配置
package com.uncle.security.springmvc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 21:34 */ @Configuration//就相当于springmvc.xml文件 @EnableWebMvc @ComponentScan(basePackages = "com.uncle.security.springmvc" ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) public class WebConfig implements WebMvcConfigurer { //视频解析器 @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("redirect:/login"); } }
此处插一句题外话,有人问我这个配置什么意思
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("redirect:/login"); }
这个配置确实不常见,但是确实有很大用处,其实理解起来也很容易,上面的写法等同于如下的写法
@Controller public class TestContrller { @RequestMapping("/test") public String test() { return "redirect:/login"; } }
这时可能会有同学问,如果当redirect后的字符串同时存在于url和页面会重定向哪里,经笔者验证后,答案是页面的优先级会更高,感兴趣的读者可以自行去验证,笔者就不再赘述。
3.2.4 加载Spring容器
在init包下定义Spring容器初始化类SpringApplicationlnitializer,此类实现WebApplicationlnitializer接口, Spring容器启动时加载WebApplicationlnitializer接口的所有实现类。
package com.uncle.security.springmvc.init; import com.uncle.security.springmvc.config.ApplicationConfig; import com.uncle.security.springmvc.config.WebConfig; import com.uncle.security.springmvc.config.WebSecurityConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 21:47 */ public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //spring容器,相当于加载 applicationContext.xml @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{ApplicationConfig.class, WebSecurityConfig.class}; } //servletContext,相当于加载springmvc.xml @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } //url-mapping @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
3.3 认证
3.3.1 认证页面
SpringSecurity默认提供认证页面。
3.3.2 安全配置
spring security提供了用户名密码登录、退出、会话管理等认证功能,只需要配置即可使用。
在config包下定义WebSecurityConfig ,安全配置的内容包括:用户信息、密码编码器、安全拦截机制。
package com.uncle.security.springmvc.config; import org.springframework.context.annotation.Bean; 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.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; /** * @program: spring-security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-23 00:41 */ @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定义用户信息服务(查询用户信息) @Bean public UserDetailsService userDetailsService(){ InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build()); manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build()); return manager; } //密码编码器 @Bean public PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } //安全拦截机制(最重要) @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过 .anyRequest().permitAll()//除了/r/**,其它的请求可以访问 .and() .formLogin()//允许表单登录 .successForwardUrl("/login-success");//自定义登录成功的页面地址 } }
在userDetailsService()方法中,我们返回了一个UserDetailsService给spring容器,Spring
Security会使用它来获取用户信息。我们暂时使用InMemoryUserDetailsManager实现类,并在其中分别创建了zhangsan、lisi两个用户,并设置密码和权限。
而在configure()中,我们通过HttpSecurity设置了安全拦截规则,其中包含了以下内容:
- url匹配"/**的资源,经过认证后才能访问。
- 其他url完全开放。
- 支持form表单认证,认证成功后转向/login-success。
- 加载 WebSecurityConfig
修改SpringApplicationlinitializer的getRootConfigClasses()方法,添加WebSecurityConfig.class:
package com.uncle.security.springmvc.init; import com.uncle.security.springmvc.config.ApplicationConfig; import com.uncle.security.springmvc.config.WebConfig; import com.uncle.security.springmvc.config.WebSecurityConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @program: security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-22 21:47 */ public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //spring容器,相当于加载 applicationContext.xml @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{ApplicationConfig.class, WebSecurityConfig.class}; } //servletContext,相当于加载springmvc.xml @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } //url-mapping @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
3.3.3 初始化
Spring Security初始化,这里有两种情况
- 若当前环境没有使用Spring或Spring MVC ,则需要将WebSecurityConfig(Spring Security配置类)传入超类,以确保获取配置,并创建spring context。
- 相反,若当前环境已经使用spring ,我们应该在现有的springContext中注册Spring Security(上一步已经将 WebSecurityConfig加载至rootcontext),此方法可以什么都不做。
package com.uncle.security.springmvc.init; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * @program: spring-security-springmvc * @description: * @author: 步尔斯特 * @create: 2021-07-23 00:46 */ @EnableWebSecurity public class SpringSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer { public SpringSecurityApplicationInitializer() { //super(WebSecurityConfig.class); } }