栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot整合SpringSecurity实现数据库认证

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot整合SpringSecurity实现数据库认证

文章目录
      • 1. 导入依赖
      • 2. 创建数据库表
      • 3.配置实体类
      • 4.继承UserDetailsService
      • 5.实现UserDetailsService
      • 6.创建页面及controller映射
      • 7.配置SecurityConfig

1. 导入依赖


    4.0.0
    tian.project
    easy_to_stop
    0.0.1-SNAPSHOT
    easy_to_stop
    Demo project for Spring Boot

    
        1.8
        UTF-8
        UTF-8
        2.3.7.RELEASE
    

    

        
            mysql
            mysql-connector-java
        

        
            com.alibaba
            druid
            1.1.24
        

        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

        
            org.projectlombok
            lombok
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.2
        

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        


        
            org.springframework.boot
            spring-boot-starter-security
        


        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity6
            3.1.0.M1
        


        
            org.apache.commons
            commons-lang3
        

        
            commons-codec
            commons-codec
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            junit
            junit
            test
        











    

    
        
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.8.1
                
                    1.8
                    1.8
                    UTF-8
                
            
            
                org.springframework.boot
                spring-boot-maven-plugin
                2.3.7.RELEASE
                
                    tian.project.easy_to_stop.EasyToStopApplication
                
                
                    
                        repackage
                        
                            repackage
                        
                    
                
            

            
                org.apache.maven.plugins
                maven-surefire-plugin
                2.22.2
                
                    true
                
            
        
    



2. 创建数据库表
CREATE TABLE `t_admin` (
  `id` bigint(19) NOT NULL COMMENT '主键',
  `admin` varchar(50) NOT NULL COMMENT '管理员账号',
  `admin_password` varchar(50) NOT NULL COMMENT '管理员密码',
  `role` varchar(50) NOT NULL COMMENT '角色',
  `locked` tinyint(1) DEFAULT '1' COMMENT '判断账户密码是否未过期',
  `check_enabled` tinyint(1) DEFAULT '1' COMMENT '判断账户是否可用',
  `gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `gmt_modified` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3.配置实体类
package tian.project.easy_to_stop.pojo;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.omg.CORBA.IDLType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.annotation.security.DenyAll;
import javax.swing.*;
import java.util.*;


@ApiModel("管理员实体类")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "t_admin")
public class Admin implements UserDetails {
    @ApiModelProperty("主键-雪花算法策略")
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    @ApiModelProperty("管理员账号")
    private String admin;
    @ApiModelProperty("密码")
    private String adminPassword;
    @ApiModelProperty("角色")
    private String role;
    @ApiModelProperty("当前用户是否未锁定")
    private Boolean locked;
    @ApiModelProperty("当前账户是否可用")
    private Boolean checkEnabled;
    @ApiModelProperty("创建时间")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @TableField(value = "gmt_create",fill = FieldFill.INSERT)//数据插入时候自动填充
    private Date gmtCreate;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//返回数据给前端的
    @TableField(fill = FieldFill.INSERT_UPDATE)//数据插入和更新的时候自动填充
    @ApiModelProperty("更新时间")
    private Date gmtModified;


    
    
    

    @Override
    public Collection getAuthorities() {
        List authorities=new ArrayList<>();
        //本系统只有一个角色
        authorities.add(new SimpleGrantedAuthority(role));
        return authorities;
    }

    @Override
    public String getUsername() {
        return admin;
    }

    @Override
    public String getPassword() {
        return adminPassword;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return checkEnabled;
    }
}

4.继承UserDetailsService
package tian.project.easy_to_stop.service;

import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import tian.project.easy_to_stop.pojo.Admin;


@Service
public interface AdminService extends UserDetailsService {
    
    Admin getAdminByAdmin(String name);
}

5.实现UserDetailsService
package tian.project.easy_to_stop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tian.project.easy_to_stop.mapper.AdminMapper;
import tian.project.easy_to_stop.pojo.Admin;
import tian.project.easy_to_stop.service.AdminService;
import tian.project.easy_to_stop.service.UserService;


@Service
@Transactional(rollbackFor = Exception.class
)
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;
    
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Admin admin=this.getAdminByAdmin(name);
        if(ObjectUtils.isEmpty(admin)){
            throw new UsernameNotFoundException("账户不存在!");
        }
        Admin getAdmin=adminMapper.selectById(admin.getId());
        UserDetails userDetails=User.withUsername(getAdmin.getAdmin())
                .password(getAdmin.getAdminPassword())
                .authorities(getAdmin.getRole())
                .build();
        System.out.println("admin:n"+getAdmin);
        System.out.println("userDetails:n"+userDetails.getUsername());
        System.out.println("roles:n"+userDetails.getAuthorities());
        System.out.println("locked:n"+userDetails.isAccountNonLocked());
        System.out.println("enabled:n"+userDetails.isEnabled());
        System.out.println("userDetails:n"+userDetails.getUsername());
        return userDetails;
    }


    @Override
    public Admin getAdminByAdmin(String admin) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("admin",admin);
        return adminMapper.selectOne(queryWrapper);
    }
}

6.创建页面及controller映射

package tian.project.easy_to_stop.controller;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import tian.project.easy_to_stop.constant.Constant;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/page")
@Slf4j
public class PageController {
    
    @ApiOperation("Hello World")
    @GetMapping("/helloWorld")
    public ModelAndView helloWorld(){
        ModelAndView modelAndView=new ModelAndView("helloWorld");
        modelAndView.addObject("name","你好");
        return modelAndView;
    }
    
    @ApiOperation("管理员登录页面")
    @GetMapping("/toLogin")
    public ModelAndView toLogin(){
        log.info("进入登录页面!");
        ModelAndView modelAndView=new ModelAndView("toLogin");
        return modelAndView;
    }
    
    @ApiOperation("views管理页面")
    @GetMapping("/views/{page}")
    public ModelAndView menu(@PathVariable("page") String page){
        ModelAndView modelAndView=new ModelAndView("views/"+page);
        log.info("进入页面!{}",modelAndView);
        return modelAndView;
    }
}

7.配置SecurityConfig
package tian.project.easy_to_stop.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
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.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.Md4PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.ObjectUtils;
import tian.project.easy_to_stop.constant.Constant;
import tian.project.easy_to_stop.service.AdminService;
import tian.project.easy_to_stop.service.UserService;
import tian.project.easy_to_stop.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Configuration
@EnableWebSecurity //开启Spring Security 的权限控制和认证功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AdminService adminService;
    
    //链式编程
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登录页所有人可以访问,功能页管理员可以访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/page/views
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //基于数据库认证
        auth.userDetailsService(adminService).passwordEncoder(passwordEncoder());
//        //这些数据正常从数据库认证,也可以从内存认证
//        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("admin")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("admin1");
    }
    
//    /登录成功的处理器
//            .successHandler(new AuthenticationSuccessHandler() {
//
//        @Override
//        public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
//                HttpServletResponse httpServletResponse,
//                Authentication authentication)
//                            throws IOException, ServletException {
//
//        }
//    })
//            .failureHandler(new AuthenticationFailureHandler() {
//
//        @Override
//        public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
//                HttpServletResponse httpServletResponse,
//                AuthenticationException e)
//                            throws IOException, ServletException {
//
//        }
//    })
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/948263.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号