SpringSecurity从数据库中获取用户信息进行验证的案例详解

基于 SpringBoot与SpringSecurity整合案例的修改:

数据库 user 表

注,密码是由 BCrypt 算法加密对应用户名所得。

root	$2a$10$uzHVooZlCWBkaGScKnpha.ZrK31NI89flKkSuTcKYjdc5ihTPtPyq
blu		$2a$10$mI0TRIcNF4mg34JmH6T1KeystzTWDzWFNL5LQmmlz.fHndcwYHZGe
kaka	$2a$10$/GMSSJ3AzeeBK3rBC4t8BOZ5zkfb38IlwlQl.6mYTEpf22r/cCZ1a
admin	$2a$10$FKf/V.0WdHnTNWHDTtPLJe2gBxTI6TBVyFjloXG9IuH4tjebOTqcS


数据库 role 表

注:role名称必须带上前缀 ROLE_ (SpringSecurity框架要求)



role_user 表



实体类 SysUser

@Data
public class SysUser {

	private Integer id;
	private String name;
	private String password;
}

实体类 SysRole

@Data
public class SysRole {
	private Integer id;
	private String name;
}


UserMapper

public interface UserMapper {

	@Select("select * from user where name = #{name}")
	SysUser loadUserByUsername(String name);

}

RoleMapper

public interface RoleMapper {

	@Select("SELECT role.`name` FROM role WHERE role.id in (SELECT role_id FROM "
			+ " role_user as r_s JOIN `user` as u ON r_s.user_id = u.id and u.id = #{id})")
	List<SysRole> findRoleByUserId(int id);

}

UserService 接口

该接口需继承UserDetailsService

package com.blu.service;

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

public interface UserService extends UserDetailsService {

}

UserServiceImpl 实现类

package com.blu.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.blu.entity.SysRole;
import com.blu.entity.SysUser;
import com.blu.mapper.LoginMapper;
import com.blu.mapper.UserMapper;
import com.blu.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		try {
			SysUser sysUser = userMapper.loadUserByUsername(username);
			if(sysUser==null) {
				return null;
			}
			List<SimpleGrantedAuthority> authorities = new ArrayList<>();
			List<SysRole> list = roleMapper.findRoleByUserId(sysUser.getId());
			for(SysRole role : list) {
				authorities.add(new SimpleGrantedAuthority(role.getName()));
			}
			//封装 SpringSecurity 需要的UserDetails 对象并返回
			UserDetails userDetails = new User(sysUser.getName(),sysUser.getPassword(),authorities);
			return userDetails;
		} catch (Exception e) {
			e.printStackTrace();
			//返回null即表示认证失败
			return null;
		}
	}

}

加密类

@Bean
public BCryptPasswordEncoder bcryptPasswordEncoder(){
	return new BCryptPasswordEncoder();
}

SpringSecurity 配置类

package com.blu.config;

import org.springframework.beans.factory.annotation.Autowired;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.blu.service.impl.UserServiceImpl;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private UserServiceImpl userServiceImpl;
	@Autowired
	private BCryptPasswordEncoder bcryptPasswordEncoder;

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		http.authorizeRequests()
			.antMatchers("/").permitAll()
			.antMatchers("/level1/**").hasRole("vip1")
			.antMatchers("/level2/**").hasRole("vip2")
			.antMatchers("/level3/**").hasRole("vip3");

		http.formLogin().loginPage("/tologin")
						.usernameParameter("name")
						.passwordParameter("password")
						.loginProcessingUrl("/login");
		http.csrf().disable();
		http.logout().logoutSuccessUrl("/");
		http.rememberMe().rememberMeParameter("remember");

	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userServiceImpl).passwordEncoder(bcryptPasswordEncoder);
	}

}


以上方式在认证时是将数据库中查出的用户信息通过 UserServiceImpl 封装成 UserDetails 交给 SpringSecurity去认证的,我们还可以让用户实体类直接实现UserDetails:

MyUser:

package com.blu.entity;

