spring-security入门demo(二),用户名、密码、角色查询数据库获得

本文主要是介绍spring-security入门demo(二),用户名、密码、角色查询数据库获得,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

			上一篇中,我们通过编程的方式,在代码中写死了用户名、密码等信息,这种方式在实际使用中是很不方便的,那么如何关联上mysql查询用户名、密码呢?这章我们就来说说这个问题

1.准备工作

1.1.创建数据库、表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for t_account
-- ----------------------------
DROP TABLE IF EXISTS `t_account`;
CREATE TABLE `t_account`  (`id` int(0) NOT NULL AUTO_INCREMENT,`account` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,`password` char(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,`role_id` int(0) NOT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of t_account  插入两条记录,密码都是123456
-- ----------------------------
INSERT INTO `t_account` VALUES (1, 'test1', 'e10adc3949ba59abbe56e057f20f883e', 1);
INSERT INTO `t_account` VALUES (2, 'why', 'e10adc3949ba59abbe56e057f20f883e', 2);-- ----------------------------
-- Table structure for t_role
-- ----------------------------
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role`  (`id` int(0) NOT NULL,`role_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`role_desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_role 插入两个角色用于测试
-- ----------------------------
INSERT INTO `t_role` VALUES (1, '省级管理员', '省级管理员');
INSERT INTO `t_role` VALUES (2, '普通管理员', '普通管理员');

1.2.准备相应的jar包

mysql 驱动包
druid 数据库连接池包
spring-boot 依赖包
spring-security 依赖包
spring-web 依赖包
fastjson 依赖包
--- 这些jar 我们将通过maven工具导入

2.具体操作

2.1目录结构

在这里插入图片描述

2.1编写pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.nxt.hy</groupId><artifactId>springsecuritytest03</artifactId><version>0.0.1-SNAPSHOT</version><name>springsecuritytest03</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- 阿里数据库连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.6</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><!-- 阿里JSON解析器 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

2.2 编写配置文件yml,主要是数据库连接配置

mybatis:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
spring:datasource:name: druidtype: com.alibaba.druid.pool.DruidDataSourcedruid:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/springtest?useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456

2.3 编写核心配置类

package com.nxt.hy.springsecuritytest03.config;import com.nxt.hy.springsecuritytest03.auth.MyAuthenticationProvider;
import com.nxt.hy.springsecuritytest03.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;/*** @author wang'hai'yang* @Description:* @date 2022/2/1610:01*/
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredMyUserDetailService userDetailsService;@AutowiredMyAuthenticationProvider authenticationProvider;@Beanpublic PasswordEncoder passwordEncoder(){//暂时不加密,要加密的话,可以return new BCryptPasswordEncoder();return NoOpPasswordEncoder.getInstance();}@Overridepublic void configure(WebSecurity web) throws Exception {//放行静态资源web.ignoring().antMatchers("/js/**", "/css/**","/images/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests()  //允许基于使用HttpServletRequest限制访问//所有请求都需要认证.anyRequest().authenticated().and()//表单登录.formLogin()//登录页面和处理接口.loginPage("/login.html")
//                .loginProcessingUrl("/login")
//                认证成功处理地址.successForwardUrl("/login/index.html")
//                认证失败处理地址.failureForwardUrl("/login/error.html").permitAll().and()//关闭跨站请求伪造的防护,这里是为了前期开发方便.csrf().disable();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        设置用户名 、角色 查询逻辑auth.userDetailsService(userDetailsService);
//        设置自定义校验逻辑auth.authenticationProvider(authenticationProvider);}
}

2.4 编写认证处理类

package com.nxt.hy.springsecuritytest03.auth;import com.nxt.hy.springsecuritytest03.service.MyUserDetailService;
import com.nxt.hy.springsecuritytest03.sign.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;/*** @author wang'hai'yang* @Description:认证是由 AuthenticationManager 来管理的,但是真正进行认证的是 AuthenticationManager 中定义的 AuthenticationProvider。AuthenticationManager 中可以定义有多个 AuthenticationProvider。当我们使用 authentication-provider 元素来定义一个 AuthenticationProvider 时,如果没有指定对应关联的 AuthenticationProvider 对象,Spring Security 默认会使用 DaoAuthenticationProvider。DaoAuthenticationProvider 在进行认证的时候需要一个 UserDetailsService 来获取用户的信息 UserDetails,其中包括用户名、密码和所拥有的权限等。所以如果我们需要改变认证的方式,我们可以实现自己的 AuthenticationProvider;如果需要改变认证的用户信息来源,我们可以实现 UserDetailsService。实现了自己的 AuthenticationProvider 之后,我们可以在配置文件中这样配置来使用我们自己的 AuthenticationProvider。其中 MyAuthenticationProvider  就是我们自己的 AuthenticationProvider 实现类对应的 bean。* @date 2022/2/1917:10*/
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {@AutowiredMyUserDetailService userDetailsService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = authentication.getCredentials().toString();UserDetails userDetails = userDetailsService.loadUserByUsername(username);if(MD5.md5(password).equals(userDetails.getPassword())){return new UsernamePasswordAuthenticationToken(username,password,userDetails.getAuthorities());}return null;}/*** description: 要保证这个方法返回true* @author:  wang'hai'yang* @param:      * @return:  * @date:    2022/2/19 17:29*/@Overridepublic boolean supports(Class<?> authentication) {return UsernamePasswordAuthenticationToken.class.equals(authentication);}
}

2.5 编写用户信息处理类

package com.nxt.hy.springsecuritytest03.service;import com.nxt.hy.springsecuritytest03.domain.Role;
import com.nxt.hy.springsecuritytest03.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;/*** @author wang'hai'yang* @Description: DaoAuthenticationProvider 在进行认证的时候需要一个 UserDetailsService 来获取用户的信息 UserDetails,其中包括用户名、密码和所拥有的权限等* @date 2022/2/1915:01*/
@Service
public class MyUserDetailService implements UserDetailsService {@AutowiredRoleMapper roleMapper;@AutowiredUserMapper userMapper;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User loginUser = userMapper.selectUserByAccount(username);System.out.println(loginUser.getUsername() +" : username");List<Role> roles = roleMapper.getRolesByUsername(username);List<GrantedAuthority> authorities = new ArrayList<>();for (int i = 0; i < roles.size(); i++) {authorities.add(new SimpleGrantedAuthority("ROLE_"+roles.get(i).getName()));}loginUser.setAuthorities(authorities);return loginUser;}
}

2.6 编写查询Mapper接口

package com.nxt.hy.springsecuritytest03.service;import com.nxt.hy.springsecuritytest03.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;/*** @author wang'hai'yang* @Description:* @date 2022/2/816:36*/
@Mapper
public interface UserMapper {@Select("select id ,account username ,password from t_account where account = #{account}")public User selectUserByAccount(String account);@Select("select id ,account username ,password from t_account where account = #{account} and password =#{password}")public User selectUserByPassword(String account, String password);
}package com.nxt.hy.springsecuritytest03.service;import com.nxt.hy.springsecuritytest03.domain.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;import java.util.List;/*** @author wang'hai'yang* @Description:* @date 2022/2/1915:36*/
@Mapper
public interface RoleMapper {@Select("select r.role_name,r.id from t_role  r,t_account a where r.id = a.role_id and account = #{username}")List<Role> getRolesByUsername(@Param("username") String username);}

2.7 编写认证成功或者失败处理URL

package com.nxt.hy.springsecuritytest03.controller;import com.nxt.hy.springsecuritytest03.utils.Message;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author wang'hai'yang* @Description:* @date 2022/1/1915:14*/
@RestController
public class LoginController {/*** description: 认证成功处理逻辑* @author:  wang'hai'yang* @param:      * @return:  * @date:    2022/2/22 11:32*/@RequestMapping("/login/index.html")public String index(){return Message.success();}/*** description:  认证失败处理逻辑* @author:  wang'hai'yang* @param:      * @return:  * @date:    2022/2/22 11:32*/@RequestMapping("/login/error.html")public String error(){return Message.error();}
}

2.7 启动类

package com.nxt.hy.springsecuritytest03;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Springsecuritytest03Application {public static void main(String[] args) {SpringApplication.run(Springsecuritytest03Application.class, args);}}

2.8 大功告成

运行启动类,访问 http://localhost:8080/login.html,显示如图
在这里插入图片描述
输入用户名test1,密码123456,显示如图:
在这里插入图片描述

这篇关于spring-security入门demo(二),用户名、密码、角色查询数据库获得的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/697727

相关文章

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.