利用SpringSecurity怎么從數(shù)據(jù)庫(kù)中獲取用戶(hù)信息進(jìn)行驗(yàn)證-創(chuàng)新互聯(lián)

本篇文章給大家分享的是有關(guān)利用SpringSecurity怎么從數(shù)據(jù)庫(kù)中獲取用戶(hù)信息進(jìn)行驗(yàn)證,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

創(chuàng)新互聯(lián)公司專(zhuān)注骨干網(wǎng)絡(luò)服務(wù)器租用十多年,服務(wù)更有保障!服務(wù)器租用,電信內(nèi)江機(jī)房 成都服務(wù)器租用,成都服務(wù)器托管,骨干網(wǎng)絡(luò)帶寬,享受低延遲,高速訪問(wèn)。靈活、實(shí)現(xiàn)低成本的共享或公網(wǎng)數(shù)據(jù)中心高速帶寬的專(zhuān)屬高性能服務(wù)器。

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


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


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名稱(chēng)必須帶上前綴 ROLE_ (SpringSecurity框架要求)



role_user 表

實(shí)體類(lèi) SysUser

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

實(shí)體類(lèi) 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)類(lèi)

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;
		}
	}

}

加密類(lèi)

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

SpringSecurity 配置類(lèi)

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ù)中查出的用戶(hù)信息通過(guò) UserServiceImpl 封裝成 UserDetails 交給 SpringSecurity去認(rèn)證的,我們還可以讓用戶(hù)實(shí)體類(lèi)直接實(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;
	}

}

以上就是利用SpringSecurity怎么從數(shù)據(jù)庫(kù)中獲取用戶(hù)信息進(jìn)行驗(yàn)證,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)站欄目:利用SpringSecurity怎么從數(shù)據(jù)庫(kù)中獲取用戶(hù)信息進(jìn)行驗(yàn)證-創(chuàng)新互聯(lián)
URL鏈接:http://bm7419.com/article6/gioog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、小程序開(kāi)發(fā)、定制開(kāi)發(fā)、ChatGPT品牌網(wǎng)站制作、定制網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化