Spring Security基础入门
创始人
2024-06-01 00:30:55
0

基础概念

什么是认证

认证:用户认证就是判断一个用户的身份身份合法的过程,用户去访问系统资源的时候系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。常见的用户身份认证方式有:用户密码登录,二维码登录,手机短信登录,指纹认证等方式。

其中Spring Security使用的是OAuth2.0认证授权协议。

什么是会话

用户认证通过后,为了避免用户的每次操作都进行认证可将用户的信息保存到会话中,会话就是系统为了保持用户当前用户的登录状态所提供的机制,常见的有基于Session的方式、基于token等方式

基于Session的认证方式

他的交互流程是,用户认证成功后,在服务端生成用户相关的数据保存在session(当前会话中),发给客户端的session_id存放到cookie中,这样用户客户端请求时带上session_id就可以验证服务器是否存在session数据,以此完成用户的合法校验。当用户退出系统或session过期销毁时,客户端的session_id就无效。

方法含义
HttpSession getSession(Boolean create)获取当前HttpSession对象
void setAttribute(String name, Object value)向session中存放对象
void removeAttribute(String name)移除session中的对象
Object getAttribute(String name)从session中获取对象

基于Token方式

他的交互流程是,用户认证成功后,服务端生成一个token发送给客户端,客户端可以放到Cookie中或localStorage等存储中,每次请求时带上token,服务端收到的token通过验证后即可确认用户身份。

对比总结

基于session的认证方式有servlet规范定制的,服务端要存储session信息都要占用内存资源,客户端需要支持Cookie;基于token的方式则一般不需要服务器存储token,并且不限制客户端的存储方式。如今移动互联网时代更多类型的用户端需要接入系统,系统多是采用前后端分离的架构进行实现,所以基于token的方式更合理。

什么是授权

授权:授权是用户认证通过根据用户的权限来控制用户访问资源的过程,拥有资源的访问权限则正常访问,没有权限则拒绝访问。

授权数据模型

授权可简单理解为who对what(which)进行how操作。包括如下:

1、who,即主体,主体一般指用户,也可以是程序,需要访问系统中的资源。

2、what,即资源,如系统菜单,页面,按钮,代码方法,系统商品信息,系统订单等。系统菜单,页面,按钮,代码方法属于系统功能资源,对于web系统每个资源通常对应一个URL,系统商品信息、订单信息等属于实体资源(数据资源),实体资源由资源类型和资源示例组成,比如商品信息为资源类型,商品编号如001为资源的实例

3、how,权限/许可(Permission),规定了用户对资源的操作许可,权限离开资源没有意义,如用户查询权限,用户添加权限,某个代码方法的调用权限,编号为001的用户修改权限等,通过权限可知用户对哪些资源都有哪些许可操作。

主体、资源、权限关系如下图

在这里插入图片描述

企业开发中权限表设计如下

资源(资源ID、资源名称、访问地址)

权限(资源ID、权限标识、权限名称、资源ID)

合并为

权限(权限ID、权限标识、权限名称、资源名称、资源访问地址)

数据模型之间的关系如下:

在这里插入图片描述

RBAC

基于角色访问控制

RBAC基于角色的访问控制(Role-Based Access Control)是按角色进行授权,比如:主体的角色为总经理可以查询企业运营报表,查询员工工资信息等,访问控制流程如下:

yes继续访问no查询工资信息判断主体是否具有总经理角色无法访问处理

基于资源访问控制

RBAC基于资源的访问控制(Resource-Based Access Control)是按资源(或权限)进行授权,比如:用户必须具有查询工资权限才能查询员工工资信息等,访问控制流程如下:

YES继续访问NO查询工资信息判断主体身份具有查询工资的权限无权访问

Spring Security

简介

Spring Security是基于Spring框架,提供一套web应用安全性解决方案。一般来说,web应用的安全性主要包括用户认证(Authentication)和用户授权(Authorization)两部分。这两点是Spring Security的核心功能。

