01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作

一、SpringSecurity概念

SpringSecurity是Spring采用AOP思想,基于servlet过滤器实现的安全框架。它提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。
SpringSecurity是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的事实上的标准。
SpringSecurity是一个框架,致力于为Java应用程序提供身份验证和授权。像所有Spring项目一样,SpringSecurity的真正强大支出在于它轻松扩展以满足定制需求的能力。

特征:

  • 对身份验证和授权的全面且可扩展的支持
  • 包括免受会话固定,点击劫持,跨站点请求伪造等攻击
  • servlet Api 集成
  • 与Spring Web MVC的可选集成

二、入门案例

1.环境准备

我们准备一个SpringMVC+Spring+jsp的Web环境

1.1 创建Web项目

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第1张图片

1.2 导入依赖

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.1.6.RELEASEversion>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <scope>providedscope>
      <version>2.5version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>1.7.28version>
    dependency>

配置Tomcat

    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.mavengroupId>
        <artifactId>tomcat7-maven-pluginartifactId>
        <version>2.2version>
        <configuration>
          <port>8080port>
          <path>/path>
          <uriEncoding>utf-8uriEncoding>
        configuration>
      plugin>
    plugins>

1.3 添加相关的配置文件

1.3.1 applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd">

beans>

1.3.2 spring-mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

beans>

1.3.3 log4j.properties

log4j.rootCategory=INFO, stdout , R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n

1.3.4 web.xml

DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app  version="2.5"
          xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>Archetype Created Web Applicationdisplay-name>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
  servlet>



  <servlet-mapping>
    
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  
  
  <filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    <init-param>
      <param-name>forceRequestEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
    <init-param>
      <param-name>forceResponseEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.htmlurl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.cssurl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.jsurl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.jpgurl-pattern>
  servlet-mapping>
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.pngurl-pattern>
  servlet-mapping>


web-app>


2.整合SpringSecurity

2.1 添加相关的依赖

依赖 说明
spring-security-core.jar 核心包,然和SpringSecurity的功能都需要此包
spring-security-web.jar web工程必备,包含过滤器和相关的web安全的基础结构代码
spring-security-config.jar 用于xml文件解析处理
spring-security-tablibs.jar 动态标签库
    
    <dependency>
      <groupId>org.springframework.securitygroupId>
      <artifactId>spring-security-configartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframework.securitygroupId>
      <artifactId>spring-security-taglibsartifactId>
      <version>5.1.5.RELEASEversion>
    dependency>

2.2 web.xml配置文件中配置SpringSecurity

  
  <filter>
    <filter-name>springSecurityFilterChainfilter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
  filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChainfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

2.3 添加SpringSecurity的配置文件

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第2张图片

2.4 测试

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第3张图片

3.自定义登录页面

3.1 登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <h1>登录页面h1>
    <form action="/login" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="登录">
    form>
body>
html>

3.2 配置文件配置认证的信息


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd
">

    
    
    <security:http auto-config="true" use-expressions="true">

        
        <security:intercept-url pattern="/login.jsp" access="permitAll()"/>

        
        <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER')">security:intercept-url>

        
        <security:form-login login-page="/login.jsp"
                             login-processing-url="/login"
                             default-target-url="/home.jsp"
                             authentication-failure-url="/error.jsp"
        />

        
        <security:logout logout-url="/logout"
                         logout-success-url="/login.jsp"/>

    security:http>



    
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                
                <security:user name="zhangsan" authorities="ROLE_USER" password="{noop}123">security:user>
                <security:user name="lisi" authorities="ROLE_USER" password="{noop}123456">security:user>
            security:user-service>
        security:authentication-provider>
    security:authentication-manager>
beans>

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第4张图片

3.3 测试

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第5张图片

3.4 提交会出现403错误

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第6张图片

3.4.1 CSRF拦截

为什么系统默认的登录页面提交没有CRSF拦截的问题呢?
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第7张图片

3.5 解决403错误方法

3.5.1 方法一

关闭CSRF
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第8张图片

3.5.2 方法二

使用CSRF防护
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第9张图片

4.数据库认证

4.1 引入相关依赖

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.4version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>2.0.4version>
    dependency>
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.17version>
    dependency>
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.0.9version>
    dependency>

4.2 创建db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

4.3 在applicationContext.xml配置


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.biao.service" >context:component-scan>

    
    <import resource="classpath:spring-security.xml"/>

    <context:property-placeholder location="classpath:db.properties"/>
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>

    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.biao.mapper"/>
    bean>
beans>

4.4 需要完成认证的Service中继承UserDetailService父接口

package com.biao.service;

import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 要实现数据库验证
 * 我们自定义的Service需要继承UserDetailsService接口
 */
public interface IUserService extends UserDetailsService {

}

4.5 实现类中实现验证方法

package com.biao.service.impl;

