记录SSM项目集成Spring Security 4.X版本 之 加密验证和记住我功能

目录

前言

一、用户登录密码加密认证

二、记住我功能


前言

本次笔记的记录是接SSM项目集成Spring Security 4.X版本 之 加入DWZ,J-UI框架实现登录和主页菜单显示-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/u011529483/article/details/136255768?spm=1001.2014.3001.5502

文章之后补全spring-security登录时用户认证进行密码加密验证和实现记住我功能。


一、用户登录密码加密认证

1. 修改上一篇文章中的项目wqdemotwo的spring-security.xml配置文件

打开如下标红的两处配置:

什么意思呢?

<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean> 是在配置文件中声明一个bean,实现BCryptPasswordEncoder类。

<security:password-encoder ref="passwordEncoder"/> 是将声明的bean “passwordEncoder” 注入到 authentication-provider 中去。对应的 AuthenticationProvider 类是认证提供者。此处指定了myUserDetailsService 服务类(获取用户详情,如 用户名,密码等)

2. 生成加密后的密码,实现登录认证

进入加密算法实现类:BCryptPasswordEncoder

进入接口:PasswordEncoder

encode()方法对明文密码进行加密。我们调用这个方法对数据库中的密码进行加密:

此处我随意找一个类生成加密密码:就 LoginController 类吧

运行项目生成加密密码:$2a$10$n/q4O15Lg9d1WvelfRu9i.qrgE5iVjTeD4.hXAqsLZaGRmTKoGxtK录入到数据库中。

完成,现在重新启动项目查看登录效果:用户:zhangsan,密码:123456

系统登录成功:

执行loadUserByUsername查询用户详情方法后,后台打印结果,密码加密了。

3. 补充说明

总结一下:整个登录认证过程中我们并没有做密码的对比校验,但是密码输入错误是无法登录认证成功的。这是因为密码比对交由 SpringSecurity 处理了,登录页面传入 用户名 通过详情查询方法loadUserByUsername 获取了UserDetails(得到了数据库中的用户名和密码)然后返回给了SpringSecurity 进行密码校验。

spring-security.xml 配置文件中注入了AuthenticationManager 身份验证管理器类,AuthenticationProvider认证提供者类,PasswordEncoder接口的实现类等。执行时会执行一系列相关类(源码就不研究了,有情怀的小伙伴可以试试)。最终完成用户登录认证。而 密码的校验是由BCryptPasswordEncoder类 通过实现PasswordEncoder接口 的matches方法来完成

我们可以来验证一下。将数据库中用户zhangsan的密码改回明文123456。此时运行项目进行登录,结果是登录失败了:

后台打印数据库获取的密码是123456明文,小伙伴注意到下图最后一行的红字。

BCryptPasswordEncoder.matches Encoded password does not look like BCrypt:什么意思呢?就是BCryptPasswordEncode类的matches方法中报出了 密码不属于自己(BCrypt)的编码格式,下图:

matches方法中如果通过了编码格式校验则进入checkpw(rawPassword.toString(), encodedPassword)方法,rawPassword登录页面传入的,encodedPassword数据库中存储的。所以密码的校验是由BCryptPasswordEncoder类 通过实现PasswordEncoder接口 的matches方法来完成

二、记住我功能

1. 将上篇文章项目wqdemotwo的spring-security.xml配置文件,打开如下两处配置

说明:token-validity-seconds="300" 属性指定免登录访问资源的维持时间,超过这个时间没有任何资源请求,便需要重新登录。

注意:第一次运行项目时要将<!--<property name="createTableOnStartup" value="true"/>--> 配置打开,createTableOnStartup属性是当项目启动时,springSecurity创建表存储remember me相关信息,第二次启动时要注释这个属性。

​​​​说明:<property name="dataSource" ref="dataSource"/>指定数据库数据源,如oracle。ref="dataSource"注入的是applicationContext.xml配置文件中的数据源,如下图:

2. 修改登录页面

增加 记住我 复选框,如图:

到此记住我功能配置完成,打开spring-security.xml文件的createTableOnStartup属性运行项目,按预期设想应该在数据库生成表PERSISTENT_LOGINS:

-- Create table
create table PERSISTENT_LOGINS
(
  username  VARCHAR2(64) not null,
  series    VARCHAR2(64) not null,
  token     VARCHAR2(64) not null,
  last_used TIMESTAMP(6) not null
);
-- Create/Recreate primary, unique and foreign key constraints 
alter table PERSISTENT_LOGINS
  add primary key (SERIES)

登录页面选择 记住我 登录成功后,关闭浏览器可以实现免登录再次访问资源。

选择 记住我 进行登录,成功登录了。此时我打开oracle数据库生成了PERSISTENT_LOGINS表

页面也成功访问到资源:

此时关闭浏览器,再次打开浏览器因该可以不用登录就可以直接访问主页面。但是我的想法是美好的,事实却是访问 http://localhost:8080/wqdemotwo_war/system/index 跳转到了登录页面,经过努力查找原因是:spring-security.xml文件的 <security:intercept-url pattern="/**" access="isFullyAuthenticated()"/> 配置导致,需要改成 <security:intercept-url pattern="/**" access="isAuthenticated()"/> 这个。

isAuthenticated():Returns true if the user is not anonymous(如果用户不是匿名的,则返回true)

isFullyAuthenticated(): Returns true if the user is not an anonymous or a remember-me user(如果用户不是匿名用户或记住我的用户,则返回true)

