Spring Security自定义登陆界面和密码验证逻辑

这篇具有很好参考价值的文章主要介绍了Spring Security自定义登陆界面和密码验证逻辑。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

1添加maven依赖

2创建配置文件处理跳转拦截等功能以及密码比对功能

3创建userservice

4自定义登陆界面login.html


1首先添加maven依赖

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

2创建配置文件处理跳转拦截等功能以及密码比对功能

package com.example.demo2.demos.web1;

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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDateService userDateService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         *  1. 允许访问路径"/"或者"/home",而不需要登录。
         *  除过"/"或者"/home",其他页面都需要登录。
         *  2. 表单登录,路径是"/login",允许所有用户都可以发起登录操作
         *  3. 允许所有用户都可以退出登录
         */
        http
             .formLogin()
                .loginPage("/login.html")    //登录页面设置
                //配置从前端传递过来的用户名和密码字段名
                //.usernameParameter("name")
				//.passwordParameter("password")
                .loginProcessingUrl("/user/login")   //点击登录后访问的路径
                .defaultSuccessUrl("/index.html").permitAll()   //登录成功后跳转路        
                    径,permitAll表示无条件进行访问
                .and()
             .authorizeRequests()
                .mvcMatchers("/","/user/login").permitAll() //设置不需要认证可以直接访问的 
                 路径
                .anyRequest().authenticated()
                //关闭csrf
                .and().csrf().disable()
             .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .permitAll();
    }
    //密码加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    //密码比对
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDateService);
    }
}

3创建userservice进行用户操作逻辑

package com.example.demo2.demos.web1;

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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author FAN BOY
 * @version 1.0
 * @date 2020/7/20 14:22
 */
@Service
public class UserDateService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //这是通过username查询获取一组数据将获得的数据传给security的User
        //sql语句自己写
        com.example.demo2.demos.web2.User user =new com.example.demo2.demos.web2.User("admin",passwordEncoder.encode("123"),12);
        //这里我们使用静态类来模拟通过数据库获取的user类
//        if (user == null) {
//            throw new UsernameNotFoundException("该用户不存在!");
//        }
        //把获得的账号密码传给security的User
        //注意此时的User是security自带的的User类,第一个参数为用户名,第
二个为密码,一般来说我们从数据库获取的为加密后的密码,所以我们通过上面配置
文件的密码加密自己进行加密,第三个为权限角色,我没有做处理
      return new User(user.getUsername(),user.getPassword(),new ArrayList<>());
    }
}

4自定义登陆界面login.html来替代自带的界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<form action="/user/login" method="post">
//注意用户名和密码 为username和password,security默认为这
两个字段,如果你要用其他的名称,需要在第一个配置文件中的
loginForm中进行配置
    用户名:<input type="text" name="username"/><br>
    密码:<input type="password" name="password"/><br>
    <input type="submit" value="登录"/>
</form>
</body>
</html>

上面的UserDateService 中我们固定返回一个用户名密码为admin        123的user类

然后security的configure(AuthenticationManagerBuilder auth)进行密码对比,注意这里只是比较密码,因为你既然返回user类了就说明你的username是存在的,(小问题,一般来说不会有问题因为我是固定返回的一个类,我在前端只要是密码输入正确就能登陆~)文章来源地址https://www.toymoban.com/news/detail-649423.html