用户认证:是验证某个用户是否为系统中的合法主体,也就是用户能否访问该系统。

用户授权:是验证某个用户是否有权限执行某个操作。在一个系统中,不同的用户所具有的权限不同的。

spring security在项目中进行应用的时候需要登录才能访问接口,否则401.默认用户名:user,密码:每次启动项目后自动生成在日志中输出

引入Maven依赖

org.springframework.bootspring-boot-starter-security

快速开始

在controller中编写对应的java代码

@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("/add")public String add() {return "hello world";}
}

浏览器访问该接口需要输入用户名以及密码,默认用户名是user,密码有控制台日志输出

在这里插入图片描述

postman调用接口,需要在Athorization中输入用户名以及密码,注意Type选择的是Basic Auth

自定义用户名密码

可以在application.yml文件中添加以下配置即可实现

spring:security:user:name: userpassword: pwd123

除此之外还可以实现UserDetailsService接口来实现自定义用户名密码

配置类

@Configuration
public class SecurityConfiguration {@Beanpublic PasswordEncoder getPasswordEncode() {return new BCryptPasswordEncoder();}
}

使用BCryptPasswordEncoder来对密码进行加密

UserDetailsService实现类

@Service
public class UserDetailServiceImpl implements UserDetailsService {@Value("${application.customize.username:admin}")private String customizeUsername;@Value("${application.customize.password:123}")private String customizePassword;@Value("${application.customize.permission.list:admin,normal}")private String permissionList;@Resourceprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 查询用户名是否在数据存在,如果不存在抛出异常if (!customizeUsername.equals(username)) {throw new UsernameNotFoundException("用户名不存在: {}" + username);}// 如果查询到密码的密码进行解析,或者总结把密码传入构造方法String password = passwordEncoder.encode(customizePassword);// 使用AuthorityUtils构造权限列表return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissionList));}
}

注意:最忌代码里写死字符串,尽可能的进行配置

配置文件

application:customize:username: adminpassword: 123permission:list: admin,normal

自定义登录页

在resources文件夹下创建一个static文件夹,同时创建login.htmlerror.htmlmain.html页面。在SecurityConfiguration中继承WebSecurityConfigurerAdapter并重写configure(HttpSecurity httpSecurity)方法

配置类代码如下

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {/*** 将Spring Security默认的登录页面路由到自定义的登录页面.* 由于重写了configure方法,所以需要httpSecurity.authorizeRequests()* .anyRequest().authenticated();来进行所有请求的拦截验证。* 同时需要对login.html进行放行不需要验证。同时对/login请求进行* 拦截,登录成功后会跳转到main.html,登录失败跳转到error.html。* 同时需要关闭csrf防护.* @param httpSecurity* @throws Exception*/@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/login.html").successForwardUrl("/toMain").failureForwardUrl("/toError");httpSecurity.authorizeRequests().antMatchers("/error.html").permitAll().antMatchers("/login.html").permitAll().anyRequest().authenticated();httpSecurity.csrf().disable();}@Beanpublic PasswordEncoder getPasswordEncode() {return new BCryptPasswordEncoder();}
}

注意:在一些前后端分离的项目中,这种配置是无法实现对应的需求

前后端分离自定义登录页

实现接口AuthenticationSuccessHandler并实现接口的中方法,将登录成功后的页面重定向到对应的url

代码示例

public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {private String url;public SecurityAuthenticationSuccessHandler(String url) {this.url = url;}/*** 前后端分离进行重定向* @param httpServletRequest* @param httpServletResponse* @param authentication* @throws IOException* @throws ServletException*/@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,Authentication authentication) throws IOException, ServletException {httpServletResponse.sendRedirect(url);}
}

登录失败就实现接口AuthenticationFailureHandler同时实践其中的方法

代码示例

