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

相关文章

Java NoClassDefFoundError运行时错误分析解决

《JavaNoClassDefFoundError运行时错误分析解决》在Java开发中,NoClassDefFoundError是一种常见的运行时错误,它通常表明Java虚拟机在尝试加载一个类时未能... 目录前言一、问题分析二、报错原因三、解决思路检查类路径配置检查依赖库检查类文件调试类加载器问题四、常见

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推