一、导入坐标

<?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.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zsh</groupId>
<artifactId>springsecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsecurity</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</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

二、Users实体类及其数据库表的创建

@Data
public class Users { private int id;
private String username;
private String password;
}

#spring.security.user.name=admin
#spring.security.user.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springsecurity?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=hao20001010

三、controller,service,mapper层的实现

@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityController { @RequestMapping("/hello")
public String hello() { return "hello! Spring Security!";
} @PreAuthorize("hasRole('admin')")
@RequestMapping("/index")
public String index() {
return "hello index!";
} @GetMapping("/delete")
@Secured({"ROLE_user","ROLE_admin"})
public String delete() {
return "delete merchandise";
} @GetMapping("/add")
@PreAuthorize("hasAuthority('admin')")
public String add() {
return "add";
} @GetMapping("/update")
@PostAuthorize("hasAnyAuthority('user')")
public String update() {
System.out.println("update方法已经执行!");
return "update";
} }
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper; @Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username", s);
Users users = userMapper.selectOne(wrapper);
if (users == null) {
throw new UsernameNotFoundException("账号或密码错误!");
} else {
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin");
return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
} }
}
@Repository
public interface UserMapper extends BaseMapper<Users> { }

四、核心–编写配置文件

package com.zsh.security.config;

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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; /**
* @author:抱着鱼睡觉的喵喵
* @date:2021/3/12
* @description:
*/
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter { @Autowired
private UserDetailsService userDetailsService; @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} @Override
protected void configure(HttpSecurity http) throws Exception {
//logout实现注销,注销之后跳转到fail.html
http.logout().logoutUrl("/logout").logoutSuccessUrl("/fail.html").permitAll();
http.exceptionHandling().accessDeniedPage("/noauth.html");
http.formLogin()
.loginPage("/login.html") //设置登录界面
.loginProcessingUrl("/user/login") //登录界面url
.defaultSuccessUrl("/success.html").permitAll() //默认登录成功界面
.and().authorizeRequests() //哪些资源可以直接访问
.antMatchers("/","/test/hello","/user/loin").permitAll() //不做处理
//.antMatchers("/test/index").hasAuthority("admin")
// .antMatchers("/test/index").hasAnyAuthority("admin","manager")
//.antMatchers("/test/index").hasRole("admin")
.antMatchers("/test/index").hasRole("admin")
.anyRequest().authenticated() //所有请求都可以访问
.and().csrf().disable(); //关闭CSRF
} @Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} }

五、页面的实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
username:<input type="text" name="username"> <br>
password:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a>已退出!</a>
<a href="/login.html">去登陆</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a style="background-color: red; margin-top: 100px; margin-left: 100px">no auth</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a>登录成功</a>
<a href="/logout">注销登录</a>
</body>
</html>

运行结果




当在登录状态时,直接去访问/test/index 能够直接到主页面

springboot集成spring security实现登录和注销的更多相关文章

  1. SpringBoot集成Spring Security(6)——登录管理

    文章目录 一.自定义认证成功.失败处理 1.1 CustomAuthenticationSuccessHandler 1.2 CustomAuthenticationFailureHandler 1. ...

  2. SpringBoot集成Spring Security(4)——自定义表单登录

    通过前面三篇文章,你应该大致了解了 Spring Security 的流程.你应该发现了,真正的 login 请求是由 Spring Security 帮我们处理的,那么我们如何实现自定义表单登录呢, ...

  3. SpringBoot集成Spring Security(2)——自动登录

    在上一章:SpringBoot集成Spring Security(1)——入门程序中,我们实现了入门程序,本篇为该程序加上自动登录的功能. 文章目录 一.修改login.html二.两种实现方式 2. ...

  4. SpringBoot集成Spring Security入门体验

    一.前言 Spring Security 和 Apache Shiro 都是安全框架,为Java应用程序提供身份认证和授权. 二者区别 Spring Security:重量级安全框架 Apache S ...

  5. SpringBoot集成Spring Security(7)——认证流程

    文章目录 一.认证流程 二.多个请求共享认证信息 三.获取用户认证信息 在前面的六章中,介绍了 Spring Security 的基础使用,在继续深入向下的学习前,有必要理解清楚 Spring Sec ...

  6. SpringBoot集成Spring Security(5)——权限控制

    在第一篇中,我们说过,用户<–>角色<–>权限三层中,暂时不考虑权限,在这一篇,是时候把它完成了. 为了方便演示,这里的权限只是对角色赋予权限,也就是说同一个角色的用户,权限是 ...

  7. SpringBoot 集成Spring security

    Spring security作为一种安全框架,使用简单,能够很轻松的集成到springboot项目中,下面讲一下如何在SpringBoot中集成Spring Security.使用gradle项目管 ...

  8. SpringBoot集成Spring Security

    1.Spring Security介绍 Spring security,是一个强大的和高度可定制的身份验证和访问控制框架.它是确保基于Spring的应用程序的标准 --来自官方参考手册 Spring ...

  9. SpringBoot集成Spring Security(授权与认证)

    ⒈添加starter依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifact ...

