服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解spring security之httpSecurity使用示例

详解spring security之httpSecurity使用示例

2021-05-26 13:40一天不进步,就是退步 Java教程

这篇文章主要介绍了详解spring security之httpSecurity使用示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

httpsecurity

类似于spring security的xml配置文件命名空间配置中的<http>元素。它允许对特定的http请求基于安全考虑进行配置。默认情况下,适用于所有的请求,但可以使用requestmatcher(requestmatcher)或者其它相似的方法进行限制。

使用示例:

最基本的基于表单的配置如下。该配置将所有的url访问权限设定为角色名称为"role_user".同时也定义了内存认证模式:使用用户名"user"和密码“password”,角色"role_user"来认证。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@configuration
@enablewebsecurity
public class formloginsecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   .formlogin();
 }
 
 @override
 protected void configure(authenticationmanagerbuilder auth) throws exception {
  auth
   .inmemoryauthentication()
    .withuser("user")
      .password("password")
      .roles("user");
 }
}

 配置基于openid的认证方式

 basic示例,不使用attribute exchange

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  @configuration
@enablewebsecurity
public class openidloginconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   .openidlogin()
    .permitall();
 }
 
 @override
 protected void configure(authenticationmanagerbuilder auth) throws exception {
  auth
    .inmemoryauthentication()
     // the username must match the openid of the user you are
     // logging in with
     .withuser("https://www.google.com/accounts/o8/id?id=lmkcn9xzpdsxvwg7pjymudgnndasfmobnkcrpawu")
      .password("password")
      .roles("user");
 }
}

下面展示一个更高级的示例,使用attribute exchange

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@configuration
@enablewebsecurity
public class openidloginconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   .openidlogin()
    .loginpage("/login")
    .permitall()
    .authenticationuserdetailsservice(new autoprovisioninguserdetailsservice())
     .attributeexchange("https://www.google.com/.")
      .attribute("email")
       .type("http://axschema.org/contact/email")
       .required(true)
       .and()
      .attribute("firstname")
       .type("http://axschema.org/nameperson/first")
       .required(true)
       .and()
      .attribute("lastname")
       .type("http://axschema.org/nameperson/last")
       .required(true)
       .and()
      .and()
     .attributeexchange(".yahoo.com.")
      .attribute("email")
       .type("http://schema.openid.net/contact/email")
       .required(true)
       .and()
      .attribute("fullname")
       .type("http://axschema.org/nameperson")
       .required(true)
       .and()
      .and()
     .attributeexchange(".myopenid.com.")
      .attribute("email")
       .type("http://schema.openid.net/contact/email")
       .required(true)
       .and()
      .attribute("fullname")
       .type("http://schema.openid.net/nameperson")
       .required(true);
 }
}
 
public class autoprovisioninguserdetailsservice implements
  authenticationuserdetailsservice<openidauthenticationtoken> {
 public userdetails loaduserdetails(openidauthenticationtoken token) throws usernamenotfoundexception {
  return new user(token.getname(), "notused", authorityutils.createauthoritylist("role_user"));
 }
}

增加响应安全报文头

默认情况下当使用websecuirtyconfigadapter的默认构造函数时激活。

仅触发headers()方法而不触发其它方法或者接受websecurityconfigureeradater默认的,等同于:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@configuration
  @enablewebsecurity
  public class csrfsecurityconfig extends websecurityconfigureradapter {
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .headers()
      .contenttypeoptions();
      .xssprotection()
      .cachecontrol()
      .httpstricttransportsecurity()
      .frameoptions()
      .and()
     ...;
   }
  }

取消安全报文头,如下:

?
1
2
3
4
5
6
7
8
9
10
11
@configuration
@enablewebsecurity
public class csrfsecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .headers().disable()
   ...;
 }
}

使用部分安全报文头