public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {private String url;public SecurityAuthenticationFailureHandler(String url) {this.url = url;}@Overridepublic void onAuthenticationFailure(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,AuthenticationException e) throws IOException, ServletException {httpServletResponse.sendRedirect(url);}
}

配置类

继承WebSecurityConfigurerAdapter重写configure(HttpSecurity httpSecurity)方法

	@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/login.html")
//                .successForwardUrl("/toMain")// 登陆成功重定向到https://www.baidu.com.successHandler(new SecurityAuthenticationSuccessHandler("https://www.baidu.com"))
//                .failureForwardUrl("/toError");// 登录失败重定向到error.html.failureHandler(new SecurityAuthenticationFailureHandler("/error.html"));httpSecurity.authorizeRequests().antMatchers("/error.html").permitAll().antMatchers("/login.html").permitAll().anyRequest().authenticated();httpSecurity.csrf().disable();}

antMatcher

方法定义

public C antMatchers(String... antPatterns)

参数是不定向参数,每个参数是一个ant表达式,用于匹配url

规则如下:

1、?:匹配一个字符

2、*:匹配0个或多个字符

3、**:匹配0个或多个目录

在实际项目中经常需要放行所有的静态资源,如下

.antMatchers("/js/**","/css/**").permitAll()

还有一种配置方式是只是.js文件都放行

.antMatchers("/**/*.js").permitAll()

regexMatchers

方法定义

public C regexMatchers(String... regexPatterns)

regexMatchers使用的是正则表达式来匹配对应的资源进行权限校验。除此之外还有通过HttpMethod来限定匹配的请求类型,如下

httpSecurity.authorizeRequests().regexMatchers(HttpMethod.POST,"/demo").permitAll()// 所有请求都会被认证.anyRequest().authenticated();

mvcMatchers

方法定义

public ExpressionUrlAuthorizationConfigurer.MvcMatchersAuthorizedUrl mvcMatchers(String... patterns) 

mvcMatchers是用来匹配在配置文件中配置的servlet.path,如下

spring:mvc:servlet:path: /security
httpSecurity.authorizeRequests().mvcMatchers("/hello").servletPath("/security").permitAll()// 所有请求都会被认证.anyRequest().authenticated();

权限控制

权限控制一般需要实现UserDetailsService接口中的loadUserByUsername方法,并在其中设置需要的权限列表,如下

@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 查询用户名是否在数据存在,如果不存在抛出异常if (!customizeUsername.equals(username)) {throw new UsernameNotFoundException("用户名不存在: {}" + username);}// 如果查询到密码的密码进行解析,或者总结把密码传入构造方法String password = passwordEncoder.encode(customizePassword);// 使用AuthorityUtils构造权限列表return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissionList));}

其中permissionList就是权限列表,我使用的是@Value注解进行注入,如下

@Value("${application.customize.permission.list:admin,normal}")
private String permissionList;

配置类

在配置类中继承WebSecurityConfigurerAdapter重写configure方法,可以对其进行权限控制。如admin.html页面只能admin进行访问,那么配置如下:

httpSecurity.authorizeRequests().antMatchers("/admin.html").hasAnyAuthority("admin")// 所有请求都会被认证.anyRequest().authenticated();

其中admin就是在配置类中的权限列表

角色配置

同上编写service实现类并继承UserDetailsService中的loadUserByUsername方法,并配置权限列表,但权限列表配置如下

@Value("${application.customize.permission.list:admin,normal,ROLE_hello}")
private String permissionList;

其中的ROLE_hello就代表角色配置,注意一定要以ROLE_开头,否则Spring Security无法识别。

配置类

 httpSecurity.authorizeRequests().antMatchers("/role.html").hasAnyRole("hello")// 所有请求都会被认证.anyRequest().authenticated();

这里使用的是hasAnyRole进行角色控制

IP地址判断

这里的ip地址指的是用户浏览器输入的地址,比如localhost是本机的地址,也可以是127.0.0.1,也可以是Windows cmd的ipconfig命令的ip地址

