springboot 整合springsecurity 通过数据库获取账号密码

  • 创建数据库
  • 创建实体类
  • 导入security 依赖
  • 创建SecurityConfig 继承 WebSecurityConfigurerAdapter
  • 实现UserDetailsService接口

之前学security的时候发现很多篇博文都是通过自定义的UserDetails来进行登录,并且加了Role 这一表来查看用户有没有以下角色后完成登录,但初学者或许会感觉比较乱,所以想给初学者一点更简单的方法实现,在里面我是用自己定制的登录页,你们可以不用,直接用它本身的测试就好了

创建数据库

/*
Navicat MySQL Data Transfer

Source Server         : spring
Source Server Version : 80017
Source Host           : localhost:3306
Source Database       : dev

Target Server Type    : MYSQL
Target Server Version : 80017
File Encoding         : 65001

Date: 2020-07-20 15:10:43
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `u_ser`
-- ----------------------------
DROP TABLE IF EXISTS `u_ser`;
CREATE TABLE `u_ser` (
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(10) NOT NULL,
  `number` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of u_ser
-- ----------------------------
INSERT INTO `u_ser` VALUES ('[email protected]', '给你看上了', '12345', '1234567894', '2020-07-20 14:47:52');
INSERT INTO `u_ser` VALUES ('[email protected]', '工会', '123', '123456786', '2020-07-17 21:28:41');
INSERT INTO `u_ser` VALUES ('[email protected]', '将水', '123456', '1834879648', '2020-07-16 19:25:58');
INSERT INTO `u_ser` VALUES ('[email protected]', '花无语', '1234564', '12313156', '2020-07-16 19:33:31');
INSERT INTO `u_ser` VALUES ('[email protected]', '张大炮', '123456', '123154846', '2020-07-16 19:26:01');
INSERT INTO `u_ser` VALUES ('[email protected]', '水大', '123459', '154564564', '2020-07-16 19:33:28');

创建实体类
这里是用lombok

package com.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import javax.persistence.Id;
/**
 * @author FAN BOY
 * @version 1.0
 * @date 2020/7/9 20:29
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class U_ser implements Serializable {
    @Id
    String username;
    String name;
    String password;
    String number;
    String time;

}

导入依赖

package com.config;

import com.service.UserService;
import com.service.impl.UserDateService;
import org.springframework.beans.factory.annotation.Autowired;
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.NoOpPasswordEncoder;

/**
 * @author FAN BOY
 * @version 1.0
 * @date 2020/6/26 14:43
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDateService userDateService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置不拦截首页登录页以及静态资源
        http.authorizeRequests().antMatchers("/tologin","/","/index","/css/**","/js/**","/img/**","/music/**","/plugins/**","/editormd/**","/Nabigation/**").permitAll()
                .anyRequest().authenticated();

        //以下是自定义login页面以及设置登出界面
        //loginPage("/tologin") 代表拦截后跳转的界面,也是自己定制的登录界面
        //loginProcessingUrl("/login")代表实现登录的界面,在表单中要跳这个url完成登陆验证
    http.formLogin().loginPage("/tologin") .usernameParameter("username")
            .passwordParameter("password").loginProcessingUrl("/login").permitAll()
                .and().logout().logoutSuccessUrl("/").invalidateHttpSession(true).deleteCookies("remove");
    
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDateService);
        super.configure(auth);
    }
    //开启不需要安全密码
    @Bean
    NoOpPasswordEncoder noOpPasswordEncoder(){
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}


实现UserDetailsService接口

package com.service.impl;

import com.mapper.UserMapper;
import com.pojo.U_ser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author FAN BOY
 * @version 1.0
 * @date 2020/7/20 14:22
 */
@Service
public class UserDateService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //这是通过username查询获取一组数据将获得的数据传给security的User
    //sql语句自己写
        U_ser user = userMapper.selectByPrimaryKey(s);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在!");
        }
        //把获得的账号密码传给security的User
        return new User(user.getUsername(),user.getPassword(),new ArrayList<>());
    }
}

测试
随便创建一个controller只要被拦截了就会自动出现登录界面
在这里插入图片描述
数据库中账号密码
在这里插入图片描述
登录成功获得了session
在这里插入图片描述
如果登录失败url会显示
在这里插入图片描述
希望会对你有所帮助,使用起来并不是非常难,就是刚开始或许不熟悉,因为springboot的原因springsecurity变得配置十分简单也是security变得越来越多人用的原因

猜你喜欢

转载自blog.csdn.net/MemoryLoss78/article/details/107464048
今日推荐