import com.biao.mapper.UserMapper;
import com.biao.pojo.User;
import com.biao.pojo.UserExample;
import com.biao.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据账号查询用户信息
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(s);
        List<User> users = mapper.selectByExample(example);
        if (users != null && users.size() > 0){
            User user = users.get(0);
            if (user != null ){
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                //设置登录账号的角色
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                        user.getUserName(),"{noop}"+user.getPassword(),authorities
                );
                return userDetails;
            }
        }
        return null;
    }
}

4.6 最后修改SpringSecurity配置文件关联我们的service即可

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第10张图片

4.7 加密

在SpringSecurity中推荐我们是使用的加密算法是BCryptPasswordEncoder

4.7.1 首先生成密文,保存到数据库

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第11张图片

4.7.2 修改配置文件

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第12张图片
在验证信息放开,说明用什么验证
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第13张图片

4.7.3 去掉{noop}

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第14张图片

4.8 认证状态

用户的状态包括 是否可用,账号过期,凭证过期,账号锁定

有重载的方法的可以使用
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第15张图片

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第16张图片
我们可以在用户的表结构中添加相关字段来维护这种关系

5.记住我Remember me功能

5.1 在表单页面添加一个记住我的按钮

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <h1>登录页面h1>
    <form action="/login" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="checkbox" name="remember-me" value="true"> 记住我 <br>
        <security:csrfInput/>
        <input type="submit" value="登录">
    form>
body>
html>

5.2 配置文件中开启

在SpringSecurity中是默认关闭RememberMe功能的,我们需要放开
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第17张图片
记住我的功能会方便大家的使用,但是安全性却是令人担忧的,因为Cookie信息存储在客户端很容易被人盗取,这时我们可以将这些数据持久化到数据库中。

5.3 持久化记住我

5.3.1 建立一个表

CREATE TABLE `persistent_logins` (
  `username` varchar(64) NOT NULL,
  `series` varchar(64) NOT NULL,
  `token` varchar(64) NOT NULL,
  `last_used` timestamp NOT NULL,
  PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

5.3.2 修改配置文件

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第18张图片

6.授权

6.1 注解使用

6.1.1 开启注解的支持

在SpringMVC的配置文件中


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.biao.controller">context:component-scan>

    <mvc:annotation-driven/>

    
    <security:global-method-security
        jsr250-annotations="enabled"
        pre-post-annotations="enabled"
        secured-annotations="enabled"
    />
beans>

6.1.2 添加依赖

    <dependency>
      <groupId>javax.annotationgroupId>
      <artifactId>jsr250-apiartifactId>
      <version>1.0version>
    dependency>

6.1.3 控制器通过注解设置

package com.biao.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.security.RolesAllowed;

@Controller
@RequestMapping("/user")
public class UserController {

    @RolesAllowed(value = {"ROLE_ADMIN"})
    @RequestMapping("/query")
    public String query(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @RequestMapping("/save")
    public String save(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @RequestMapping("/update")
    public String update(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

}

6.1.4 测试

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第19张图片
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第20张图片

6.1.5 Spring表达式的使用

package com.biao.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.security.RolesAllowed;

@Controller
@RequestMapping("/order")
public class OrderController {

    @PreAuthorize(value = "hasAnyRole('ROLE_USER')")
    @RequestMapping("/query")
    public String query(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @PreAuthorize(value = "hasAnyRole('ROLE_ADMIN')")
    @RequestMapping("/save")
    public String save(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @PreAuthorize(value = "hasAnyRole('ROLE_USER')")
    @RequestMapping("/update")
    public String update(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

}

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第21张图片

6.1.6 SpringSecurity提供的注解

package com.biao.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.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Secured("ROLE_USER")
    @RequestMapping("/query")
    public String query(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @Secured("ROLE_ADMIN")
    @RequestMapping("/save")
    public String save(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

    @Secured("ROLE_USER")
    @RequestMapping("/update")
    public String update(){
        System.out.println("用户查询");
        return "/home.jsp";
    }

}

01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第22张图片

6.1.7 异常处理

新增一个错误页面,然后在SpringSecurity的配置文件中配置即可
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第23张图片

6.2 标签使用

前面介绍的注解的权限管理可以控制用户是否具有这个操作的权限,但是当用户具有这个权限后进入到具体的操作页面,这时我们还有进行更细粒度的控制,这时注解的方式就不太适用了,这时我们可以通过标签来处理。

<html>
<head>
    <title>主页title>
head>
<body>
    <h1>欢迎光临h1>
    <security:authentication property="principal.username"/>
    <security:authorize access="hasAnyRole('ROLE_USER')">
        <a href="#">用户查询a>
    security:authorize>
        <a href="#">用户添加a>
    <security:authorize access="hasAnyRole('ROLE_ADMIN')">
        <a href="#">用户更新a>
    security:authorize>
    <security:authorize access="hasAnyRole('ROLE_USER')">
        <a href="#">用户删除a>
    security:authorize>
body>
html>

页面效果
01.SpringSecurity基础应用——概念、整合SpringSecurity、自定义登录页面、数据库验证、Remember me、授权操作_第24张图片

你可能感兴趣的:(#,SpringSecurity)