spring security 使用数据库数据进行认证:

编程入门 行业动态 更新时间:2024-10-21 06:25:26

spring security 使用<a href=https://www.elefans.com/category/jswz/34/1771350.html style=数据库数据进行认证:"/>

spring security 使用数据库数据进行认证:

spring security 使用数据库数据进行认证:

提示:security更新后还需要添加加密方式:

参考:
springboot+security 的BCryptPasswordEncoder 使用

SpringBoot Security:Encoded password does not look like BCrypt 解决

以及其狂神的视频,还有其他博主。


主要代码:

实体类:我这边用的是lombok, 不用记得加上 set,get 方法,无参构造。
里面主要得有两个字段:账号,密码,我这里是手机号,role 是身份;

import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;/*** @author Nuisance* @since 2020-08-31*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {private static final long serialVersionUID = 1L;private String phone;      private String password;private String role; private String username;
}

mapper:mapper接口,

import com.example.demo.blog.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>*  Mapper 接口* </p>** @author Nuisance* @since 2020-08-31*/
public interface UserMapper extends BaseMapper<User> {//这边写一个select方法,我用的是mybatisPlus,已经继承了父类的方法所以没写;
}

service


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.subject.LiTu.entity.User;
import com.example.subject.LiTu.mapper.UserMapper;
import com.example.subject.LiTu.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/*** <p>*  服务实现类* </p>** @author Nuisance* @since 2020-08-31*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {@Autowiredprivate UserMapper userService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {System.out.println("进入service,用户为 : "  + username);if(username == null || username == ""){throw new UsernameNotFoundException("请输入用户手机号!");}/**下面三行就是换成mapper写的 select方法,查询user中的账号,密码,以及身份*/QueryWrapper<User> wrapper =new QueryWrapper<>();wrapper.eq("phone",username);User user = userService.selectOne(wrapper);if(user != null){List<SimpleGrantedAuthority> authorities = new ArrayList<>();// 设置登录账号的角色authorities.add(new SimpleGrantedAuthority("ROLE_vip"));UserDetails user1 =  new org.springframework.security.core.userdetails.User(user.getPhone(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);//密码需要加密return user1;}return null;}
}

SpringSecurityConfig :config 类

package com.example.subject.Config;import com.example.subject.LiTu.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
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 org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;/*** @author Nuisance* @date 2020/8/30 11:59*/
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@Resourceprivate UserServiceImpl userService;/*** 授权* @param http* @throws Exception*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/login").permitAll()// .antMatchers("/LiTu/**").permitAll();.antMatchers("/LiTu/**").hasRole("vip");//身份授权//定制登录页面(/toLogin)http.formLogin().loginPage("/toLogin").successForwardUrl("/LiTu/");http.csrf().disable();//关闭CSRF功能http.logout().logoutSuccessUrl("/toLogin");http.rememberMe().rememberMeParameter("remember");}/*** 认证* @param auth* @throws Exception*///定义认证规则@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());//认证,设置加密方式 }@BeanPasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
}

常见原因分析:

1、没有设置加密,出警告,且无法验证:Encoded password does not look like BCrypt;
在service,和config类都加上就行了;

2、User:

UserDetails user1 =  new org.springframework.security.core.userdetails.User(user.getPhone(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);
//注意这里面的User类是哪里的

更多推荐

spring security 使用数据库数据进行认证:

本文发布于:2024-03-10 21:19:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1729061.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   数据   spring   security

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!