1.自定义认证前端页面
1-前端代码
login.html
(2 KB)
拷贝上述路径到下述位置,注意没有对应文件夹则需要手动创建
2-后端代码
1.定义接口
这里我们在原来的基础之上,继续追加一个即可,我就简单的添加一下哥哥的地址吧
2.创建配置类
Java
运行代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.yzxb.SpringSecurity.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 SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated().and().formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/doLogin")
.defaultSuccessUrl("/demo/index")
.failureUrl("/login.html")
.usernameParameter("uname")
.passwordParameter("passwd")
.permitAll()
.and()
.csrf().disable();
}
}
这个配置类非常重要,笔者带领大家单独解释一下。
(1)configure是一个链式配置,这里不用链式配置也可以,那就每一个属性设置后再http.重新开始写
(2)authenticated()表示开始权限配置,.anyRequest().authenticated()表示所有请求都需认证才可访问
(3)and()会返回HttpSecurityBuilder对象的一个子类(实际就是HttpSecurity),所以and方法相当于又回到HttpSecurity,重新开启新一轮的配置
(4)formLogin()表示开启表单登录配置,loginPage("")用来配置登录页面地址;loginProcessingUrl("")用来配置登录接口地址;defaultSuccessUrl("")用来表示登陆成功后的跳转地址;failureUrl("")表示登录失败后的跳转地址;usernameParameter、passwordParameter表示登录用户名、密码参数名称;permitAll()表示跟登录相关的接口和页面不做拦截,直接通过。
(5)csrf().disable()表示禁用CSRF防御功能,SpringSecurity自带CSRF机制,这里为了测试方便临时关闭。
3-启动验证
启动工程后访问地址:http://localhost:8080/demo/index
页面自动跳转至我们自己创建的登录页面,用户名:user,密码:参照idea控制台打印
输入用户名、密码后跳转返回我们的接口信息