SpringSecurity的初次邂逅

1.Spring Security概念

Spring Security是Spring采用 AOP思想,基于 servlet过滤器实现的安全框架。它提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是用于保护基于Spring的应用程序的事实上的标准。

Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权。像所有Spring项目一样,Spring Security的真正强大之处在于它可以轻松扩展以满足定制需求的能力。

特征

1.2 快速入门案例

1.2.1 环境准备

准备一个SpringMVC+Spring+jsp的Web环境,然后在这个基础上整合SpringSecurity。

首先创建Web项目

添加相关的依赖



junit
junit
4.11
test


org.springframework
spring-webmvc
5.2.1.RELEASE


javax.servlet
servlet-api
2.5
provided


org.slf4j
slf4j-log4j12
1.7.25

添加相关的配置文件

Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
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
http://www.springframework.org/schema/context/spring-context.xsd">

SpringMVC配置文件

<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/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">


log4j.properties文件

log4j.rootCategory=INFO, stdout

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

web.xml

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

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">
Archetype Created Web Application



contextConfigLocation
classpath:applicationContext.xml


org.springframework.web.context.ContextLoaderListener




CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter

encoding
utf-8



CharacterEncodingFilter
/*



dispatcherServletb
org.springframework.web.servlet.DispatcherServlet


contextConfigLocation
classpath:spring-mvc.xml

1


dispatcherServletb

/


添加Tomcat的插件 启动测试



org.apache.tomcat.maven
tomcat7-maven-plugin
2.2

8082
/


1.2.2 整合SpringSecurity

添加相关的依赖

spring-security-core.jar 核心包,任何SpringSecurity的功能都需要此包

spring-security-web.jar:web工程必备,包含过滤器和相关的web安全的基础结构代码

spring-security-config.jar:用于xml文件解析处理

spring-security-tablibs.jar:动态标签库



org.springframework.security
spring-security-config
5.1.5.RELEASE


org.springframework.security
spring-security-taglibs
5.1.5.RELEASE

web.xml文件中配置SpringSecurity



springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy


springSecurityFilterChain
/*

添加SpringSecurity的配置文件

<?xml version="1.0" encoding="UTF-8"?>
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">

















将SpringSecurity的配置文件引入到Spring中

启动测试访问

2. 认证操作

2.1 自定义登录页面

<%--
Created by IntelliJ IDEA.
User: dpb
Date: 2021/3/16
Time: 16:57
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


Title


登录页面




修改相关的配置文件

<?xml version="1.0" encoding="UTF-8"?>
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">









login-processing-url="/login"
default-target-url="/home.jsp"
authentication-failure-url="/error.jsp"
/>

logout-success-url="/login.jsp" />












访问home.jsp页面后会自动跳转到自定义的登录页面,说明这个需求是实现了

但是当我们提交了请求后页面出现了如下的错误

2.2 关闭CSRF拦截

为什么系统默认的登录页面提交没有CRSF拦截的问题呢

我自定义的认证页面没有这个信息怎么办呢?两种方式:

关闭CSRF拦截

登录成功~

使用CSRF防护

在页面中添加对应taglib

我们访问登录页面

登录成功

2.3 数据库认证

  前面的案例我们的账号信息是直接写在配置文件中的,这显然是不太好的,我们来介绍小如何实现和数据库中的信息进行认证

添加相关的依赖


org.mybatis
mybatis
3.5.4


org.mybatis
mybatis-spring
2.0.4


mysql
mysql-connector-java
8.0.11


com.alibaba
druid
1.1.8

添加配置文件

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

<?xml version="1.0" encoding="UTF-8"?>
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
http://www.springframework.org/schema/context/spring-context.xsd">






















需要完成认证的service中继承 UserDetailsService父接口

实现类中实现验证方法

package com.bobo.service.impl;

import com.bobo.mapper.UserMapper;
import com.bobo.pojo.User;
import com.bobo.pojo.UserExample;
import com.bobo.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 users = mapper.selectByExample(example);
if(users != null && users.size() > 0){
User user = users.get(0);
if(user != null){
List 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;
}
}

最后修改配置文件关联我们自定义的service即可

2.4 加密

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

首先生成秘闻

修改配置文件

去掉 {noop}

2.5 认证状态

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

我们可以在用户的表结构中添加相关的字段来维护这种关系

2.6 记住我

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

在SpringSecurity中默认是关闭 RememberMe功能的,我们需要放开

这样就配置好了。

记住我的功能会方便大家的使用,但是安全性却是令人担忧的,因为Cookie信息存储在客户端很容易被盗取,这时我们可以将这些数据持久化到数据库中。

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

注意设置了过期时间,到期后并不是删除表结构中的数据,而是客户端不会在携带相关信息了,同时删除掉数据库中的数据 记住我也会失效

3. 授权

3.1 注解使用

开启注解的支持

<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/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
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">






jsr250-annotations="enabled"
pre-post-annotations="enabled"
secured-annotations="enabled"
/>

jsr250的使用

添加依赖


javax.annotation
jsr250-api
1.0

控制器中通过注解设置

package com.bobo.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";
}

@RequestMapping("/update")
public String update(){
System.out.println("用户更新....");
return "/home.jsp";
}
}

Spring表达式的使用

package com.bobo.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";
}

@RequestMapping("/update")
public String update(){
System.out.println("用户更新....");
return "/home.jsp";
}
}

SpringSecurity提供的注解

package com.bobo.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";
}

@RequestMapping("/update")
public String update(){
System.out.println("用户更新....");
return "/home.jsp";
}
}

异常处理

新增一个错误页面,然后在SpringSecurity的配置文件中配置即可

当然你也可以使用前面介绍的SpringMVC中的各种异常处理器处理

3.2 标签使用

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

添加SpringSecurity的标签库

<%--
Created by IntelliJ IDEA.
User: dpb
Date: 2021/3/16
Time: 17:02
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>


Title


欢迎光临...




用户查询



用户添加



用户更新



用户删除



页面效果

展开阅读全文

页面更新:2024-05-19

标签:注解   账号   框架   权限   结构   页面   标签   功能   用户   信息

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top