配置类

httpSecurity.authorizeRequests().antMatchers("/main.html").hasIpAddress("127.0.0.1")// 所有请求都会被认证.anyRequest().authenticated();

这里配置的127.0.0.1只能在浏览器输入127.0.0.1才有效,输入localhostWindows cmd的ipconfig命令的ip地址均无法访问。

自定义403处理

编写自定义类SecurityAccessDeniedHandler同时实现接口AccessDeniedHandler,实现handle方法

Handler配置

@Component
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {/*** 设置响应的状态码,处理403状态码请求,同时* 设置请求头,并返回json字符串* @param httpServletRequest* @param httpServletResponse* @param e* @throws IOException* @throws ServletException*/@Overridepublic void handle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,AccessDeniedException e) throws IOException, ServletException {httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");@Cleanup PrintWriter writer = httpServletResponse.getWriter();writer.write("{\"status\": \"error\", \"message\": \"权限不足请联系管理员\"}");writer.flush();}
}

编写配置类SecurityConfiguration继承WebSecurityConfigurerAdapter重写configure方法

配置类

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/login.html").successHandler(new SecurityAuthenticationSuccessHandler("/main.html"))// 登录失败重定向到error.html.failureHandler(new SecurityAuthenticationFailureHandler("/error.html"));httpSecurity.authorizeRequests()// 可以写多条对不同的url进行权限认证.antMatchers("/error.html")// 允许访问的权限.permitAll().antMatchers("/login.html").permitAll()// 所有请求都会被认证.anyRequest().authenticated();httpSecurity.csrf().disable();httpSecurity.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);
}

httpSecurity.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);设置自定义的AccessDeniedHandler

基于表达式的访问控制

Access方法使用

登录用户权限判断实际上底层实现都是调用access(表达式)

表达式描述
hasRole(String role)如果当前主体具有指定角色,则返回true。例子:hasRole('admin'),默认情况下,如果提供的角色不以 开头ROLE_,则会添加它。defaultRolePrefix您可以通过修改on来自定义此行为DefaultWebSecurityExpressionHandler
hasAnyRole(String… roles)如果当前主体具有任何提供的角色(以逗号分隔的字符串列表形式给出),则返回true。例子:hasAnyRole('admin', 'user')
hasAuthority(String authority)如果当前委托人具有指定的权限,则返回true
hasAnyAuthority(String… authorities)如果当前主体具有任何提供的权限(以逗号分隔的字符串列表形式给出),则返回true。例子:hasAnyAuthority('read', 'write')
principal允许直接访问代表当前用户的主体对象。
authentication允许直接访问AuthenticationSecurityContext.
permitAll始终评估为true.
denyAll始终评估为false.
isAnonymous()如果当前主体是匿名用户则返回true
isRememberMe()如果当前主体是记住我的用户,则返回true
isAuthenticated()如果用户不是匿名用户则返回true
isFullyAuthenticated()如果用户不是匿名用户且不是记住我的用户,则返回true
hasPermission(Object target, Object permission)如果用户有权访问给定权限的提供目标,则返回true。例如,hasPermission(domainObject, 'read')
hasPermission(Object targetId, String targetType, Object permission)如果用户有权访问给定权限的提供目标,则返回true。例如,hasPermission(1, 'com.example.domain.Message', 'read')

Access自定义权限控制

编写自定义接口以及自定义方法

public interface SecurityService {Boolean hasPermission(HttpServletRequest httpServletRequest,Authentication authentication);
}

编写对应的实现类,注意要注册为Spring的一个Bean

@Service
public class SecurityServiceImpl implements SecurityService {@Overridepublic Boolean hasPermission(HttpServletRequest httpServletRequest,Authentication authentication) {// 获取主体Object object = authentication.getPrincipal();if (object instanceof UserDetails) {UserDetails userDetails = (UserDetails) object;// 获取权限Collection authorities = userDetails.getAuthorities();// 判断权限是否存在对应的URIreturn authorities.contains(new SimpleGrantedAuthority(httpServletRequest.getRequestURI()));}return false;}
}

通过获取主体以及对应的URI来编写对应的权限

通过httpSecurity.authorizeRequests()..anyRequest().access("");方法来调用自定义的SecurityServiceImpl中的自定义hasPermission方法

配置类

