最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringSecurity從數(shù)據(jù)庫(kù)中獲取用戶信息進(jìn)行驗(yàn)證的案例詳解

 更新時(shí)間:2021年01月26日 11:29:13   作者:BLUcoding  
這篇文章主要介紹了SpringSecurity從數(shù)據(jù)庫(kù)中獲取用戶信息進(jìn)行驗(yàn)證的案例詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

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

數(shù)據(jù)庫(kù) user 表

在這里插入圖片描述

注,密碼是由 BCrypt 算法加密對(duì)應(yīng)用戶名所得。

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

數(shù)據(jù)庫(kù) role 表

在這里插入圖片描述

注:role名稱必須帶上前綴 ROLE_ (SpringSecurity框架要求)


role_user 表

在這里插入圖片描述


實(shí)體類 SysUser

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

實(shí)體類 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 實(shí)現(xiàn)類

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 對(duì)象并返回
			UserDetails userDetails = new User(sysUser.getName(),sysUser.getPassword(),authorities);
			return userDetails;
		} catch (Exception e) {
			e.printStackTrace();
			//返回null即表示認(rèn)證失敗
			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);
	}
	
}

以上方式在認(rèn)證時(shí)是將數(shù)據(jù)庫(kù)中查出的用戶信息通過(guò) UserServiceImpl 封裝成 UserDetails 交給 SpringSecurity去認(rèn)證的,我們還可以讓用戶實(shí)體類直接實(shí)現(xiàn)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;
	}

}

到此這篇關(guān)于SpringSecurity從數(shù)據(jù)庫(kù)中獲取用戶信息進(jìn)行驗(yàn)證的文章就介紹到這了,更多相關(guān)SpringSecurity數(shù)據(jù)庫(kù)獲取用戶信息驗(yàn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決java編譯錯(cuò)誤:程序包不存在的問(wèn)題

    解決java編譯錯(cuò)誤:程序包不存在的問(wèn)題

    出錯(cuò):Error:(3, 27) java: 程序包c(diǎn)om.aliyun.odps.udf不存在,遇到這樣的錯(cuò)誤問(wèn)題如何解決呢,下面小編給大家?guī)?lái)了java編譯錯(cuò)誤:程序包不存在的問(wèn)題及解決方法,感興趣的朋友一起看看吧
    2023-05-05
  • Java的HashSet源碼詳解

    Java的HashSet源碼詳解

    這篇文章主要介紹了Java的HashSet源碼詳解,HashSet底層封裝的是HashMap,所以元素添加會(huì)放到HashMap的key中,value值使用new Object對(duì)象作為value,所以HashSet和HashMap的所具有的特點(diǎn)是類似的,需要的朋友可以參考下
    2023-09-09
  • springboot?集成identityserver4身份驗(yàn)證的過(guò)程解析

    springboot?集成identityserver4身份驗(yàn)證的過(guò)程解析

    這篇文章主要介紹了springboot?集成identityserver4身份驗(yàn)證的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-01-01
  • 如何解決java:錯(cuò)誤:無(wú)效的源發(fā)行版:17問(wèn)題

    如何解決java:錯(cuò)誤:無(wú)效的源發(fā)行版:17問(wèn)題

    這篇文章主要介紹了如何解決java:錯(cuò)誤:無(wú)效的源發(fā)行版:17問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • Mybatis的插件運(yùn)行原理及如何編寫(xiě)一個(gè)插件

    Mybatis的插件運(yùn)行原理及如何編寫(xiě)一個(gè)插件

    這篇文章主要介紹了Mybatis的插件運(yùn)行原理及如何編寫(xiě)一個(gè)插件 ,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • Druid(新版starter)在SpringBoot下的使用教程

    Druid(新版starter)在SpringBoot下的使用教程

    Druid是Java語(yǔ)言中最好的數(shù)據(jù)庫(kù)連接池,Druid能夠提供強(qiáng)大的監(jiān)控和擴(kuò)展功能,DruidDataSource支持的數(shù)據(jù)庫(kù),這篇文章主要介紹了Druid(新版starter)在SpringBoot下的使用,需要的朋友可以參考下
    2023-05-05
  • 配置了jdk的環(huán)境idea卻提示找不到j(luò)dk解決辦法

    配置了jdk的環(huán)境idea卻提示找不到j(luò)dk解決辦法

    在使用Java編程語(yǔ)言進(jìn)行開(kāi)發(fā)時(shí),IDEA是一個(gè)非常流行和強(qiáng)大的集成開(kāi)發(fā)環(huán)境,這篇文章主要給大家介紹了關(guān)于配置了jdk的環(huán)境idea卻提示找不到j(luò)dk的解決辦法,需要的朋友可以參考下
    2023-12-12
  • Eclipse配置tomcat發(fā)布路徑的問(wèn)題wtpwebapps解決辦法

    Eclipse配置tomcat發(fā)布路徑的問(wèn)題wtpwebapps解決辦法

    這篇文章主要介紹了Eclipse配置tomcat發(fā)布路徑的問(wèn)題wtpwebapps解決辦法的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • Java中Map的entrySet()使用說(shuō)明

    Java中Map的entrySet()使用說(shuō)明

    這篇文章主要介紹了Java中Map的entrySet()使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-09-09
  • springboot項(xiàng)目配置多個(gè)kafka的示例代碼

    springboot項(xiàng)目配置多個(gè)kafka的示例代碼

    這篇文章主要介紹了springboot項(xiàng)目配置多個(gè)kafka,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04

最新評(píng)論

内乡县| 安吉县| 观塘区| 枣庄市| 宜君县| 亚东县| 隆昌县| 通渭县| 克什克腾旗| 田林县| 龙里县| 务川| 灵寿县| 上栗县| 建宁县| 安泽县| 简阳市| 巫溪县| 奈曼旗| 山阴县| 砀山县| 台州市| 汪清县| 肥乡县| 克山县| 武定县| 南江县| 金门县| 康平县| 安泽县| 福海县| 甘泉县| 高要市| 五河县| 佛教| 东乡族自治县| 淳安县| 循化| 汉沽区| 昭觉县| 天台县|