触发headers()方法的返回结果,例如,只使用headerconfigurer的cachecontroll()方法和headersconfigurer的frameoptions()方法.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@configuration
@enablewebsecurity
public class csrfsecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .headers()
    .cachecontrol()
    .frameoptions()
    .and()
   ...;
 }
}

配置session管理

下面的配置展示了只允许认证用户在同一时间只有一个实例是如何配置的。若一个用户使用用户名为"user"认证并且没有退出,同一个名为“user”的试图再次认证时,第一个用户的session将会强制销毁,并设置到"/login?expired"的url。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@configuration
@enablewebsecurity
public class sessionmanagementsecurityconfig extends
  websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .authorizerequests()
    .anyrequest().hasrole("user")
    .and()
   .formlogin()
    .permitall()
    .and()
   .sessionmanagement()
    .maximumsessions(1)
    .expiredurl("/login?expired");
 }
 
 @override
 protected void configure(authenticationmanagerbuilder auth)
   throws exception {
  auth.
   inmemoryauthentication()
    .withuser("user")
     .password("password")
     .roles("user");
 }
}

当使用sessionmanagementconfigurer的maximumsessio(int)时不用忘记为应用配置httpsessioneventpublisher,这样能保证过期的session能够被清除。

在web.xml中可以这样配置:

?
1
2
3
<listener>
 <listener-class>org.springframework.security.web.session.httpsessioneventpublisher</listener-class>;
</listener>

配置portmapper

允许配置一个从httpsecurity的getsharedobject(class)方法中获取的portmapper。当http请求跳转到https或者https请求跳转到http请求时(例如我们和requireschanenl一起使用时),别的提供的securityconfigurer对象使用p诶账户的portmapper作为默认的portmapper。默认情况下,spring security使用portmapperimpl来映射http端口8080到https端口8443,并且将http端口的80映射到https的端口443.

配置示例如下,下面的配置将确保在spring security中的http请求端口9090跳转到https端口9443 并且将http端口80跳转到https443端口。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@configuration
@enablewebsecurity
public class portmappersecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   .formlogin()
    .permitall()
    .and()
    // example portmapper() configuration
    .portmapper()
     .http(9090).mapsto(9443)
     .http(80).mapsto(443);
 }
 
 @override
 protected void configure(authenticationmanagerbuilder auth) throws exception {
  auth
   .inmemoryauthentication()
    .withuser("user")
     .password("password")
     .roles("user");
 }
}

配置基于容器的预认证

在这个场景中,servlet容器管理认证。

配置示例:

下面的配置使用httpservletrequest中的principal,若用户的角色是“role_user”或者"role_admin",将会返回authentication结果。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@configuration
 @enablewebsecurity
 public class jeesecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/").hasrole("user")
     .and()
    // example jee() configuration
    .jee()
     .mappableroles("role_user", "role_admin");
  }
 }

开发者希望使用基于容器预认证时,需要在web.xml中配置安全限制。例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<login-config>
  <auth-method>form</auth-method>
  <form-login-config>
   <form-login-page>/login</form-login-page>
   <form-error-page>/login?error</form-error-page>
  </form-login-config>
 </login-config>
 
 <security-role>
  <role-name>role_user</role-name>
 </security-role>
 <security-constraint>
  <web-resource-collection>
  <web-resource-name>public</web-resource-name>
   <description>matches unconstrained pages</description>
   <url-pattern>/login</url-pattern>
   <url-pattern>/logout</url-pattern>
   <url-pattern>/resources/</url-pattern>
  </web-resource-collection>
 </security-constraint>
 <security-constraint>
  <web-resource-collection>
   <web-resource-name>secured areas</web-resource-name>
   <url-pattern>/</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <role-name>role_user</role-name>
  </auth-constraint>
 </security-constraint>

配置基于x509的预认证

配置示例,下面的配置试图从x509证书中提取用户名,注意,为完成这个工作,客户端请求证书需要配置到servlet容器中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@configuration
@enablewebsecurity
public class x509securityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   // example x509() configuration
   .x509();
 }
}

配置remember-me服务

