Spring security登录过程逻辑详解

 更新时间:2020年04月07日 14:47:29   作者:if年少有为  
这篇文章主要介绍了SSpringsecurity登录过程逻辑详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1. 新建项目

引入web和security包

完整的pom.xml文件如下

<?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.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>spring-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-demo</name>
  <description>Demo project for Spring Boot</description>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <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>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </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>

2. 编写启动类和控制器方法和自定义登录页面

package com.example.springdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringDemoApplication.class, args);
  }

  @GetMapping("/")
  public String hello() {
    return "hello spring security";
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<form action="myLogin.html" method="post">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="submit" value="登录">
</form>
</body>
</html>

3. 编写配置类

package com.example.springdemo.conf;

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.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        //指定处理登录页面
        .loginPage("/myLogin.html")
        //指定登录成功的处理逻辑
        .successHandler(new AuthenticationSuccessHandler() {
          @Override
          public void onAuthenticationSuccess(HttpServletRequest request,
                            HttpServletResponse response,
                            Authentication authentication)
              throws IOException, ServletException {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"error_code\":\"0\",\"message\":\"欢迎登录\"}");
          }
        })
        //指定登录失败时的处理逻辑
        .failureHandler(new AuthenticationFailureHandler() {
          @Override
          public void onAuthenticationFailure(HttpServletRequest request,
                            HttpServletResponse response,
                            AuthenticationException e)
              throws IOException, ServletException {
            response.setStatus(401);
            PrintWriter writer = response.getWriter();
            writer.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");

          }
        })
        .permitAll()
        .and()
        .csrf().disable();
  }
}

4. 运行结果

当输入密码错误时

当输入密码正确时

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

相关文章

  • SpringBoot的异常处理流程是什么样的?

    SpringBoot的异常处理流程是什么样的?

    今天给大家带来的是Java的相关知识,文章围绕着SpringBoot的异常处理流程展开,文中有非常详细的介绍及代码示例,需要的朋友可以参考下
    2021-06-06
  • Java中ThreadLocal的用法及原理详解

    Java中ThreadLocal的用法及原理详解

    这篇文章主要介绍了Java中ThreadLocal的用法及原理详解,在并发编程中,如果一个类变量被多个线程操作,会造成线程安全问题,使用ThreadLocal可以让每个线程拥有线程内部的变量,防止多个线程操作一个类变量造成的线程安全问题,需要的朋友可以参考下
    2023-09-09
  • Java多线程之线程池七个参数详解

    Java多线程之线程池七个参数详解

    这篇文章主要介绍了Java多线程之线程池七个参数详解,文中有很详细的代码示例,对正在学习java的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-04-04
  • java实现自动售货机

    java实现自动售货机

    这篇文章主要为大家详细介绍了java实现自动售货机,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • Spring Cloud @RefreshScope 原理及使用

    Spring Cloud @RefreshScope 原理及使用

    这篇文章主要介绍了Spring Cloud @RefreshScope 原理及使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • maven配置阿里云仓库的实现方法

    maven配置阿里云仓库的实现方法

    本文主要介绍了maven配置阿里云仓库的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Java编程探索之泛型擦除实例解析

    Java编程探索之泛型擦除实例解析

    这篇文章主要介绍了Java编程探索之泛型擦除实例解析,具有一定参考价值,需要的朋友可以了解下。
    2017-10-10
  • Spring cloud alibaba之Gateway网关功能特征详解

    Spring cloud alibaba之Gateway网关功能特征详解

    spring cloud gateway是spring cloud推出的第二代网关,是由WebFlux+Netty+Reactor实现的响应式的API网关,它不能在传统的servlet容器中工作,也不能构建成war包,接下来通过本文给大家分享Spring cloud alibaba--Gateway网关,需要的朋友可以参考下
    2021-08-08
  • 解决Mybatis 大数据量的批量insert问题

    解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • 详解eclipse下创建第一个spring boot项目

    详解eclipse下创建第一个spring boot项目

    本文详细介绍了创建第一个基于eclipse(eclipse-jee-neon-3-win32-x86_64.zip)+spring boot创建的项目。
    2017-04-04

最新评论