SpringSecurity自定义登录界面

为什么需要自定义登录界面?

答:因为SpringBoot整合SpringSecurity时,只需要一个依赖,无需其他配置,就可以实现认证功能。但是它的认证登录界面是固定那样的,如下图所示,但是我们希望自己搞个好看的登录界面,所以需要自定义登录界面。

第一步:创建springboot项目

<?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.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-security-03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-security-03</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第二步:添加配置application.properties

#修改springSecurity默认用户名和密码
spring.security.user.name=root
spring.security.user.password=root

#设置 thymeleaf 缓存为false,表示立即生效
spring.thymeleaf.cache=false

第三步:Controller

package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("hello spring security");
        return "hello spring security";
    }
}
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @RequestMapping("/index")
    public String hello(){
        System.out.println("hello index");
        return "hello index";
    }
}
package com.example.controller;

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

@Controller
public class LoginController {

    @RequestMapping("/loginHtml")
    public String loginHtml(){
        return "login";
    }
}

第四步:login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/" lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form th:action="@{/doLogin}" method="post">
        用户名:<input type="text" name="username"> <br>
        密码:<input type="text" name="password"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

第五步:配置自定义登录界面

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

5.1 请求参数名修改

上面的login.html用户名必须为username,密码必须为password,如果我们想要使用自定义的属性名,按照如下修改

5.1.1 修改login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/" lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form th:action="@{/doLogin}" method="post">
        用户名:<input type="text" name="uname"> <br>
        密码:<input type="text" name="passwd"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

5.1.2 修改配置类

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

5.1 认证成功跳转路径

修改配置类successForwardUrl

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
                .successForwardUrl("/index")//认证成功 forward 跳转路径
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

修改配置类defaultSuccessUrl

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers("/index").permitAll() //代表放行index的所有请求
                .mvcMatchers("/loginHtml").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage("/loginHtml")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl("/doLogin")//指定处理登录的请求url
                .usernameParameter("uname") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter("passwd")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
//                .successForwardUrl("/index")//认证成功 forward 跳转路径,forward代表服务器内部的跳转之后,地址栏不变 始终在认证成功之后跳转到指定请求
                .defaultSuccessUrl("/index")//认证成功 之后跳转,重定向 redirect 跳转后,地址会发生改变  根据上一保存请求进行成功跳转
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

访问http://localhost:8080/hello,认证后

发现并没有到/index的情况,这是defaultSuccessUrl一特性,如果你想硬跳到/index,修改java defaultSuccessUrl("/index",true)即可

访问http://localhost:8080/loginHtml,认证后

defaultSuccessUrl和successForwardUrl区别