随机推荐

  1. LGP2490题解

    有点儿神秘? 根据他这个题意说的,白子向右的第一个一定是对应的黑子啊. 所以棋子的绝对位置是不重要的,我们只需要考虑白子和黑子的相对位置,然后考虑用 GF 来拼凑状态就好了. 下面的 \(k\) 是题 ...

  2. LGP2726题解

    当初 mark 这道题还是因为看到是黑,感觉比较水,然后它现在掉紫了. 不过这题题解居然满了,写一篇给自己看吧. 首先我们有一个思路,就是割掉一条边,然后分别求两颗树的重心. 等等,这好像是CSP原题 ...

  3. TypeScript-axios模块进行封装的操作与一些想法

    所谓封装与模块化,对我这种初学者来说,个人理解就是解耦,比如说,当我们前端一个项目使用了现在流行的模块,但是没有对其进行封装处理,包括一些相同的代码逻辑,把他们分散在各个组件当中,这样一来整个项目对于 ...

  4. Linux环境下安装Maven

    最近在搞虚拟机,记录下虚拟机内Maven环境的搭建流程 一.选择合适的版本(由于Maven运行需要依赖于JDK,所以安装之前需要保证当前虚拟机下已经安装并配置好JDK环境,安装流程参见) https: ...

  5. 保姆级SpringBoot+Vue图片上传到阿里云OSS教程

    小二是新来的实习生,作为技术 leader,我给他安排了一个非常简单的练手任务,把前端 markdown 编辑器里上传的图片保存到服务器端,结果他真的就把图片直接保存到了服务器上,这下可把我气坏了,就 ...

  6. vim编写C/C++程序过程

    vim编写C.C++程序过程(以hello world为例): vim hello.c/hello.cpp 或者vi hello.c/hello.cpp创建hello.c/hello.cpp文件并进入 ...

  7. Java基础——System类

    System包含几个有用的类字段和方法,因为成员都是静态的所以不能被实例化,可以直接通过类名调用 System类的常用方法: 方法名 说明 public static void exit(int st ...

  8. 基于EMR离线数据分析-反馈有礼

    "云上漫步"第三期-反馈有礼 参与体验产品,提交反馈,就有机会获得定制背包,T恤,超萌虎年鼠标垫,以及5到100元阿里云通用代金券~ 反馈地址: https://developer ...

  9. RabbitMQ Go客户端教程6——RPC

    本文翻译自RabbitMQ官网的Go语言客户端系列教程,本文首发于我的个人博客:liwenzhou.com,教程共分为六篇,本文是第六篇--RPC. 这些教程涵盖了使用RabbitMQ创建消息传递应用 ...

  10. java高级用法之:无所不能的java,本地方法调用实况

    目录 简介 JDK的本地方法 自定义native方法 总结 简介 相信每个程序员都有一个成为C++大师的梦想,毕竟C++程序员处于程序员鄙视链的顶端,他可以俯视任何其他语言的程序员. 但事实情况是,无 ...