修改后再次运行项目,便可以实现 记住我 功能,即:登录成功后关闭浏览器,再次打开浏览器访问资源可以免登录访问。(记住注释掉spring-security.xml文件的<!--<property name="createTableOnStartup" value="true"/>-->属性


好了,今天的记录到此结束。

  • 24
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: SSM指的是Spring+SpringMVC+MyBatis这一组合,而Spring SecuritySpring框架中用于安全认证和授权的模块。将SSM整合Spring Security,可以在SSM应用中提供更加完善的安全控制和认证功能。 具体的实现过程包括以下几个步骤: 1. 添加Spring Security依赖:在pom.xml文件中添加Spring Security的依赖,如下所示: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.2</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.2</version> </dependency> ``` 2. 配置Spring Security:在Spring的配置文件中配置Spring Security,包括认证管理器、用户详情服务、密码加密方式、安全过滤器链等内容。 3. 编写登录页面和控制器:编写用户登录页面和控制器,用户在登录页面输入用户名和密码后,控制器将用户输入的信息交给Spring Security进行认证。 4. 配置安全规则:根据业务需求,配置安全规则,例如需要登录才能访问某些资源,或者某些资源只有特定的用户角色才能访问等。 5. 测试:启动应用,测试登录、授权等功能是否正常。 通过以上步骤,就可以将Spring Security整合到SSM应用中,提供更加完善的安全控制和认证功能。 ### 回答2: ssm整合springsecurity是指将SpringSecurity框架与SSM框架进行集成,实现对用户认证和授权的支持,保护Web应用程序中的资源。 具体来说,SSM框架中的Web应用程序可以使用SpringSecurity框架提供的安全机制,从而可以很好地保护应用程序中的敏感信息。此外,SpringSecurity还提供了一套完整的用户认证和授权框架,可以自定义实现用户登录、密码验证、用户授权等功能。 要实现SSM整合SpringSecurity,需要进行以下几个步骤: 1. 在pom.xml文件中添加spring-security-core和spring-security-config依赖,具体依赖根据项目需求而定。 2. 在Spring MVC的配置文件中添加SpringSecurity的配置信息,如用户权限的设置、HTTPS的启用以及记录用户登录日志等。 3. 在web.xml文件中添加SpringSecurity的Filter和配置信息。 4. 编写实现用户认证和授权的Java类,如自定义认证管理器、用户详细信息服务、密码加密服务等。 5. 编写安全相关的页面和控制器,如登录页面、注册页面、注销页面和授权页面等。 在SSM整合SpringSecurity的过程中,需要注意以下几点: 1. SpringSecurity框架提供了多种用户认证和授权的方式,开发者需要根据需求选择最适合的。 2. 在实现用户认证和授权的Java类中,需要注意代码的可读性、可维护性和安全性。 3. 在页面和控制器中,需要对用户输入的数据进行验证和过滤,防止SQL注入、跨站脚本攻击等安全问题。 总的来说,SSM整合SpringSecurity可以很好地提高Web应用程序的安全性,保护用户信息不被恶意攻击者利用,并且可以轻松地实现用户认证和授权等功能,为应用程序提供更好的用户体验。 ### 回答3: SSM是指SpringSpringMVC和Mybatis三个框架的整合,Spring SecuritySpring的安全框架。对于SSM整合Spring Security,可以按照以下步骤进行。 1.在Spring的配置文件中添加以下内容: ``` <!--启用Spring Security--> <security:http auto-config="true"> <security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" /> <security:intercept-url pattern="/user/**" access="ROLE_USER" /> <security:form-login login-page="/login" username-parameter="username" password-parameter="password" /> <security:logout logout-success-url="/logout" /> </security:http> <security:authentication-manager> <security:authentication-provider> <security:user-service> <security:user name="admin" password="admin123" authorities="ROLE_ADMIN" /> <security:user name="user" password="user123" authorities="ROLE_USER" /> </security:user-service> </security:authentication-provider> </security:authentication-manager> ``` 2.在SpringMVC的配置文件中添加以下内容,通过@Autowired注解将上面的bean引入: ``` <!--开启注解扫描--> <context:component-scan base-package="com.example.controller" /> <!--启用Spring Security--> <security:global-method-security pre-post-annotations="enabled" /> <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy"> <security:filter-chain-map path-type="ant"> <security:filter-chain pattern="/login" filters="authenticationProcessingFilter" /> <security:filter-chain pattern="/logout" filters="logoutFilter" /> <security:filter-chain pattern="/**" filters="basicAuthenticationFilter" /> </security:filter-chain-map> </bean> <bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManager" /> <property name="authenticationSuccessHandler"> <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/admin/index" /> </bean> </property> <property name="authenticationFailureHandler"> <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> <property name="defaultFailureUrl" value="/login?error=true" /> </bean> </property> <property name="usernameParameter" value="username" /> <property name="passwordParameter" value="password" /> </bean> <bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter"> <constructor-arg value="/login" /> <constructor-arg> <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" /> </constructor-arg> </bean> <bean id="basicAuthenticationFilter" class="org.springframework.security.web.authentication.www.BasicAuthenticationFilter"> <property name="authenticationManager" ref="authenticationManager" /> <property name="authenticationEntryPoint"> <bean class="org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint"> <property name="realmName" value="Spring Security Application" /> </bean> </property> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="com.example.service.MyUserDetailsService" /> ``` 3.在Mybatis的配置文件中,为所有需要授权的Mapper接口添加以下内容: ``` @Secured("ROLE_USER") ``` 其中ROLE_USER需要在Spring的配置文件中定义。 通过以上步骤,就可以在SSM框架中整合Spring Security实现安全认证和权限控制了。在实际开发中,还需要根据具体的业务需求和系统架构进行定制,包括自定义认证和授权方式、注销登录、记住密码、登陆超时等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值