SpringBoot集成SpringSecurity框架实现登录功能(模板)

配置依赖

大致所需依赖如下:

SpringBoot集成SpringSecurity框架实现登录功能(模板)_第1张图片



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.7
         
    
    com.yunhe
    SpringBootDemo3
    0.0.1-SNAPSHOT
    SpringBootDemo3
    SpringBootDemo3
    
        8
    
    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity5
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.2
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            com.mysql
            mysql-connector-j
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter-test
            2.2.2
            test
        

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

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    


配置application配置文件
server.port=8080
#配置数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123

#thymeleaf 缓存关闭
spring.thymeleaf.cache=false

#mybatis驼峰
mybatis.configuration.map-underscore-to-camel-case=true

#设置静态资源位置
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/

编写Security配置文件
package com.yunhe.config;

import com.yunhe.service.AccountService;
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.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.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security配置文件
 */
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccountService accountService;

    /**
     * 认证数据管理,连接service
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(accountService);
    }

    /**
     * 设置认证的访问配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //放行资源
        http.authorizeRequests().antMatchers("/login.html","/error.html","/register.html").permitAll();

        //角色名不加 ROLE_ ,系统自动添加
        http.authorizeRequests().antMatchers("/**").hasAnyRole("USER","ADMIN");

        //设置资源必须登录成功后进行访问
        http.authorizeRequests().antMatchers("/**").authenticated();

        //设置登录页面
        http.formLogin().defaultSuccessUrl("/index").loginPage("/login.html").loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .failureUrl("/error.html");

        //设置退出登录
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");

        //关闭跨域
        http.csrf().disable();

        //配置403异常处理
        http.exceptionHandling().accessDeniedPage("/authizeError.html");
    }

    //定义加密器
    @Bean
    public PasswordEncoder createPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
}
编写业务层方法

业务层接口要继承UserDetailsService方法

SpringBoot集成SpringSecurity框架实现登录功能(模板)_第2张图片

package com.yunhe.service.impl;

import com.yunhe.service.AccountService;
import com.yunhe.dao.AccountDao;
import com.yunhe.entity.Account;
import com.yunhe.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    /**
     * 登录认证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //调用持久层获取用户信息
        Account account = accountDao.findAccountByUsername(username);

        //创建一个认证对象
        User user = new User(account.getUsername(),account.getPassword(),true,true,true,true,getRoles(account.getRoles()));

        return user;
    }

    //获取用户的授权角色
    private Collection getRoles(List roles) {

        ArrayList sgas = new ArrayList<>();

        //遍历查询到的角色集合
        for (Role role : roles) {

            SimpleGrantedAuthority sa = new SimpleGrantedAuthority("ROLE_" + role.getRolename());

            sgas.add(sa);
        }

        return sgas;
    }

}
编写持久层方法

持久层要查询用户信息以及权限信息,要查询两个表+中间表

import com.yunhe.entity.Account;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface AccountDao {
    @Select("select id,username,password from account where username=#{username}")
    @Results({
            @Result(property = "roles",javaType = List.class,column ="id",many = @Many(select = "com.yunhe.dao.RoleDao.findRolesByAid"))
    })
    Account findAccountByUsername(String username);
}
import com.yunhe.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface RoleDao {
    @Select("select r.* from role_account ra,role r where ra.rid = r.id and ra.aid=#{id}")
    List findRolesByAid(int id);
}
登录准备

先来一个登录页面




    
    
    登录



  
账号:
密码:

由于在Security配置文件中配置了登录成功跳转页面、登录页面、登录方法,而在项目中使用了thymeleaf模板引擎,所以需要进行控制层跳转。

控制层跳转主页面:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

    @RequestMapping("index")
    public String index(){

        return "index";
    }
}

配置文件中的其他页面如error页面、403页面自行设置即可。

你可能感兴趣的:(后端,java,springboot,spring,boot,spring,java,mybatis,idea)