    @Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/login.html").successHandler(new SecurityAuthenticationSuccessHandler("/main.html"))// 登录失败重定向到error.html.failureHandler(new SecurityAuthenticationFailureHandler("/error.html"));httpSecurity.authorizeRequests()// 可以写多条对不同的url进行权限认证.antMatchers("/error.html")// 允许访问的权限.permitAll().antMatchers("/login.html").permitAll().anyRequest()// 注意是beanName不是类名.access("@securityServiceImpl.hasPermission(request, authentication)");httpSecurity.csrf().disable();httpSecurity.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);}

自定义配置类继承WebSecurityConfigurerAdapter类重写configure方法。值得注意的是在登录成功后会跳转到main.html页面,但由于自定义的Access中没有main.thml所以登录成功后会403

解决方法

@Service
public class UserDetailServiceImpl implements UserDetailsService {@Value("${application.customize.username:admin}")private String customizeUsername;@Value("${application.customize.password:123}")private String customizePassword;@Value("${application.customize.permission.list:admin,normal,ROLE_hello,/main.html}")private String permissionList;@Resourceprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 查询用户名是否在数据存在,如果不存在抛出异常if (!customizeUsername.equals(username)) {throw new UsernameNotFoundException("用户名不存在: {}" + username);}// 如果查询到密码的密码进行解析,或者总结把密码传入构造方法String password = passwordEncoder.encode(customizePassword);// 使用AuthorityUtils构造权限列表return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissionList));}
}

permissionList加入/main.html即可

基于注解的访问控制

Spring Security中提供了一些访问控制的注解。这些注解都是默认不可用的,需要通过@EnableGlobalMethodSecurity进行开启后使用

如果设置条件允许,程序正常运行,如果不允许会报500,如下

org.springframework.security.access.AccessDeniedException:不允许访问

这些注解可以写到Service接口或方法上也可以写到ControllerController的方法上。通常情况下都是卸载控制器方法上。控制器接口URL是否允许被访问

@Secured注解

@Secured是专门用于判断是否具有角色的。能写在方法或类上。参数以ROLE_开头

启动类添加@EnableGlobalMethodSecurity(securedEnabled = true)

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityStudyApplication {public static void main(String[] args) {SpringApplication.run(SpringSecurityStudyApplication.class, args);}
}

注意这里的配置类不能配置successHandler以及failureHandler

接口Controller添加@Secured

@Secured("ROLE_hello")
@PostMapping("/toMain")
public String toMain() {return "redirect:main.html";
}

即角色为hello的用户才可以访问该接口,角色由实现接口UserDetailsService重写loadUserByUsername方法中即可实现

@PreAuthorize以及@PostAuthorize

@PreAuthorize@PostAuthorize都是方法或类级别的注解

@PreAuthorize:表示访问方法或类在执行之前判断权限,大多数情况下都是使用这个注解,注解的参数和access()方法参数取值相同,都是权限表达式

@PostAuthorize:表示方法或类执行结束后判断权限,该注解很少被使用

启动类添加@EnableGlobalMethodSecurity(prePostEnabled = true),接口Controller添加@PreAuthorize

@PreAuthorize("hasRole('world')")
@PostMapping("/toMain")
public String toMain() {return "redirect:main.html";
}

注意:同样在配置类中的configure方法不能配置successHandler以及failureHandler

RememberMe

Spring Security中的RememberMe,用户只需要在登录时添加remember me复选框,取值为true,即可将用户信息存储到数据库中,以后就可以不登录访问了

添加依赖

org.mybatis.spring.bootmybatis-spring-boot-starter2.1.3

mysqlmysql-connector-java

application.yml配置

spring:datasource:url: jdbc:mysql://localhost:3306/security?userUnicode=true&charseterEncoding=UTF-8&serverTimezone=Asia/Shanghaidriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456

注入PersistentTokenRepository

@Bean
public PersistentTokenRepository getPersistentTokenRepository() {JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();jdbcTokenRepository.setDataSource(dataSource);// 自动建表,第一次启动需要,第二次启动需要启动//        jdbcTokenRepository.setCreateTableOnStartup(true);return jdbcTokenRepository;
}

继承WebSecurityConfigurerAdapter类,重写configure方法的配置如下:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/login.html").successForwardUrl("/toMain").failureForwardUrl("/toError");httpSecurity.authorizeRequests()// 可以写多条对不同的url进行权限认证.antMatchers("/error.html")// 允许访问的权限.permitAll().antMatchers("/login.html").permitAll().anyRequest().authenticated();httpSecurity.csrf().disable();httpSecurity.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);httpSecurity.rememberMe().userDetailsService(userDetailServiceImpl)// 持久层对象.tokenRepository(persistentTokenRepository);
}