到了这里,关于Spring Security自定义登陆界面和密码验证逻辑的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Security 身份验证的基本类/架构

    目录 1、SecurityContextHolder 核心类 2、SecurityContext 接口 3、Authentication 用户认证信息接口 4、GrantedAuthority 拥有权限接口 5、AuthenticationManager 身份认证管理器接口 6、ProviderManager 身份认证管理器的实现 7、AuthenticationProvider 特定类型的身份验证接口 8、AuthenticationEntryPoint 身份验证

    2024年02月16日
    浏览(31)
  • Spring - Security 之 Servlet身份验证架构

    这个讨论是对之前文章的扩展,用于描述Spring Security在Servlet身份验证中使用的主要架构组件。 组件 描述 SecurityContextHolder SecurityContextHolder是Spring Security存储已认证用户详细信息的位置。 SecurityContext 从SecurityContextHolder获取,包含当前认证用户的认证信息。 Authentication 可以是

    2024年01月23日
    浏览(30)
  • Spring Security BCryptPasswordEncoder 密码加盐

    测试类 上面的运行结果 可以发现对密码加密, 每次都是不一样的密文, 但是任意的一个结果密文和原文match , 得到的都是true, 这到底是是怎么回事尼? 先说结论 BCryptPasswordEncoder的 encode 方法对 原文加密, 是会产生随机数的 盐 salt, 所以每次加密得到的密文都是不同的

    2024年02月11日
    浏览(34)
  • Spring Security实现用户身份验证及权限管理

    Spring Security是Spring生态的一个成员,提供了一套Web应用安全性的完整解决方案。 Spring Security 旨在以一种自包含的方式进行操作,因此你不需要在 Java 运行时环境中放置任何特殊的配置文件。这种设计使部署极为方便,因为可以将目标 工件 (无论是 JAR还是WAR)从一个系统复

    2024年02月05日
    浏览(30)
  • Spring Security:PasswordEncoder密码加密匹配操作

    目录 PasswordEncoder SpringBoot:注入BSryptPasswordEncoder实例 BSryptPasswordEncoder详解 父接口PasswordEncoder BSryptPasswordEncoder及其使用 成员方法 SecurityUtils安全服务工具类 测试代码         PasswordEncoder是Spring Security框架默认使用的密码加密器,对应的数据表 sys_user 的密码 password 字段需

    2023年04月26日
    浏览(27)
  • Spring-Security+OAuth2+redis实现密码登录

    一、OAuth2认证模式         一共四种认证方式,授权码模式、密码模式、简化模式和客户端模式。实现单点登录,比较流行的方法是使用jwt方式,jwt是无状态的,其本身就能携带信息,因此服务端可以不用保存他的信息,但只要token不过期,用户就可以一直访问,这样就无

    2024年02月16日
    浏览(28)
  • 新版Spring Security6.2案例 - Authentication用户名密码

    前面有翻译了新版Spring Security6.2架构,包括总体架构,Authentication和Authorization,感兴趣可以直接点链接,这篇翻译官网给出的关于Authentication的Username/Password这页。 首先呢,官网就直接给出了基于用户名和密码的认证的代码,可以说是spring security的一个入门小案例,表单登录

    2024年02月20日
    浏览(35)
  • 【Spring Security】认证&密码加密&Token令牌&CSRF的使用详解

    🎉🎉欢迎来到我的CSDN主页!🎉🎉 🏅我是Java方文山,一个在CSDN分享笔记的博主。📚📚 🌟推荐给大家我的专栏《Spring Security》。🎯🎯 👉点击这里,就可以查看我的主页啦!👇👇 Java方文山的个人主页 🎁如果感觉还不错的话请给我点赞吧!🎁🎁 💖期待你的加入,一

    2024年02月04日
    浏览(39)
  • 后端进阶之路——Spring Security构建强大的身份验证和授权系统(四)

    「作者主页」 :雪碧有白泡泡 「个人网站」 :雪碧的个人网站 「推荐专栏」 : ★ java一站式服务 ★ ★ 前端炫酷代码分享 ★ ★ uniapp-从构建到提升 ★ ★ 从0到英雄,vue成神之路 ★ ★ 解决算法,一个专栏就够了 ★ ★ 架构咱们从0说 ★ ★ 数据流通的精妙之道★ ★后端进

    2024年02月14日
    浏览(41)
  • Spring Security 6.0系列【14】认证篇之添加登录验证码功能

    有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.0.4 本系列Spring Security 版本 6.0.2 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 验证码 ( CAPTCHA )是“ Completely Automated Public Turing test to tell Computers and Humans Apart ”(全自动区分计算机和人类的图灵

    2023年04月09日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包