配置示例,下面的配置展示了如何允许基于token的remember-me的认证。若http参数中包含一个名为“remember-me”的参数,不管session是否过期,用户记录将会被记保存下来。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@configuration
 @enablewebsecurity
 public class remembermesecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
       .password("password")
       .roles("user");
  }
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/").hasrole("user")
     .and()
    .formlogin()
     .permitall()
     .and()
    // example remember me configuration
    .rememberme();
  }
 }

限制httpservletrequest的请求访问

配置示例,最基本的示例是配置所有的url访问都需要角色"role_user".下面的配置要求每一个url的访问都需要认证,并且授权访问权限给用户"admin"和"user".

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@configuration
  @enablewebsecurity
  public class authorizeurlssecurityconfig extends websecurityconfigureradapter {
  
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .authorizerequests()
      .antmatchers("/").hasrole("user")
      .and()
     .formlogin();
   }
  
   @override
   protected void configure(authenticationmanagerbuilder auth)
     throws exception {
    auth
     .inmemoryauthentication()
      .withuser("user")
        .password("password")
        .roles("user")
        .and()
      .withuser("adminr")
        .password("password")
        .roles("admin","user");
   }
  }

同样,也可以配置多个url。下面的配置要求以/admin/开始的url访问权限为“admin”用户。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@configuration
  @enablewebsecurity
  public class authorizeurlssecurityconfig extends websecurityconfigureradapter {
  
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .authorizerequests()
      .antmatchers("/admin/**").hasrole("admin")
      .antmatchers("/**").hasrole("user")
      .and()
     .formlogin();
   }
  
   @override
   protected void configure(authenticationmanagerbuilder auth)
     throws exception {
    auth
     .inmemoryauthentication()
      .withuser("user")
        .password("password")
        .roles("user")
        .and()
      .withuser("adminr")
        .password("password")
        .roles("admin","user");
   }
  }

注意:匹配起效是按照顺序来的。因此如果下面的配置是无效的,因为满足第一个规则后将不会检查第二条规则:

?
1
2
3
4
http
 .authorizerequests()
  .antmatchers("/**").hasrole("user")
  .antmatchers("/admin/**").hasrole("admin")

增加csrf支持

默认情况下,当使用websecurityconfigureradapter时的默认构造方法时csrf是激活的。你可以使用如下方法关闭它:

?
1
2
3
4
5
6
7
8
9
10
11
@configuration
@enablewebsecurity
public class csrfsecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .csrf().disable()
   ...;
 }
}

增加logout支持

默认支持,当使用websecurityconfigureradapter时logout是支持的。当用户发出“/logout”请求时,系统将会销毁session并且清空配置的rememberme()认证,然后清除securitycontextholder,最后跳向logout成功页面或者登陆页面。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@configuration
 @enablewebsecurity
 public class logoutsecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/").hasrole("user")
     .and()
    .formlogin()
     .and()
    // sample logout customization
    .logout()
     .logout()
      .deletecookies("remove")
      .invalidatehttpsession(false)
      .logouturl("/custom-logout")
      .logoutsuccessurl("/logout-success");
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
       .password("password")
       .roles("user");
  }
 }

匿名用户控制

使用websecurityconfigureradapter时自动绑定。默认情况下,匿名用户有一个anonymousauthenticationtoken标示,包含角色"role_anonymous"。

下面的配置展示了如何指定匿名用户应该包含"role_anon".

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  @configuration
@enablewebsecurity
public class anononymoussecurityconfig extends websecurityconfigureradapter {
 
 @override
 protected void configure(httpsecurity http) throws exception {
  http
   .authorizerequests()
    .antmatchers("/").hasrole("user")
    .and()
   .formlogin()
    .and()
   // sample anonymous customization
   .anonymous()
    .authorities("role_anon");
 }
 
 @override
 protected void configure(authenticationmanagerbuilder auth)
   throws exception {
  auth
   .inmemoryauthentication()
    .withuser("user")
      .password("password")
      .roles("user");
 }
}

