一 基于session的认证流程
1.1 认证流程
基于Session的认证机制由Servlet规范定制,Servlet容器已实现,用户通过HttpSession的操作方法即可实现。
1.2 java的api
1.3 拦截器的使用
见下文第二章节,查看2.4.5 章节,拦截器案例的使用
二 基于session的案例
2.1 案例说明
1.工程说明:使用maven进行构建,使用SpringMVC、Servlet3.0实现。其中servlet3.0不再使用配置文件,使用配置类来实现。
ApplicationConfifig.class对应以下配置的application-context.xml,
WebConfifig.class对应以下配置的spring- mvc.xml
ApplicationConfig //相当于applicationContext.xml
WebConfig // 就相当于springmvc.xml文件
SpringApplicationInitializer 相当于web.xml
2.截图
注意后面:拦截器的使用案例: 2.4.5 *****编写拦截器******
2.1 创建工程
2.1.1 pom文件配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- spring web mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- lombok 降成1.16.6版本,防止出现和tomcat不兼容的情况 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
</dependency>
2.1.2 spring容器的配置
@Configuration //相当于applicationContext.xml
@ComponentScan(basePackages = "com.ljf.spring.session"
//排除@controller注解标注的类,排除我们不希望spring容器加载的类。
,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class ApplicationConfig {
//在此配置除了Controller的其它bean,比如:数据库链接池、事务管理器、业务bean等。
}
2.1.3 servletContext配置
package com.ljf.spring.session.config;
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;
/**
* @author Administrator
* @version 1.0
**/
@Configuration //就相当于springmvc.xml文件
@EnableWebMvc
@ComponentScan(basePackages = "com.ljf.spring.session"
,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("login");
}
}
2.1.4 加载spring容器
package com.ljf.spring.session.init;
import com.ljf.spring.session.config.ApplicationConfig;
import com.ljf.spring.session.config.WebConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/** 在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[]{"/"};
}
}
2.2 认证
2.2.1 配置认证页面
<%@ 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>
2.2.2 在配置类中新增登录页面的跳转路径
1.在WebConfifig中新增如下配置,将/直接导向login.jsp页面:
2.代码
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//指向的是webapp/web-inf/view/login.jsp这个页面
registry.addViewController("/").setViewName("login");
}
2.2.3 启动访问
发布
页面访问
tomcat的日志:
2.2.4 配置认证接口
1.controller
前端提交登录后跳转到这里:
/*** 用户登录 *
@param authenticationRequest 登录请求
* @return */
@PostMapping(value = "/login",produces = {"text/plain;charset=UTF‐8"})
public String login(AuthenticationRequest authenticationRequest){
UserDetails userDetails = authenticationService.authentication(authenticationRequest);
return userDetails.getFullname() + " 登录成功";
}
2.定义service内容
public interface AuthenticationService {
/**
* 用户认证
* @param authenticationRequest 用户认证请求,账号和密码
* @return 认证成功的用户信息
*/
UserDto authentication(AuthenticationRequest authenticationRequest);
}
2.实现类: 配置用户所属的权限类
package com.ljf.spring.session.service;
import com.ljf.spring.session.model.AuthenticationRequest;
import com.ljf.spring.session.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;
/**
* @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.javabean
1.AuthenticationRequest
@Data
public class AuthenticationRequest {
//认证请求参数,账号、密码。。
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
}
4.userDto
@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;
}
5.测试
1.正确输入用户名和密码
2.输入错误的用户名和密码
6.总结
2.3 会话
2.3.1 增加会话控制
2.3.2 session的存储与销毁
在loginController中进行修改,将登录认证信息,存入session中,认证成功后,将用户信息放入当前会话。并增加用户登出方法,登出时将session置为 失效。
2.3.3 设置可以访问的资源
1.controller编写代码:从session中获取是否有登录的信息
@GetMapping(value = "/user/show",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";
}
2. 资源进行访问
1.未登录的情况
2.登录的情况下
1.进行登录
进行资源的访问:
2.3.4 总结
总结:在用户登录成功时,该用户信息已被成功放入session,并且后续请求可以正常从session中获取当 前登录用户信息,符合预期结果。
2.4 授权
2.4.1 授权实现目标
2.4.2 增加权限
2.4.3 模拟用户分配权限
在AuthenticationServiceImpl中为模拟用户初始化权限,其中张三给了p1权限,李四给了p2权限。
2.4.4 controller层增加用户资源
2.4.5 **编写拦截器判断session中是否用信息
package com.ljf.spring.session.interceptor;
import com.ljf.spring.session.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;
/**
* @author Administrator
* @version 1.0
**/
@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("/user/show")){
return true;
}
if( userDto.getAuthorities().contains("p2") && requestURI.contains("/order/show")){
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();
}
}
2.4.6 配置拦截器**
@Autowired private SimpleAuthenticationInterceptor simpleAuthenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/user/**");
registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/order/**");
}
2.4.7 测试
1.未登录情况下,/user/show与/order/show均提示 “请先登录”。
2.在登录的情况下:zhangsan登录,lisi未登录
1.在用户zhangsan登录的后:
2.张三访问用户资源
3.张三访问订单资源
总结:
1.张三登录情况下,由于张三有p1权限,因此可以访问/user/show,张三没有p2权限,访问/r/r2时提示 “权限不足 “。