SpringSecurity从数据库中获取用户信息进行验证的案例详解
程序员文章站
2022-06-27 19:03:14
基于 springboot与springsecurity整合 案例的修改:数据库 user 表注,密码是由 bcrypt 算法加密对应用户名所得。root$2a$10$uzhvoozlcwbkagsc...
基于 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数据库获取用户信息验证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!