2016-04-15 79 views
0

有沒有一種方法可以配置Spring Security(使用Java配置)以僅保護自定義頁面,甚至可以在註解上工作?Spring Security安全自定義頁面

這個想法是,我想保證自定義調用如/admin和其他東西(沒有硬編碼安全配置中的每個調用),它是在控制器中設置的提到的註釋,但其他的東西不應該使用完全認證。

回答

1

我很難找到適合我的東西。這是訣竅,它也是非常可讀的。

@Override 
protected void configure(HttpSecurity http) throws Exception 
{ 
    http.authorizeRequests() 
      .antMatchers("/admin/**").access("hasRole('ADMIN')") 
      .antMatchers("/**").permitAll() 
      .anyRequest().authenticated() 
      .and() 
      .formLogin(); 
} 

滿級對於那些誰仍然不能在同一網頁上

package com.your.package.config; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.*; 

@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter 
{ 
    @Override 
    protected void configure(HttpSecurity http) throws Exception 
    { 
     http.authorizeRequests() 
       .antMatchers("/admin/**").access("hasRole('ADMIN')") 
       .antMatchers("/**").permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .formLogin(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
    { 
     auth.inMemoryAuthentication().withUser("user").password("password").roles("USER"); 
    } 
} 

注意,不是調用formLogin()方法將使默認的「/登錄」返回404錯誤。

0

我不知道這是否回答你的問題,但你可以使用ant的匹配來識別特定頁面,而忽略其他人在你的安全配置,像這樣:

.antMatchers("/**").permitAll() 

.antMatcher("/admin/**") 
.authorizeRequests() 
.anyRequest().authenticated() 
+0

http://stackoverflow.com/questions/35633194/spring-security-configuration-for-basic-authentication-and-form-login/35634692#35634692在這裏你可以找到兩個工作的例子,也許它有幫助。 – Andrei

+0

感謝您的回覆。第二個版本是我需要的,但仍然是更多的硬編碼(「/ admin/**」)。 但是最終的結果是來自系統的「另一面」 - 我簡單地爲Controller定義添加了 @PreAuthorize(「hasRole('ROLE_ANONYMOUS')」) ,這幫助我導出了主要調用從那些我需要額外的安全。 –

+0

如果要完全刪除java配置類中的硬編碼值,可以使用常量定義一個抽象類,如ADMIN_PATH =「/ admin /」,並將其用於控制​​器和安全配置中,或者甚至可以更好地定義它在屬性文件中。 – Andrei

相關問題