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

相关内容

热门资讯

安卓10系统省电不,安卓10系... 你有没有发现,自从升级到安卓10系统,手机续航能力好像大不如前了?别急,今天就来给你揭秘安卓10系统...
cm14安卓系统,深度定制与极... 你有没有发现,你的安卓手机最近是不是有点不一样了?是不是觉得系统运行得更加流畅,界面也更加美观了呢?...
平板安卓系统咋样升级,轻松实现... 你那平板安卓系统是不是有点儿卡,想给它来个升级大变身?别急,让我来给你详细说说平板安卓系统咋样升级,...
安卓原系统在哪下载,探索纯净体... 你有没有想过,为什么安卓手机那么受欢迎?那是因为它的系统——安卓原系统,它就像是一个充满活力的魔法师...
安卓系统procreate绘图... 你有没有发现,现在手机上画画变得越来越流行了?尤其是用安卓系统的手机,搭配上那个神奇的Procrea...
电视的安卓系统吗,探索安卓电视... 你有没有想过,家里的电视是不是也在悄悄地使用安卓系统呢?没错,就是那个我们手机上常用的安卓系统。今天...
苹果手机系统操作安卓,苹果iO... 你有没有发现,身边的朋友换手机的时候,总是对苹果和安卓两大阵营争论不休?今天,咱们就来聊聊这个话题,...
安卓系统换成苹果键盘,键盘切换... 你知道吗?最近我在想,要是把安卓系统的手机换成苹果的键盘,那会是怎样的体验呢?想象那是不是就像是在安...
小米操作系统跟安卓系统,深度解... 亲爱的读者们,你是否曾在手机上看到过“小米操作系统”和“安卓系统”这两个词,然后好奇它们之间有什么区...
miui算是安卓系统吗,深度定... 亲爱的读者,你是否曾在手机上看到过“MIUI”这个词,然后好奇地问自己:“这玩意儿是安卓系统吗?”今...
安卓系统开机启动应用,打造个性... 你有没有发现,每次打开安卓手机,那些应用就像小精灵一样,迫不及待地跳出来和你打招呼?没错,这就是安卓...
小米搭载安卓11系统,畅享智能... 你知道吗?最近小米的新机子可是火得一塌糊涂,而且听说它搭载了安卓11系统,这可真是让人眼前一亮呢!想...
安卓2.35系统软件,功能升级... 你知道吗?最近在安卓系统界,有个小家伙引起了不小的关注,它就是安卓2.35系统软件。这可不是什么新玩...
安卓系统设置来电拦截,轻松实现... 手机里总是突然响起那些不期而至的来电,有时候真是让人头疼不已。是不是你也想摆脱这种烦恼,让自己的手机...
专刷安卓手机系统,安卓手机系统... 你有没有想过,你的安卓手机系统是不是已经有点儿“老态龙钟”了呢?别急,别急,今天就来给你揭秘如何让你...
安卓系统照片储存位置,照片存储... 手机里的照片可是我们珍贵的回忆啊!但是,你知道吗?这些照片在安卓系统里藏得可深了呢!今天,就让我带你...
华为鸿蒙系统不如安卓,挑战安卓... 你有没有发现,最近手机圈里又掀起了一股热议?没错,就是华为鸿蒙系统和安卓系统的较量。很多人都在问,华...
安卓系统陌生电话群发,揭秘安卓... 你有没有遇到过这种情况?手机里突然冒出好多陌生的电话号码,而且还是一个接一个地打过来,简直让人摸不着...
ios 系统 安卓系统对比度,... 你有没有发现,手机的世界里,iOS系统和安卓系统就像是一对双胞胎,长得差不多,但细节上却各有各的特色...
安卓只恢复系统应用,重拾系统流... 你有没有遇到过这种情况?手机突然卡顿,或者某个应用突然罢工,你一气之下,直接开启了“恢复出厂设置”大...