传统Session认证方式和SpringSecurity认证

发布于 2022-08-14  2.6k 次阅读


1. 基于session的传统认证方式

1.1 Session的认证流程

交互流程:用户认证成功后,在服务端生成用户相关的数据保存在session(当前会话)中,发给客户端的session_id存放到cookie中,这样用户客户端请求时带上session_id就可以验证服务器端是否存在session数据,以此完成用户的合法性效验,当用户退出系统或session过期销毁时,客户端session_id也就无效

基于Session的认证机制由Servlet规范实现,用户通过HttpSession的操作方法即可实现:

方法
含义
HttpSession getSession(Boolean create)
获取当前的HttpSession对象
void setAttribute(String name,Object value)
向session中存储对象
object getAttribute(String name)
从session中获取对象
void removeAttribute(String name)
移除session中对象
…………
…………

1.2 创建并配置工程

创建一个maven工程

1.2.1 加入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.21.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

1.2.2 Spring容器配置

在config包下定义ApplicationConfig.java,它对应web.xml中ContextLoaderListener的配置
@Configuration
@ComponentScan(basePackages = "com.kxjsecurity.springmvc",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})

public class applicationConfig {
    //在此配置除了Controller的其他bean,比如:数据库连接池、事物管理器、业务bean等
    
}

1.2.3 servletContext配置

本案例采用Servlet3.0无web.xml的配置类方式,在config包下定义WebConfig.java,它对应servlet的DispatchServlet配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.kxjsecurity.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/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

1.2.4 加载Spring容器

    在init包下定义Spring容器初始化类SpringApplicationInitalizer,此类实现WebApplicationInitalizer接口,Spring容器启动时加载WebApplicationInitalizer接口的所有实现类

public class SpringApplicationInitalizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //指定rootContext的配置类
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{applicationConfig.class};
    }

    //指定servletContext的配置类
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    //url-map
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

1.3 认证功能

1.3.1 登录页面准备

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="login" method="post">
        用户名:<input type="text" name="username">

        密&nbsp;&nbsp;码:
        <input type="password" name="password">

        <input type="submit" value="登录">
    </form>
</body>
</html>

在WebConfig中新增如下配置:将/直接导向login.jsp

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController( "/").setViewName("login");
}

1.3.2 认证接口 

① 认证方法

//实现自定义接口
public class AuthenticationServiceimpl implements  AuthenticationService {

    @Override
    public UserDetails authentication(authenticationRequest auth) {

         if(ObjectUtils.isEmpty(auth) || StringUtils.isEmpty(auth.getUsername()) || StringUtils.isEmpty(auth.getPassword())){

             throw new RuntimeException("账号或者密码为空!");
         }

        UserDetails user = getUser(auth.getUsername());

         if(!user.getPassword().equals(auth.getPassword())){

             throw new RuntimeException("密码错误!");
         }

        return user;
    }

    //模拟查询
    private UserDetails getUser(String username){

        UserDetails userDetails = map.get(username);

        if(ObjectUtils.isEmpty(userDetails)){
            throw new RuntimeException("用户不存在!");
        }

        return userDetails;
    }

    //模拟数据
    private HashMap<String,UserDetails> map;

    {
        map.put("lishi",new UserDetails("1","lishi","123456"));
        map.put("wangwu",new UserDetails("2","wangwu","123456"));
    }}

② 用户类和效验类

//用户类
@Data
public class UserDetails {
    String id;
    String username;
    String password;
    String fullname;
    String mobile;

    public UserDetails(String id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.fullname="";
        this.mobile="";
    }
}

//效验类
@Data
public class authenticationRequest {

    String username;

    String password;
}

③ controller

@RestController
public class LoginController {

    @Autowired
    AuthenticationServiceimpl authenticationService;

    @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
    public String login(authenticationRequest a){


        UserDetails authentication = authenticationService.authentication(a);
        return authentication.getUsername()+"登录成功!";
    }
}

