Spring Boot整合Spring Security并设置自定义登录页面

准备工作,创建一个Spring Boot项目,注意选择Spring Boot的版本,选择3.0以下的版本。

 选择如下依赖,等待项目创建成功。

项目创建成功之后,添加Mybatis-plus的依赖。

 <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

 上篇文章没有带大家查询数据库,这次我们就去查一下,并且使用ide自带的MybatisX的插件去逆向生成我们的的实体类和mapper文件。

创建数据库text,创建表、字段.


CREATE DATABASE `text`;

USE `text`;


DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `t_id` int(4) NOT NULL AUTO_INCREMENT,
  `t_name` varchar(20) DEFAULT NULL,
  `t_password` varchar(60) DEFAULT NULL,
  `t_authority` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


insert  into `t_user`(`t_id`,`t_name`,`t_password`,`t_authority`) values (1,'yjd','123','1'),(2,'zhansan','123','0');

MybatisX的使用大家可以看一下我的另外一篇文章。这里不再赘述了。

逆向生成实体类之后,我们先配置数据源。

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/text?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: ******

mybatis-plus:
  #    配置mybatis-plus
  mapper-locations: mapper/*.xml

启动项目,不出意外是Security默认生成是账户和密码。接下来我们按照我上一篇文章的方法,使用UserDetailsService和PasswordEncode接口,自定义登录验证的逻辑,将它更改为从数据库查询。

由于我们存放在数据库中的密码是明文的方式,所以我们先通过测试类,使用 BCryptPasswordEncoder加密一下密码并放到数据库中

    @Test
    void contextLoads() {
        PasswordEncoder pe=new BCryptPasswordEncoder();
        System.out.println(pe.encode("123"));
    }

 

数据存入数据库之后,和上一篇文章一样,创建一个配置类,将PasswordEncoder注入容器,然后创建一个类去实现UserDetailsService接口。

实现UserDetailsService接口

package com.dong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dong.mapper.UserMapper;
import com.dong.pojo.User;

import org.springframework.security.core.authority.AuthorityUtils;
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.util.StringUtils;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    //注入mapper查询数据库

    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //1.查询数据库
        QueryWrapper<User> lqw=new QueryWrapper<>();
        lqw.eq("t_name",username); //查询数据库中用户名为username的用户。
        User user = userMapper.selectOne(lqw);
        System.out.println("user = " + user);
        if(StringUtils.isEmpty(user)){
//            如果为空,抛出异常。
            throw new UsernameNotFoundException("用户不存在!");
        }
        //如果存在,则封装到User中返回,这里要注意区分两个User
        return new org.springframework.security.core.userdetails.User
        (user.getTName(),user.getTPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(user.getTAuthority()));
    }
}

创建配置类,注入PasswordEncoder

package com.dong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder getPe(){
        return new BCryptPasswordEncoder();
    }
}

别忘了在启动类上面添加mapperScan注解。

 启动项目, 输入数据库中的用户登录。

ps:如果启动之后配置没有生效。观察你的启动类是不是所在的位置。

 登录成功,并且后台也输出了我们从数据库中查询到的数据。

接下来就是替换掉security自带的登录页面,换成我们自己的登录页面

首先我们在static目录下面准备两个页面,一个是登录页面,一个是登录成功的页面。

 重启项目,访问login.html,发现还是得先登录之后才能访问到我们的页面

 接下来继续在我们之前创建的SecurityConfig配置类中进行配置。

让其SecurityConfig配置类继承WebSecurityConfigureAdapter类,并且重写其中的configure方法,在configur方法中就可以自定义登录页面。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //表单提交
        httpSecurity.formLogin()
                //自定义登录页面
                .loginPage("/login.html");
    }
    @Bean
    public PasswordEncoder getPe(){
        return new BCryptPasswordEncoder();
    }
}

我们再次重启项目,发现可以直接访问到login.html。

 不仅可以访问到login.html页面,而且也可以访问到index.html,好像不用登录也可以访问了,那这样我们做的那些配置不就都没有用了吗?当然不是,我们还需要对它进行配置。

package com.dong.config;

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.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //表单提交
        httpSecurity.formLogin()
                //自定义登录页面
                .loginPage("/login.html")
                //设置默认的的登录路径
                .loginProcessingUrl("/login")
                //登录成功之后跳转的路径
                .successForwardUrl("/index");

        //开启授权认证
        httpSecurity.authorizeRequests()
                //将登录路径排除在外
                .antMatchers("/login.html").permitAll()
                //所有的请求都需要登录之后才能访问
                .anyRequest().authenticated();
        //关闭security的防护,类似于电脑的防火墙
        httpSecurity.csrf().disable();
    }

    @Bean
    public PasswordEncoder getPe(){
        return new BCryptPasswordEncoder();
    }
}

配置完成之后,启动项目测试一下,然后你会发现无论我们访问什么路径,它最终都会跳转到登录页面。只有登录之后才会跳转到其他页面。

以上就是自定义登录逻辑和自定义登录页面的内容了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是Spring Boot整合Spring Security自定义登录的步骤: 1. 引入依赖:在pom.xml文件中引入Spring Security和Thymeleaf的依赖。 2. 配置Spring Security:在Spring Boot的配置类中添加@EnableWebSecurity注解,并继承WebSecurityConfigurerAdapter类,重写configure(HttpSecurity http)方法,配置登录页面、登录请求、登录成功后的跳转等信息。 3. 自定义登录页面:在resources/templates目录下创建login.html文件,使用Thymeleaf模板引擎实现自定义登录页面。 4. 自定义登录表单:在login.html文件中添加表单,表单中包含用户名和密码两个输入框。 5. 自定义登录请求:在Spring Boot的控制器类中添加/login请求的处理方法,该方法接收用户名和密码参数,并使用Spring Security提供的AuthenticationManager进行认证。 6. 自定义认证逻辑:在Spring Security的配置类中重写configure(AuthenticationManagerBuilder auth)方法,实现自定义的认证逻辑。 7. 自定义登录成功后的跳转:在Spring Security的配置类中重写configure(HttpSecurity http)方法,配置登录成功后的跳转页面。 下面是示例代码: 1. 引入依赖: ```xml <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> ``` 2. 配置Spring Security: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login", "/register").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } } ``` 3. 自定义登录页面: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h1>Login</h1> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" required autofocus> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" required> </div> <button type="submit">Login</button> </form> </body> </html> ``` 4. 自定义登录表单:在login.html文件中添加表单,表单中包含用户名和密码两个输入框。 5. 自定义登录请求: ```java @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") public String doLogin(@RequestParam String username, @RequestParam String password) { // 使用AuthenticationManager进行认证 return "redirect:/home"; } } ``` 6. 自定义认证逻辑: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } } ``` 7. 自定义登录成功后的跳转: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login", "/register").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@Yjd007

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

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

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

打赏作者

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

抵扣说明:

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

余额充值