全栈式使用 SpringBoot + SpringSecurity 做登录认证
发布日期:2021-06-30 16:50:33 浏览次数:4 分类:技术文章

本文共 9285 字,大约阅读时间需要 30 分钟。

一、前言

这里写图片描述

目前JavaEE开发中,安全框架流行的主要有两个,分别是 Shiro、SpringSecurity。
之前是都是使用 Shiro 做权限管理的,原因很简单,因为大家都说这个更简单轻量,都觉得 SpringSecurity 太笨重复杂。但是在下使用了之后,觉得还是挺简单,因为我们开发基本都要以 Spring 为核心,而 SpringSecurity 更能很好地整合在一块,其和 SpringBoot 整合更是不在话下。

二、功能演示

下面使用 SpringBoot + SpringSecurity + thymeleaf,做一个简单的登录认证,以后有空在补上授权吧

说明:
①在原式页面上,输入跳转到 main.html 的 RequestMapping localhost/main ,由于还没有登录,跳转到登录界面
②在登录界面输入正确的用户名、密码,进入main.html 这个设置好的登录成功页面
③ 点击注销按钮,又回到登录页面
这里写图片描述

为了看到输入密码的内容,type="text",而不用 type="password"

三、代码

这里写图片描述

1、后台:使用了 SpringBoot 之后,异常简单,

① SpringSecurity 配置类

package com.cun.conf;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;/** * 使用 SpringSecurity 有很多好处: * ①输入一个需要登录验证的url,先跳转到登录界面,登录成功后,立即跳转到刚才请求的url * @author linhongcun * */@Configuration@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启 SpringSecurity注解// 1.继承WebSecurityConfigurerAdapter适配器public class SpringSecurityConf extends WebSecurityConfigurerAdapter {
// 2.重写configure(AuthenticationManagerBuilder)、configure(HttpSecurity),快捷键Alt+Shift+S @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("cun")// 用户名 .password("123")// 用户密码 .roles("USER");// 认证后必须加入一个角色,这里随便设为USER } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().cors().disable().headers().disable()// 一般设置去掉,否则经常报错 .authorizeRequests() .anyRequest() .authenticated()// 其他 url 需要身份认证 .and() .formLogin() //开启登录 .loginPage("/login")// 指定登录请求的 url .defaultSuccessUrl("/main") // 登录成功后的 url .permitAll() .and() .logout() //开启注销 .logoutUrl("/logout") //指定注销请求的 url (default is "/logout"). .logoutSuccessUrl("/login") // 注销成功后的 url .permitAll(); }}

② 控制层

package com.cun.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class SpringSecurityController {
/** * 发送登录请求,则跳转的到登录页面login.html * @return */ @RequestMapping("/login") public String login() { //或者 return "/login",都一样,下面同理 return "login"; } /** * 登录成功后发送请求,则跳转到登录成功页面 mian.html * @return */ @RequestMapping("/main") public String main() { return "main"; }}

2、前端:仅为了演示,去除所有修饰

① 登录页面

登录界面

②登录成功页面

            
后台管理

欢迎管理员进入后台管理系统

Copyright © 2016-2018 linhongcun

3、application.yml

server:     port: 80    context-path: /spring:    datasource:      driver-class-name: com.mysql.jdbc.Driver      url: jdbc:mysql://localhost:3306/mybatis      username: root      password: 123   jpa:       hibernate:        ddl-auto: update      show-sql: true   thymeleaf:       cache: false

4、pom.xml

4.0.0
com.cun
SpringSecurityTest
0.0.1-SNAPSHOT
war
SpringSecurityTest
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-tomcat
provided
org.springframework.boot
spring-boot-starter-test
test
org.springframework.security
spring-security-test
test
org.springframework.boot
spring-boot-maven-plugin

四、细节(2018.6.1更新)

1、实践出真知,使用的过程满满的都是坑,我遇过的坑基本都注释在代码里边。

SpringSecurity 常见的配置补充

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;@EnableWebSecuritypublic class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定制请求的授权规则 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("VIP1") .antMatchers("/level2/**").hasRole("VIP2") .antMatchers("/level3/**").hasRole("VIP3"); //开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面 http.formLogin().usernameParameter("user").passwordParameter("pwd") .loginPage("/userlogin"); //1、/login来到登陆页 //2、重定向到/login?error表示登陆失败 //3、更多详细规定 //4、默认post形式的 /login代表处理登陆 //5、一但定制loginPage;那么 loginPage的post请求就是登陆 //开启自动配置的注销功能。 http.logout().logoutSuccessUrl("/");//注销成功以后来到首页 //1、访问 /logout 表示用户注销,清空session //2、注销成功会返回 /login?logout 页面; //开启记住我功能 http.rememberMe().rememberMeParameter("remeber"); //登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录 //点击注销会删除cookie } //定义认证规则 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //super.configure(auth); auth.inMemoryAuthentication() .withUser("linhongcun").password("123").roles("VIP1","VIP2") .and() .withUser("larger5").password("456").roles("VIP2","VIP3") .and() .withUser("ITAEM").password("789").roles("VIP1","VIP3"); }}

对应的登录界面参数

Insert title here

管理系统


用户名:
密码:
记住我

五、细节(2018.7.14更新)

1、只要在 pom 加入 SpringSecurity 依赖,立刻就登录拦截效果

org.springframework.boot
spring-boot-starter-security

这里写图片描述

默认用户名:user,默认密码会在日志中打出:
这里写图片描述

2、只要在SpringBoot项目中写一个继承 WebSecurityConfigurerAdapter 的空配置类,上述的 alert 形式的登录拦截,则自动变为一个简历的登录页:

这里写图片描述
输入帐号错误也会自动简单地提示用户:
这里写图片描述

转载地址:https://larger5.blog.csdn.net/article/details/79439478 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:使用 EasyUI 写一些后台常用的界面
下一篇:使用 SpringBoot + Ckeditor 富文本编辑器、图片上传

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月08日 00时28分13秒