1.4 会话功能

    会话是指用户登入系统后,系统会记住该用户的登录状态,他可以在系统连续操作直至退出系统的操作

    认证的目的是对系统资源的保护,每次对资源的访问,系统必须得知道谁在访问资源,才能对该请求进行合法性拦截。因此在认证成功后,一般会把认证成功的用户信息放入Session中,在后续的请求中,系统能够从Session中获取到当前用户,用这样的方式实现会话机制

① 增加会话控制

    首先在UserDetails中定义一个SESSION_USER_KEY,作为Session中存放登录用户信息的key

static final String SESSION_USER_KEY="_user";

② 修改LoginController

    认证成功后,将用户信息放入当前会话。并增加用户登出方法,登出后session失效

@RestController
public class LoginController {

    @Autowired
    AuthenticationServiceimpl authenticationService

    @RequestMapping(value = "/login",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
    public String login(authenticationRequest a, HttpSession session){

        UserDetails authentication = authenticationService.authentication(a);

        //存入session
        session.setAttribute(UserDetails.SESSION_USER_KEY,authentication);

        return authentication.getUsername()+"登录成功!";
    }

    //测试是否有状态信息
    @RequestMapping(value = "/status",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
    public String status(HttpSession session){

        Object attribute = session.getAttribute(UserDetails.SESSION_USER_KEY);

        if(ObjectUtils.isEmpty(attribute)){
            return "匿名访问!";
        }

        UserDetails Details=(UserDetails)attribute;

        return Details.getUsername()+"访问!";
    }

    //退出
    @RequestMapping(value = "/logout",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
    public String logout(HttpSession session){
        //删除session
        session.removeAttribute(UserDetails.SESSION_USER_KEY);

        return "退出成功!";
    }
}

1.5 授权功能

用户访问系统需要进行如下授权,即需要实现如下功能:
  • 匿名用户(未登录用户)访问拦截:禁止匿名用户访问某些资源
  • 登录用户访问拦截:根据用户的权限决定是否能访问某些资源
① 增加权限数据
    在UserDetails里增加权限属性,用于标识该登录用户所拥有的权限,同时修改UserDetails的构造方法
Set<String> authorities;
public UserDetails(String id, String username, String password,Set<String> authorities) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.authorities=authorities;
    this.fullname="";
    this.mobile="";
}

在AuthenticationServiceimpl中为模拟用户初始化权限,其中lishi给了a1权限,wangwu给a2权限

private HashMap<String,UserDetails> map = new HashMap<>();
{
    Set<String> a1 = new HashSet<>();
    a1.add("a1");
    Set<String> a2 = new HashSet<>();
    a1.add("a2");

    map.put("lishi",new UserDetails("1","lishi","123456",a1));
    map.put("wangwu",new UserDetails("2","wangwu","123456",a2));
}

② 增加测试资源

针对不同的用户能访问不同的资源,前提是得有多个资源,因此在LoginController中增加测试资源2

//测试资源2
@RequestMapping(value = "/wql/resource",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
public String resource(HttpSession session){

    Object attribute = session.getAttribute(UserDetails.SESSION_USER_KEY);

    if(ObjectUtils.isEmpty(attribute)){
        return "匿名访问!";
    }

    UserDetails Details=(UserDetails)attribute;

    return Details.getUsername()+"访问资源2!";
}

③ 实现授权拦截器

在interceptor包下定义SimpleAuthenticationInterceptor拦截器,实现授权拦截:

  1. 效验用户是否登录
  2. 效验用户是否拥有操作权限
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    //通过这个方法效验用户请求是否在权限范围内
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.通过session判断用户是否登录
        Object attribute = request.getSession().getAttribute(UserDetails.SESSION_USER_KEY);

        if(attribute==null) {
            //没有认证提示登录
            writeContent(response,"请登录");
        }

        UserDetails userDetails = (UserDetails)attribute;
        //请求URL
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        System.out.println(userDetails.getUsername()+"\t"+userDetails.getAuthorities());
        if(userDetails.getAuthorities().contains("a1") && requestURI.contains("/wql/status")){
            return true;
        }

        if(userDetails.getAuthorities().contains("a2") && requestURI.contains("/wql/resource")){
            return true;
        }

        writeContent(response,"没有权限访问!");
        return false;
    }

    //响应信息给前端
    private void writeContent(HttpServletResponse response, String message) throws IOException {
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(message);
        writer.close();
    }
}

④ 添加拦截器配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.kxjsecurity.springmvc",
                includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    SimpleAuthenticationInterceptor simpleAuthenticationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/wql/**");
    }
}

测试:

  • lishi有a1权限,可以顺利访问/wql/status资源,但无权访问/wql/resource
  • wangwu则反之

总结: 基于Session的认证方式是一种常见的认证方式, 而在正式生产项目中,往往会考虑使用第三方安全框架(如spring security, shiro等安全框架)来实现认证授权功能,因为这样做能一定程度提高生产力,提高软件标准化程度,另外往往这些框架的可扩展性考虑的非常全面。但是缺点也非常明显,这些通用化组件为了提高支持范围会增加很多可能我们不需要的功能,结构上也会,比较抽象,如果我们不够了解它,一旦出现问题,将会很难定位。

2. Spring Security认证

2.1 创建并配置工程

创建一个maven工程

2.1.1 引入依赖

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>5.3.8.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.3.8.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.21.RELEASE</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>

2.1.2 Spring容器配置 

在config包下定义ApplicationConfig.java,它对应web.xml中ContextLoaderListener的配置

@Configuration
@ComponentScan(basePackages = "com.kxjsecurity.springmvc",excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})

public class applicationConfig {
    //在此配置除了Controller的其他bean,比如:数据库连接池、事物管理器、业务bean等
    
}

2.1.3 servletContext配置

同session认证一样

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.kxjsecurity.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/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

2.1.4 加载Spring容器

    在init包下定义Spring容器初始化类SpringApplicationInitalizer,此类实现WebApplicationInitalizer接口,Spring容器启动时加载WebApplicationInitalizer接口的所有实现类

public class SpringApplicationInitalizer extends AbstractAnnotationConfigDispatcherServletInitializer {

    //指定rootContext的配置类
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{applicationConfig.class};
    }

    //指定servletContext的配置类
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    //url-map
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

2.2 SpringSecurity认证功能

2.2.1 安全配置

spring security提供了用户名密码登录、退出、会话管理等认证功能,只需要配主即可使用

① 在config包下定义WebSecurityConfig,安全配置的内容包括:用户信息、密码编码器、安全拦截机制

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //1,定义用户信息服务
    @Bean
    public UserDetailsService userDetailsService(){

        //基于内存的用户信息服务
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("lishi").password("123").authorities("a1").build());
        manager.createUser(User.withUsername("wangwu").password("123").authorities("a2").build());
        return manager;
    }

    //2,密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        //不需要对密码进行编码
        return NoOpPasswordEncoder.getInstance();
    }

    //3,安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/wql/**").authenticated()//所有/wql/**的请求必须认证通过
                .anyRequest().permitAll()//除了/wql/))其他请求可以访问
                .and()
                .formLogin()//允许表单登录
                .successForwardUrl("/login-success");//自定义登录成功的页面地址
    }
}

用户信息服务包括两种:

  • InMemoryUserDetailsManager:基于内存的
  • JdbcUserDetailsManager:基于数据库的

提供InMemoryUserDetailsManager创建了两个用户,并设置了权限

② 在config中,需要通过HttpSecurity设置安全拦截规则,其中包括以下内容

修改SpringApplicationInitalizer的getRootConfigClasses()方法,添加WebSecurityConfig.class

//指定rootContext的配置类
protected Class<?>[] getRootConfigClasses() {
    return new Class[]{applicationConfig.class, WebSecurityConfig.class};
}

③ 默认根路径请求

WebConfig.java中添加默认请求根路径跳转到/login,此url为spring security提供:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController( "/").setViewName("redirect:/login");
}

Spring Security默认提供登录页面

2.2.2 Spring Security初始化

Spring Security初始化有两种方式:

  • 若当前环境没有使用Spring或SpringMVC,则需要将WebSecurityConfig(Spring Security配置类)传入超类,以确保获取配置,并创建Spring Context
  • 相反,若当前环境已经使用spring,我们应该在现有的springContext中注册spring security(上一步已经做将WebSecurityConfig加载至rootcontext),此方法可以什么都不做

在init包下定义SpringSecurityApplicationInitalizer:

public class SpringSecurityApplicationInitalizer extends AbstractSecurityWebApplicationInitializer {
    
    public SpringSecurityApplicationInitalizer(){
    //super(WebSecurityConfig.class);
    }
}

2.2.3 认证成功后的页面

在安全配置中,认证成功将跳转到/login-success,代码如下:

@RestController
public class LoginController {

    @RequestMapping(value = "/login-success",produces = "text/plain;charset=UTF-8")
    public String success(){
        return "登录成功";
    }
}

测试:

2.3 SpringSecurity授权功能

实现授权需要对用户的访问进行拦截效验,效验用户的权限是否可以操作指定的资源,Spring Security默认提供授权的方法

① 在controller中新建两个资源(/wql/t1和/wql/t2)

@RestController
public class LoginController {

    @RequestMapping(value = "/wql/t1",produces = "text/plain;charset=UTF-8")
    public String t1(){
        return "访问t1资源成功!";
    }
    @RequestMapping(value = "/wql/t2",produces = "text/plain;charset=UTF-8")
    public String t2(){
        return "访问t2资源成功!";
    }
}

② 

  • 配置用户信息,添加两个用户并赋予权限
  • 安全拦截配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    //1,定义用户信息服务
    @Bean
    public UserDetailsService userDetailsService(){


        //基于内存的用户信息服务
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("lishi").password("123").authorities("a1").build());
        manager.createUser(User.withUsername("wangwu").password("123").authorities("a2").build());
        return manager;
    }

    //2,密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        //不需要对密码进行编码
        return NoOpPasswordEncoder.getInstance();
    }

    //3,安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/wql/t1").hasAuthority("a1")//访问/wql/t1必须要有a1权限
                .antMatchers("/wql/t2").hasAuthority("a2")//访问/wql/t2必须要有a2权限
                .antMatchers("/wql/**").authenticated()//所有/wql/**的请求必须认证通过
                .anyRequest().permitAll()//除了/wql/))其他请求可以访问
                .and()
                .formLogin()//允许表单登录
                .successForwardUrl("/login-success");//自定义登录成功的页面地址
    }
}

测试:

3. SpringSecurity集成SpringBoot

创建一个SpringBoot工程

3.1 导入maven依赖

<!--SpringBoot父工程-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0</version>
</parent>

<dependencies>
    <!--web场景启动器,不需要声明版本,所有启动器的版本号和父工程一样-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--security场景启动器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

3.2 配置

3.2.1 Spring容器配置

SpringBoot工程启动会自动扫描启动类所在包下的所有Bean,加载到spring容器

① Spring Boot配置文件

在resource下添加application.properties

server.port=8080
server.servlet.context-path=/security-springboot
spring.application.name=security-springboot

② Spring Boot启动类

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

3.2.2 Servlet Context配置

由于Spring boot starter自动装配机制,这里无需使用@EnableWebMvc与@ComponentScan

@Configuration
public class WebConfig implements WebMvcConfigurer {

    //默认URL根据跳转到/login,此url为spring security提供
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/login");
    }
}

视图解析器配置在application.properties中(使用thymenaf不用配置)

spring.mvc.view.prefix=/WEB-INF/views
spring.mvc.view.suffix=.jsp

测试访问:


路漫漫其修远兮,吾将上下而求索