---
# System prepended metadata

title: Sping Security Config
tags: [Spring]

---

# Sping Security Config 
## HttpSecurity, WebSecurity and AuthenticationManagerBuilder 差異
### 官方文件範例 CustomWebSecurityConfigurerAdapter.java 
```java
@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends
   WebSecurityConfigurerAdapter {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user")  // #1
          .password("password")
          .roles("USER")
          .and()
        .withUser("admin") // #2
          .password("password")
          .roles("ADMIN","USER");
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
         .antMatchers("/resources/**"); // #3
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeUrls()
        .antMatchers("/signup","/about").permitAll() // #4
        .antMatchers("/admin/**").hasRole("ADMIN") // #6
        .anyRequest().authenticated() // 7
        .and()
    .formLogin()  // #8
        .loginUrl("/login") // #9
        .permitAll(); // #5
  }
}
```

在 Spring Security 複寫 config 方法的時候，有三種不同的方式，說明如下: 
### configure(HttpSecurity)
允許基於選擇匹配在資源級別配置基於 Web 的安全性 - 例如，下面的示例將 /admin/ 開頭的 URL 限制為具有 ADMIN 角色的用戶，並聲明任何其他 URL 需要成功認證。
```java
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
}
```
### configure(WebSecurity)
用於影響全局安全性的配置設置（忽略資源、設置調試模式、通過實施自定義防火牆定義拒絕請求）。
例如，以下方法將導致任何以 /resources/ 開頭的請求被忽略以進行身份驗證。
```java
public void configure(WebSecurity web) throws Exception {
    web
        .ignoring()
        .antMatchers("/resources/**");
}
```
### configure(AuthenticationManagerBuilder)
用於通過允許輕鬆添加 AuthenticationProviders 來建立身份驗證機制：例如，以下定義了具有內置“用戶”和“管理員”登錄名的內存身份驗證。
```java
public void configure(AuthenticationManagerBuilder auth) {
    auth
        .inMemoryAuthentication()
        .withUser("user")
        .password("password")
        .roles("USER")
    .and()
        .withUser("admin")
        .password("password")
        .roles("ADMIN","USER");
}
```


以上 java 配置與 XML 配置相似
```xml
<http security="none" pattern="/resources/**"/>
<http use-expressions="true">
  <intercept-url pattern="/logout" access="permitAll"/>
  <intercept-url pattern="/login" access="permitAll"/>
  <intercept-url pattern="/signup" access="permitAll"/>
  <intercept-url pattern="/about" access="permitAll"/>
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
  <logout
      logout-success-url="/login?logout"
      logout-url="/logout"
  />
  <form-login
      authentication-failure-url="/login?error"
      login-page="/login"
      login-processing-url="/login"
      password-parameter="password"
      username-parameter="username"
  />
</http>
<authentication-manager>
  <authentication-provider>
    <user-service>
      <user name="user" 
          password="password" 
          authorities="ROLE_USER"/>
      <user name="admin" 
          password="password" 
          authorities="ROLE_USER,ROLE_ADMIN"/>
    </user-service>
  </authentication-provider>
</authentication-manager>
```
[spring-security-java-config](https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/)

###### tags: `Spring`