SpringBoot整合SpringSecurity系列(7)-内置访问控制

811 阅读1分钟

一、内置访问控制

  1. Spring Security匹配了 URL 后调用了 permitAll() 表示不需要认证,同时也提供了多种内置控制方式
  2. 访问控制信息在类ExpressionUrlAuthorizationConfigurer中配置
    • org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer

二、内置控制方法

2.1 permitAll()

  1. permitAll()表示所匹配的 URL 任何人都允许访问
/**
 * Specify that URLs are allowed by anyone.
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 */
public ExpressionInterceptUrlRegistry permitAll() {
	return access(permitAll);
}

2.2 authenticated()

  1. authenticated()表示所匹配的 URL 都需要被认证才能访问
/**
 * Specify that URLs are allowed by any authenticated user.
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 */
public ExpressionInterceptUrlRegistry authenticated() {
	return access(authenticated);
}

2.3 anonymous()

  1. anonymous()表示可以匿名访问匹配的URL,和permitAll()效果类似,只是设置为 anonymous()的 url会执行 filter 链
/**
 * Specify that URLs are allowed by anonymous users.
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 */
public ExpressionInterceptUrlRegistry anonymous() {
	return access(anonymous);
}
  1. 指定资源可以匿名访问
.antMatchers("/index.md").anonymous()

2.4 denyAll()

  1. denyAll()表示所匹配的 URL 都不允许被访问
/**
 * Specify that URLs are not allowed by anyone.
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 */
public ExpressionInterceptUrlRegistry denyAll() {
	return access(denyAll);
}
  1. 指定资源禁止访问
.antMatchers("/private.key").denyAll()
  1. 指定之后登录后访问资源将会提示403

2.5 rememberMe()

  1. 被“remember me”的用户允许访问
/**
 * Specify that URLs are allowed by users that have been remembered.
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 * @see RememberMeConfigurer
 */
public ExpressionInterceptUrlRegistry rememberMe() {
	return access(rememberMe);
}
  1. 配置remember资源
.antMatchers("/remember.conf").rememberMe()

2.6 fullyAuthenticated

  1. 非remember me验证登录的用户才可访问
/**
 * Specify that URLs are allowed by users who have authenticated and were not
 * "remembered".
 * @return the {@link ExpressionUrlAuthorizationConfigurer} for further
 * customization
 * @see RememberMeConfigurer
 */
public ExpressionInterceptUrlRegistry fullyAuthenticated() {
	return access(fullyAuthenticated);
}