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

4 篇文章 0 订阅
1 篇文章 0 订阅
配置依赖

大致所需依赖如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.7</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yunhe</groupId>
    <artifactId>SpringBootDemo3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootDemo3</name>
    <description>SpringBootDemo3</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- 该依赖无法直接生成,需手动添加,不然获取不到权限 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>2.2.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
配置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方法

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<? extends GrantedAuthority> getRoles(List<Role> roles) {

        ArrayList<SimpleGrantedAuthority> 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<Role> findRolesByAid(int id);
}
登录准备

先来一个登录页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <base href="http://localhost:8080/"/>
    <title>登录</title>
</head>
<body>

  <form action="login" method="post">
    账号:<input type="text" name="username"/><br/>
    密码:<input type="password" name="password"/><br/>
    <button type="submit">登录</button>
    <button><a href="register.html">注册</a></button>
  </form>
</body>
</html>

由于在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页面自行设置即可。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四夕兴言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值