1 认证流程
基于Session认证方式的流程是,用户认证成功后,在服务端生成用户相关的数据保存在session(当前会话),而发给客户端的 sesssion_id 存放到 cookie 中,这样用客户端请求时带上 session_id 就可以验证服务器端是否存在session 数据,以此完成用户的合法校验。当用户退出系统或session过期销毁时,客户端的session_id也就无效了。下图是session认证方式的流程图:
基于Session的认证机制由Servlet规范定制,Servlet容器已实现,用户通过HttpSession的操作方法即可实现,如
下是HttpSession相关的操作API。
2 创建工程
本案例工程使用maven进行构建,使用SpringMVC、Servlet3.0实现。以下步骤对应到springboot只需配置文件中配置即可,剩下的自动装配
2.1 创建maven工程
创建maven工程 security-springmvc,工程结构如下:
引入如下依赖如下,注意:
1、由于是web工程,packaging设置为war
2、使用tomcat7-maven-plugin插件来运行工程
<?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.oldlu.security</groupId> <artifactId>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</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>
2.2 Spring 容器配置
在confifig包下定义ApplicationConfifig.java,它对应web.xml中ContextLoaderListener的配置
@Configuration @ComponentScan(basePackages = "com.oldlu.security.springmvc" ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) public class ApplicationConfig { //在此配置除了Controller的其它bean,比如:数据库链接池、事务管理器、业务bean等。 }
2.3 servletContext配置
本案例采用Servlet3.0无web.xml方式,的confifig包下定义WebConfifig.java,它对应s对应于DispatcherServlet配置。
@Configuration//就相当于springmvc.xml文件 @EnableWebMvc @ComponentScan(basePackages = "com.oldlu.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; } }
2.4 加载 Spring容器
在init包下定义Spring容器初始化类SpringApplicationInitializer,此类实现WebApplicationInitializer接口,Spring容器启动时加载WebApplicationInitializer接口的所有实现类。
/** * @author Administrator * @version 1.0 **/ public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //spring容器,相当于加载 applicationContext.xml @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{ApplicationConfig.class}; } //servletContext,相当于加载springmvc.xml @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } //url-mapping @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
SpringApplicationInitializer相当于web.xml,使用了servlet3.0开发则不需要再定义web.xml,
ApplicationConfifig.class对应以下配置的application-context.xml,WebConfifig.class对应以下配置的spring-mvc.xml,web.xml的内容参考:
<web‐app> <listener> <listener‐class>org.springframework.web.context.ContextLoaderListener</listener‐class> </listener> <context‐param> <param‐name>contextConfigLocation</param‐name> <param‐value>/WEB‐INF/application‐context.xml</param‐value> </context‐param> <servlet> <servlet‐name>springmvc</servlet‐name> <servlet‐class>org.springframework.web.servlet.DispatcherServlet</servlet‐class> <init‐param> <param‐name>contextConfigLocation</param‐name> <param‐value>/WEB‐INF/spring‐mvc.xml</param‐value> </init‐param> <load‐on‐startup>1</load‐on‐startup> </servlet> <servlet‐mapping> <servlet‐name>springmvc</servlet‐name> <url‐pattern>/</url‐pattern> </servlet‐mapping> </web‐app>
3 实现认证功能
3.1 认证页面
在webapp/WEB-INF/views下定义认证页面login.jsp,本案例只是测试认证流程,页面没有添加css样式,页面实
现可填入用户名,密码,触发登录将提交表单信息至/login,内容如下:
<%@ page contentType="text/html;charset=UTF‐8" pageEncoding="utf‐8" %> <html> <head> <title>用户登录</title> </head> <body> <form action="login" method="post"> 用户名:<input type="text" name="username"><br> 密 码: <input type="password" name="password"><br> <input type="submit" value="登录"> </form> </body> </html>
在WebConfifig中新增如下配置,将/直接导向login.jsp页面
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); }
3.2 认证接口
用户进入认证页面,输入账号和密码,点击登录,请求/login进行身份认证。
(1)定义认证接口,此接口用于对传来的用户名、密码校验,若成功则返回该用户的详细信息,否则抛出错误异常:
/** * Created by Administrator. */ public interface AuthenticationService { /** * 用户认证 * @param authenticationRequest 用户认证请求,账号和密码 * @return 认证成功的用户信息 */ UserDto authentication(AuthenticationRequest authenticationRequest); }
认证请求结构:
/** * @author Administrator * @version 1.0 **/ @Data public class AuthenticationRequest { //认证请求参数,账号、密码。。 /** * 用户名 */ private String username; /** * 密码 */ private String password; }
认证成功后返回的用户详细信息,也就是当前登录用户的信息:
/** * @author Administrator * @version 1.0 **/ @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; }
(2)认证实现类,根据用户名查找用户信息,并校验密码,这里模拟了两个用户:
/** * @author Administrator * @version 1.0 **/ @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)); } }
(3)登录Controller,对/login请求处理,它调用AuthenticationService完成认证并返回登录结果提示信息:
/** * @author Administrator * @version 1.0 **/ @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"; } }
(5)测试
启动项目,访问/路径地址,进行测试
以上的测试全部符合预期,到目前为止最基础的认证功能已经完成,它仅仅实现了对用户身份凭证的校验,若某用户认证成功,只能说明他是该系统的一个合法用户,仅此而已。