Spring boot 项目(二十二)——集成Spring Security,完成用户登录

Security简介

Spring 是非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
在这里插入图片描述

核心功能:

  • 用户认证(Authentication):系统判断用户是否能登录
  • 用户授权(Authorization):系统判断用户是否有权限去做某些事情

特点:

  • Spring 技术栈的组成部分,与Spring 无缝整合。
  • 全面的权限控制,能提供完整可扩展的认证和授权支持保护
  • 专门为 Web开发而设计。
  • 重量级,需要引入各种家族组件与依赖

项目结构

在这里插入图片描述

代码部分

1、pom文件

<!--Springboot启动-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--Spring Web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!--mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!--Spring Security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2、yml配置文件

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/websocket
    driver-class-name: com.mysql.jdbc.Driver
  thymeleaf:
    cache: false
    #prefix: classpath:/templates/
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
  typeAliasesPackage: com.iss.security.*.entity
  #  mapperLocations: classpath:mapper/*.xml

3、security配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 流星
 * security配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 自定义无访问权限跳转的页面
         */
        http.exceptionHandling()
                .accessDeniedPage("/403.html");
        /**
         * 自定义登陆页面
         */
        http.formLogin()
                //登陆页面设置
                .loginPage("/index.html")
                //登陆访问路径
                .loginProcessingUrl("/user/login")
                //登陆成功后跳转路径
                .defaultSuccessUrl("/success.html").permitAll()
                .and()
                .authorizeRequests()
                //设置不需要认证的访问路径,可以直接访问
                .antMatchers("/", "/user/login").permitAll()

                //当前用户只有具有addUser权限时才能访问该路径
//                .antMatchers("/test/addUser").hasAuthority("addUser")

//                .antMatchers("/test/findAll").hasAnyAuthority("addUser,findAll")
//                .antMatchers("/test/hello").hasRole("admin")
//                .antMatchers("/test/hello").hasAnyRole("admin")

                .anyRequest().authenticated()
                .and()
                //关闭csrf的保护
                .csrf().disable();
        http.logout()
                //退出的地址
                .logoutUrl("/logout")
                .logoutSuccessUrl("/index.html").permitAll();
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }
}

4、MyUserDetailsService

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iss.security.login.entity.SysUser;
import com.iss.security.login.mapper.SysUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * 进行认证操作
 *
 * @author lx
 * @since 2022-06-05 13:01:06
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //调用usersMapper方法,根据用户名查询数据库
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",username);
        SysUser users = sysUserMapper.selectOne(wrapper);
        if(users==null){
            //数据库没有数据,认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //手动设置权限,也可以通过数据库查询获取
        List<GrantedAuthority> auths = AuthorityUtils
                .commaSeparatedStringToAuthorityList("addUser,findAll,ROLE_admin,ROLE_user");
        
        return new User(users.getUserName(),
                new BCryptPasswordEncoder().encode(users.getPassword()),auths);
    }

}

5、entity

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUser implements Serializable {

    private Integer id;

    private String userName;

    private String password;

    private String qqMail;

    private String role;

}

6、mybatis-plus
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
7、html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="hidden" name="_csrf.parameterName" th:value="${_csrf.token}"  th:if="${_csrf}!=null"/>
<form action="/user/login" method="post">
    <!--注意:页面提交方式必须为 post 请求,用户名,密码必须为username,password
    可以通过 usernameParameter()passwordParameter()方法修改默认配置-->
    用户名:<input type="text" name="username">
    <br/>
    密码:<input type="password" name="password">
    <br/>
    <input type="submit" value="login">

</form>
</body>
</html>

在这里插入图片描述
在这里插入图片描述

测试结果

在这里插入图片描述
在这里插入图片描述

扩展资料

在这里插入图片描述
权限控制:
在这里插入图片描述

附:参考资料

SpringBoot整合SpringSecurity超详细入门教程

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

--流星。

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

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

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

打赏作者

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

抵扣说明:

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

余额充值