1、successForwardUrl是forward跳转,defaultSuccessUrl是重定向redirect跳转
2、successForwardUrl始终在认证成功之后跳转到指定请求,defaultSuccessUrl根据上一保存请求进行成功跳转

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • SpringSecurity整合springBoot、redis实现登录互踢功能

    背景 基于我的文章--<SpringSecurity整合springBoot.redis token动态url权限校验>.要实现的功能是要实现一个用户不可以同时在两台设备上登录,有两种思路: (1)后来的登录自动踢掉前面的登录. (2)如果用户已经登录,则不允许后来者登录. 需要特别说明的是,项目的基础是已经是redis维护的session. 配置redisHttpSession 设置spring session由redis 管理. 2.1去掉yml中的http session 配置,yml和

  • 解决SpringSecurity 一直登录失败的问题

    springsecurity 是spring提供的关于登录授权的框架,他提供了controller层的服务,只需要我们自己实现service层和dao层,以及一些相关的配置 错误结果以及调试信息 笔者初次使用springsecurity,登录一直显示错误,郁闷的一批,代码debug调试结构 调试结果显示service层返回controller层的结果里面 全部正确,最后一个List 参数也符合权限配置 结果仍旧返回失败,经过两个小时的各种跪求,找到了原因. 解决方案 原来,springsecur

  • SpringSecurity动态加载用户角色权限实现登录及鉴权功能

    很多人觉得Spring Security实现登录验证很难,我最开始学习的时候也这样觉得.因为我好久都没看懂我该怎么样将自己写的用于接收用户名密码的Controller与Spring Security结合使用,这是一个先入为主的误区.后来我搞懂了:根本不用你自己去写Controller. 你只需要告诉Spring Security用户信息.角色信息.权限信息.登录页是什么?登陆成功页是什么?或者其他有关登录的一切信息.具体的登录验证逻辑它来帮你实现. 一.动态数据登录验证的基础知识 在本号之前的文

  • Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

    如今,互联网项目对于安全的要求越来越严格,这就是对后端开发提出了更多的要求,目前比较成熟的几种大家比较熟悉的模式,像RBAC 基于角色权限的验证,shiro框架专门用于处理权限方面的,另一个比较流行的后端框架是Spring-Security,该框架提供了一整套比较成熟,也很完整的机制用于处理各类场景下的可以基于权限,资源路径,以及授权方面的解决方案,部分模块支持定制化,而且在和oauth2.0进行了很好的无缝连接,在移动互联网的授权认证方面有很强的优势,具体的使用大家可以结合自己的业务场景进行选

  • SpringBoot + SpringSecurity 短信验证码登录功能实现

    实现原理 在之前的文章中,我们介绍了普通的帐号密码登录的方式: SpringBoot + Spring Security 基本使用及个性化登录配置. 但是现在还有一种常见的方式,就是直接通过手机短信验证码登录,这里就需要自己来做一些额外的工作了. 对SpringSecurity认证流程详解有一定了解的都知道,在帐号密码认证的过程中,涉及到了以下几个类:UsernamePasswordAuthenticationFilter(用于请求参数获取),UsernamePasswordAuthentica

  • 详解SpringSecurity中的Authentication信息与登录流程

    Authentication 使用SpringSecurity可以在任何地方注入Authentication进而获取到当前登录的用户信息,可谓十分强大. 在Authenticaiton的继承体系中,实现类UsernamePasswordAuthenticationToken 算是比较常见的一个了,在这个类中存在两个属性:principal和credentials,其实分别代表着用户和密码.[当然其他的属性存在于其父类中,如authorities和details.] 我们需要对这个对象有一个基本地

  • SpringBoot+SpringSecurity处理Ajax登录请求问题(推荐)

    最近在项目中遇到了这样一个问题:前后端分离,前端用Vue来做,所有的数据请求都使用vue-resource,没有使用表单,因此数据交互都是使用JSON,后台使用Spring Boot,权限验证使用了Spring Security,因为之前用Spring Security都是处理页面的,这次单纯处理Ajax请求,因此记录下遇到的一些问题.这里的解决方案不仅适用于Ajax请求,也可以解决移动端请求验证. 创建工程 首先我们需要创建一个Spring Boot工程,创建时需要引入Web.Spring S

  • SpringSecurity 默认表单登录页展示流程源码

    SpringSecurity 默认表单登录页展示流程源码 本篇主要讲解 SpringSecurity提供的默认表单登录页 它是如何展示的的流程, 涉及 1.FilterSecurityInterceptor, 2.ExceptionTranslationFilc,xmccmc,ter , 3.DefaultLoginPageGeneratingFilter 过滤器, 并且简单介绍了 AccessDecisionManager 投票机制  1.准备工作(体验SpringSecurity默认表单认证

  • 解析SpringSecurity自定义登录验证成功与失败的结果处理问题

    一.需要自定义登录结果的场景 在我之前的文章中,做过登录验证流程的源码解析.其中比较重要的就是 当我们登录成功的时候,是由AuthenticationSuccessHandler进行登录结果处理,默认跳转到defaultSuccessUrl配置的路径对应的资源页面(一般是首页index.html). 当我们登录失败的时候,是由AuthenticationfailureHandler进行登录结果处理,默认跳转到failureUrl配置的路径对应的资源页面(一般是登录页login.html). 但是

  • springboot+jwt+springSecurity微信小程序授权登录问题

    场景重现:1.微信小程序向后台发送请求 --而后台web采用的springSecuriry没有token生成,就会拦截请求,,所以小编记录下这个问题 微信小程序授权登录问题 思路 参考网上一大堆资料 核心关键字: 自定义授权+鉴权 (说的通俗就是解决办法就是改造springSecurity的过滤器) 参考文章 https://www.jb51.net/article/204704.htm 总的来说的 通过自定义的WxAppletAuthenticationFilter替换默认的UsernameP

随机推荐