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和安卓的操作系统,还有个神秘的鸿蒙系统?今天,咱们就来聊...
哪个安卓机系统好用,探索安卓系... 你有没有想过,手机里的安卓系统就像是个大厨,不同的系统就像不同的烹饪手法,有的让你吃得津津有味,有的...
安卓如何控制苹果系统,从安卓到... 你知道吗?在这个科技飞速发展的时代,安卓和苹果两大操作系统之间的较量从未停歇。虽然它们各自有着忠实的...
安卓原生系统文件夹,安卓原生系... 你有没有发现,每次打开安卓手机,里面那些文件夹就像是一个个神秘的宝箱,里面藏着各种各样的宝贝?今天,...
基于安卓系统的游戏开发,从入门... 你有没有想过,为什么安卓手机上的游戏总是那么吸引人?是不是因为它们就像是你身边的好朋友,随时随地都能...
安卓系统怎样装驱动精灵,安卓系... 你那安卓设备是不是突然间有点儿不给力了?别急,今天就来手把手教你如何给安卓系统装上驱动精灵,让你的设...
如何本地安装安卓系统包,详细步... 你有没有想过,把安卓系统装在你的电脑上,是不是就像给电脑穿上了时尚的新衣?想象你可以在电脑上直接玩手...
安卓12卡刷系统教程,体验全新... 你有没有发现,你的安卓手机最近有点儿不给力了?运行速度慢得像蜗牛,是不是也想给它来个“换血大法”,让...
安卓系统无法打开swf文件,安... 最近是不是发现你的安卓手机有点儿不给力?打开SWF文件时,是不是总是出现“无法打开”的尴尬局面?别急...
鸿蒙系统依赖于安卓系统吗,独立... 你有没有想过,我们手机里的那个鸿蒙系统,它是不是真的完全独立于安卓系统呢?这个问题,估计不少手机控都...
适合安卓系统的图片软件,精选图... 手机里堆满了各种美美的照片,是不是觉得找起来有点头疼呢?别急,今天就来给你安利几款超级适合安卓系统的...
阴阳师安卓系统典藏,探寻阴阳师... 亲爱的阴阳师们,你是否在安卓系统上玩得如痴如醉,对那些精美的典藏式神们垂涎欲滴?今天,就让我带你深入...
安卓系统有碎片化缺点,系统优化... 你知道吗?在手机江湖里,安卓系统可是个响当当的大侠。它那开放、自由的个性,让无数手机厂商和开发者都为...
安卓4系统手机微信,功能解析与... 你有没有发现,现在市面上还有很多安卓4系统的手机在使用呢?尤其是那些喜欢微信的朋友们,这款手机简直就...
鸿蒙系统是安卓的盗版,从安卓“... 你知道吗?最近在科技圈里,关于鸿蒙系统的讨论可是热闹非凡呢!有人说是安卓的盗版,有人则认为这是华为的...
安卓系统怎么剪辑音乐,轻松打造... 你是不是也和我一样,手机里存了超多好听的歌,但是有时候想给它们来个变身,变成一段专属的旋律呢?别急,...
怎么把安卓手机系统变为pc系统... 你有没有想过,把你的安卓手机变成一台PC呢?听起来是不是有点酷炫?想象你可以在手机上玩电脑游戏,或者...
手机怎么装安卓11系统,手机安... 你有没有想过,让你的手机也来个“青春焕发”,升级一下系统呢?没错,就是安卓11系统!这个新系统不仅带...
安卓系统如何拼网络,构建高效连... 你有没有想过,你的安卓手机是怎么和网络“谈恋爱”的呢?没错,就是拼网络!今天,就让我带你一探究竟,看...
安卓系统怎么看小说,轻松畅享电... 你有没有发现,手机里装了那么多应用,最离不开的竟然是那个小小的小说阅读器?没错,就是安卓系统上的小说...