import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class MyUser implements UserDetails {

	@Data
	private Integer id;
	private String name;
	private String password;
	private List<MyRole> roles;

	@JsonIgnore
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {

		return roles;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@JsonIgnore
	@Override
	public String getUsername() {
		return name;
	}

	@JsonIgnore
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@JsonIgnore
	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@JsonIgnore
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@JsonIgnore
	@Override
	public boolean isEnabled() {
		return true;
	}

}

MyRole:

package com.blu.entity;

import org.springframework.security.core.GrantedAuthority;
import com.fasterxml.jackson.annotation.JsonIgnore;

@Data
public class MyRole implements GrantedAuthority {

	private Integer id;
	private String name;

	@JsonIgnore
	@Override
	public String getAuthority() {
		return name;
	}

}

MyUserMapper:

package com.blu.mapper;

import com.blu.entity.MyUser;

public interface MyUserMapper {

	MyUser findByName(String name);

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.blu.mapper.MyUserMapper">
	<resultMap type="com.blu.entity.MyUser" id="myUserMap">
		<id column="uid" property="id"></id>
		<result column="uname" property="name"></result>
		<result column="password" property="password"></result>
		<collection property="roles" ofType="com.blu.entity.MyRole">
			<id column="rid" property="id" />
			<result column="rname" property="name" />
		</collection>
	</resultMap>

	<select id="findByName" parameterType="String"
		resultMap="myUserMap">
		select u.id uid,u.name uname,u.password,r.id rid,r.name rname
		from user u,role r,role_user ur
		where u.name = #{name} and ur.user_id = u.id and ur.role_id = r.id
	</select>
</mapper>

修改:UserServiceImpl:

package com.blu.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.blu.entity.MyUser;
import com.blu.mapper.MyUserMapper;
import com.blu.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private MyUserMapper myUserMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		MyUser myUser = myUserMapper.findByName(username);
		return myUser;
	}

}