前端HTML页面修改如下

用户名:
密码:
记住我

注意:这里的name一定是remember-mevaluetrue。登录后在数据库的表里会发现录入有一条数据,该失效时间默认是两周,修改默认失效时间,以及remember-me的别名如下:

httpSecurity.rememberMe()// 失效时间,单位:秒.tokenValiditySeconds(60)// 设置remember-me的别名.rememberMeParameter("remember-me-alias").userDetailsService(userDetailServiceImpl)// 持久层对象.tokenRepository(persistentTokenRepository);

CSRF

CSRF(Cross-site request forgery)跨站请求伪造,也称为"OneClick Attack"或者Session Riding。通过伪造用户请求访问受信任站点的非法请求

跨域:只要网络协议、IP地址、端口中任何一个不相同就是跨域请求

客户端与服务进行交互时,由于Http协议是无状态的协议,所以引入了Cookie进行记录客户端身份。在Cookie中会存放Session ID用来识别客户端的身份。在跨域情况下,session id可能被第三方恶意劫持,通过这个Session id向服务器发起请求时,服务端会认为该请求是合法的,可能发生很多意想不到的事情。

Spring Security中的CSRF

从Spring Security4开始CSRF防护默认开启,默认会拦截请求。进行CSRF处理。CSRF为了保证不是其他第三方网站访问,要求访问时同时携带参数名为_csrf值为token(token在服务器产生的)的内容,如果token和服务器的token匹配成功,则访问成功。

示例

引入thymeleaf依赖

org.springframework.bootspring-boot-starter-thymeleaf3.0.4

org.thymeleafthymeleaf-spring5

org.thymeleaf.extrasthymeleaf-extras-java8time

配置类

配置类继承WebSecurityConfigurerAdapter重写configure方法,并放行对应的请求

protected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.formLogin().loginProcessingUrl("/login").loginPage("/showLogin").successForwardUrl("/toMain").failureForwardUrl("/toError");httpSecurity.authorizeRequests()// 可以写多条对不同的url进行权限认证.antMatchers("/error.html")// 允许访问的权限.permitAll().antMatchers("/showLogin").permitAll()// 所有请求都会被认证.anyRequest().authenticated();//        httpSecurity.csrf().disable();httpSecurity.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);httpSecurity.rememberMe()// 失效时间,单位:秒.tokenValiditySeconds(60).userDetailsService(userDetailServiceImpl)// 持久层对象.tokenRepository(persistentTokenRepository);httpSecurity.logout().logoutSuccessUrl("/logout");}

关闭Spring Security CSRF

Controller跳转到视图

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

该视图跳转到resources/templates/login.html下的页面

thymeleaf页面

用户名:
密码:
记住我

是表单提交时携带_csrf