基于表单的认证

若formloginconfigurer的loginpage(string)没有指定,将会产生一个默认的login页面。

示例配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@configuration
  @enablewebsecurity
  public class formloginsecurityconfig extends websecurityconfigureradapter {
  
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .authorizerequests()
      .antmatchers("/**").hasrole("user")
      .and()
     .formlogin();
   }
  
   @override
   protected void configure(authenticationmanagerbuilder auth)
     throws exception {
    auth
     .inmemoryauthentication()
      .withuser("user")
        .password("password")
        .roles("user");
   }
  }

下面的示例展示了自定义的表单认证:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@configuration
 @enablewebsecurity
 public class formloginsecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/").hasrole("user")
     .and()
    .formlogin()
      .usernameparameter("j_username") // default is username
      .passwordparameter("j_password") // default is password
      .loginpage("/authentication/login") // default is /login with an http get
      .failureurl("/authentication/login?failed") // default is /login?error
      .loginprocessingurl("/authentication/login/process"); // default is /login with an http post
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
       .password("password")
       .roles("user");
  }
 }

配置安全通道

为使配置生效,需至少配置一个通道的映射。

配置示例:

下面例子展示了如何将每个请求都使用https通道。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@configuration
 @enablewebsecurity
 public class channelsecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/**").hasrole("user")
     .and()
    .formlogin()
     .and()
    .channelsecurity()
     .anyrequest().requiressecure();
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
       .password("password")
       .roles("user");
  }
 }

配置http 基本认证

配置示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@configuration
 @enablewebsecurity
 public class httpbasicsecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .authorizerequests()
     .antmatchers("/**").hasrole("user").and()
     .httpbasic();
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
      .password("password")
      .roles("user");
  }
 }

配置要触发的httprequest

重写requestmatcher方法、antmatcher()z、regexmatcher()等。

配置示例

下面的配置使httpsecurity接收以"/api/","/oauth/"开头请求。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@configuration
 @enablewebsecurity
 public class requestmatcherssecurityconfig extends websecurityconfigureradapter {
 
  @override
  protected void configure(httpsecurity http) throws exception {
   http
    .requestmatchers()
     .antmatchers("/api/**","/oauth/**")
     .and()
    .authorizerequests()
     .antmatchers("/**").hasrole("user").and()
     .httpbasic();
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth)
    throws exception {
   auth
    .inmemoryauthentication()
     .withuser("user")
      .password("password")
      .roles("user");
  }
 }

下面的配置和上面的相同:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@configuration
  @enablewebsecurity
  public class requestmatcherssecurityconfig extends websecurityconfigureradapter {
  
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .requestmatchers()
      .antmatchers("/api/**")
      .antmatchers("/oauth/**")
      .and()
     .authorizerequests()
      .antmatchers("/**").hasrole("user").and()
      .httpbasic();
   }
  
   @override
   protected void configure(authenticationmanagerbuilder auth)
     throws exception {
    auth
     .inmemoryauthentication()
      .withuser("user")
       .password("password")
       .roles("user");
   }
  }

同样也可以这样使用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@configuration
  @enablewebsecurity
  public class requestmatcherssecurityconfig extends websecurityconfigureradapter {
  
   @override
   protected void configure(httpsecurity http) throws exception {
    http
     .requestmatchers()
      .antmatchers("/api/**")
      .and()
     .requestmatchers()
      .antmatchers("/oauth/**")
      .and()
     .authorizerequests()
      .antmatchers("/**").hasrole("user").and()
      .httpbasic();
   }
  
   @override
   protected void configure(authenticationmanagerbuilder auth)
     throws exception {
    auth
     .inmemoryauthentication()
      .withuser("user")
       .password("password")
       .roles("user");
   }
  }

小结:

本文是从httpsecurity代码中整理得来的,有助于对spring security的全面理解。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/davidwang456/p/4549344.html

延伸 · 阅读

精彩推荐