到此这篇关于SpringSecurity从数据库中获取用户信息进行验证的文章就介绍到这了,更多相关SpringSecurity数据库获取用户信息验证内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringBoot + SpringSecurity 短信验证码登录功能实现

    实现原理 在之前的文章中,我们介绍了普通的帐号密码登录的方式: SpringBoot + Spring Security 基本使用及个性化登录配置. 但是现在还有一种常见的方式,就是直接通过手机短信验证码登录,这里就需要自己来做一些额外的工作了. 对SpringSecurity认证流程详解有一定了解的都知道,在帐号密码认证的过程中,涉及到了以下几个类:UsernamePasswordAuthenticationFilter(用于请求参数获取),UsernamePasswordAuthentica

  • SpringBoot结合SpringSecurity实现图形验证码功能

    本文介绍了SpringBoot结合SpringSecurity实现图形验证码功能,分享给大家,具体如下: 生成图形验证码 根据随机数生成图片 将随机数存到Session中 将生成的图片写到接口的响应中 生成图形验证码的过程比较简单,和SpringSecurity也没有什么关系.所以就直接贴出代码了 根据随机数生成图片 /** * 生成图形验证码 * @param request * @return */ private ImageCode generate(ServletWebRequest r

  • 解析SpringSecurity自定义登录验证成功与失败的结果处理问题

    一.需要自定义登录结果的场景 在我之前的文章中,做过登录验证流程的源码解析.其中比较重要的就是 当我们登录成功的时候,是由AuthenticationSuccessHandler进行登录结果处理,默认跳转到defaultSuccessUrl配置的路径对应的资源页面(一般是首页index.html). 当我们登录失败的时候,是由AuthenticationfailureHandler进行登录结果处理,默认跳转到failureUrl配置的路径对应的资源页面(一般是登录页login.html). 但是

  • 一篇文章带你搞定 springsecurity基于数据库的认证(springsecurity整合mybatis)

    一.前期配置 1. 加入依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> &

  • SpringSecurity从数据库中获取用户信息进行验证的案例详解

    基于 SpringBoot与SpringSecurity整合案例的修改: 数据库 user 表 注,密码是由 BCrypt 算法加密对应用户名所得. root $2a$10$uzHVooZlCWBkaGScKnpha.ZrK31NI89flKkSuTcKYjdc5ihTPtPyq blu $2a$10$mI0TRIcNF4mg34JmH6T1KeystzTWDzWFNL5LQmmlz.fHndcwYHZGe kaka $2a$10$/GMSSJ3AzeeBK3rBC4t8BOZ5zkfb38Il

  • 微信小程序获取用户信息并保存登录状态详解

    前言 微信小程序的运行环境不是在浏览器下运行的.所以不能以cookie来维护登录态.下面我就来说说我根据官方给出的方法来写出的维护登录态的方法吧. 一.登录态维护 官方的文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html#wxloginobject 通过 wx.login() 获取到用户登录态之后,需要维护登录态.开发者要注意不应该直接把 session_key.openid 等字段作为用户的标识或者 session

  • 小程序获取用户信息的两种方法详解(getUserProfile和头像昵称填写)

    目录 第一种使用 getUserProfile 第二种使用 头像昵称填写 总结 相信大家之前也经常使用open-data获取用户的头像和昵称吧,但微信的这个改编意味着我们要使用新的方法获取信息了.在讨论区引发了很大的讨论,接下来我们一起尝试两种获取信息的方法. 第一种使用 getUserProfile 我们可以查看一下官方文档 wx.getUserProfile(Object object),获取用户信息.页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都

  • Java获取用户IP属地模拟抖音详解

    目录 介绍 内置的三种查询算法 ip2region安装 介绍 细心的小伙伴可能会发现,抖音新上线了IP属地的功能,小伙伴在发表动态.发表评论以及聊天的时候,都会显示自己的IP属地信息 下面,我就来讲讲,Java中是如何获取IP属地的,主要分为以下几步 通过 HttpServletRequest 对象,获取用户的IP地址 通过 IP 地址,获取对应的省份.城市 首先需要写一个IP获取的工具类,因为每一次用户的Request请求,都会携带上请求的IP地址放到请求头中. public class Ip

  • JS中获取 DOM 元素的绝对位置实例详解

    在操作页面滚动和动画时经常会获取 DOM 元素的绝对位置,例如 本文 左侧的悬浮导航,当页面滚动到它以前会正常地渲染到文档流中,当页面滚动超过了它的位置,就会始终悬浮在左侧. 本文会详述各种获取 DOM 元素绝对位置 的方法以及对应的兼容性.关于如何获取 DOM 元素高度和滚动高度,请参考视口的宽高与滚动高度 一文. 概述 这些是本文涉及的 API 对应的文档和标准,供查阅: API 用途 文档 标准 offsetTop 相对定位容器的位置 MDN CSSOM View Module clien

  • SpringBoot之自定义Filter获取请求参数与响应结果案例详解

    一个系统上线,肯定会或多或少的存在异常情况.为了更快更好的排雷,记录请求参数和响应结果是非常必要的.所以,Nginx 和 Tomcat 之类的 web 服务器,都提供了访问日志,可以帮助我们记录一些请求信息. 本文是在我们的应用中,定义一个Filter来实现记录请求参数和响应结果的功能. 有一定经验的都知道,如果我们在Filter中读取了HttpServletRequest或者HttpServletResponse的流,就没有办法再次读取了,这样就会造成请求异常.所以,我们需要借助 Spring

  • Java SpringBoot在RequestBody中高效的使用枚举参数原理案例详解

    在优雅的使用枚举参数(原理篇)中我们聊过,Spring对于不同的参数形式,会采用不同的处理类处理参数,这种形式,有些类似于策略模式.将针对不同参数形式的处理逻辑,拆分到不同处理类中,减少耦合和各种if-else逻辑.本文就来扒一扒,RequestBody参数中使用枚举参数的原理. 找入口 对 Spring 有一定基础的同学一定知道,请求入口是DispatcherServlet,所有的请求最终都会落到doDispatch方法中的ha.handle(processedRequest, respons

  • Python中read,readline和readlines的区别案例详解

    python中有神奇的三种读操作:read.readline和readlines read()  : 一次性读取整个文件内容.推荐使用read(size)方法,size越大运行时间越长 readline()  :每次读取一行内容.内存不够时使用,一般不太用 readlines()   :一次性读取整个文件内容,并按行返回到list,方便我们遍历 一般小文件我们都采用read(),不确定大小你就定个size,大文件就用readlines() 1)我们先用read来完整读取一个小文件,代码如下: f

  • Laravel框架用户登陆身份验证实现方法详解

    本文实例讲述了Laravel框架用户登陆身份验证实现方法.分享给大家供大家参考,具体如下: laravel中检测用户是否登录,有以下的代码: if ( !Auth::guest() ) { return Redirect::to('/dashboard'); } 那Auth::guest是如何调用的呢? laravel用了Facade模式,相关门面类在laravel/framework/src/Illuminate/Support/Facades文件夹定义的,看下Auth类的定义: class

  • ASP.NET中获取URL重写前的原始地址详解

    通常的使用场景是当我们有某个页面需要用户登录才能访问时,我们会在代码中判断当前访问用户是否登录,如果未登录,则重定向至登录页面,并将当前网址通过Url参数传递给登录页面.如果使用了URL重写,并通过Request.Url.AbsoluteUri获取当前网址,用户登录后打开的就是重写后的地址,这虽然不影响正常使用,但从用户体验及URL统一的角度,我们更希望是重写前的地址. 之前,我们在开发中也被这个问题困扰,只能尽量通过js重定向至登录页面(通过location.href获取当前网址)或者在代码中

随机推荐