相关内容

热门资讯

迷你退出安卓系统了吗,转型新篇... 最近有没有发现你的手机上那个可爱的迷你退出图标突然不见了?别急,让我来给你揭秘迷你退出安卓系统了吗的...
华为优先使用安卓系统,打造自主... 你知道吗?最近科技圈里有个大动作,那就是华为宣布优先使用安卓系统。这可不是一个简单的决定,它背后可是...
安卓系统隐藏了设置,隐藏设置功... 你知道吗?安卓系统这个大宝藏里,竟然隐藏着一些不为人知的设置!是不是听起来就有点小激动呢?别急,今天...
反渣恋爱系统安卓,收获真爱 你有没有听说过那个神奇的“反渣恋爱系统安卓”呢?最近,这款应用在网络上可是火得一塌糊涂,不少单身狗都...
安卓出厂系统能升级,探索无限可... 你知道吗?现在这个时代,手机更新换代的速度简直就像坐上了火箭!而说到手机,安卓系统可是占据了半壁江山...
老安卓刷机系统,从入门到精通 你有没有想过,你的老安卓手机其实还有大大的潜力呢?没错,就是那个陪伴你多年的老安卓,它可不是只能用来...
安卓粉ios系统app,兼容性... 你有没有发现,身边的朋友圈里,安卓粉和iOS系统粉总是争论不休?今天,咱们就来聊聊这个话题,看看安卓...
安卓系统语言下载,探索安卓系统... 你有没有想过,你的安卓手机是不是该换换口味了?没错,就是语言!想象如果你能轻松切换到自己喜欢的语言,...
安卓共有多少种系统,究竟有多少... 你有没有想过,安卓这个我们每天不离手的操作系统,竟然有那么多不同的版本呢?没错,安卓系统就像一个大家...
安卓系统怎么播放swf,And... 你有没有遇到过这种情况:手里拿着一部安卓手机,想看一个SWF格式的动画,结果发现怎么也打不开?别急,...
pos机安卓系统跟win系统,... 你有没有想过,那些在我们生活中默默无闻的POS机,竟然也有自己的操作系统呢?没错,就是安卓系统和Wi...
俄罗斯封禁安卓系统,本土化替代... 俄罗斯封禁安卓系统的背后:技术、经济与社会的影响在数字化浪潮席卷全球的今天,智能手机已成为我们生活中...
安卓系统总是弹出权限,安卓系统... 手机里的安卓系统是不是总爱和你玩捉迷藏?每次打开一个应用,它就跳出来问你要不要给它开权限,真是让人又...
安卓系统测血氧,便捷健康生活新... 你知道吗?现在科技的发展真是让人惊叹不已!手机,这个我们日常生活中不可或缺的小玩意儿,竟然也能变身成...
蓝光助手安卓系统的,深度解析与... 你有没有发现,现在手机屏幕越来越大,看视频、刷抖音,简直爽到飞起!但是,你知道吗?长时间盯着屏幕,尤...
安卓系统如何隐藏提示,Andr... 你是不是也和我一样,在使用安卓手机的时候,总是被那些弹出来的提示信息打扰到?别急,今天就来教你怎么巧...
安卓6.0系统如何分区,And... 你有没有想过,你的安卓手机里那些神秘的分区到底是怎么来的?别急,今天就来给你揭秘安卓6.0系统如何分...
安卓系统图片怎么涂鸦,指尖上的... 你有没有想过,在安卓系统的手机上,那些单调的图片也能变得生动有趣呢?没错,就是涂鸦!今天,就让我来带...
安卓系统40g,40GB存储空... 你有没有发现,最近你的安卓手机突然变得有点“胖”了呢?没错,就是那个传说中的40G!别急,别慌,今天...
安卓5.0系统怎么重置,轻松实... 手机用久了是不是感觉卡得要命?别急,今天就来教你怎么给安卓5.0系统来个彻底的重置,让它焕发新生!一...