2016-10-06 165 views
0

我正在寻找一种方法来保护Spring Boot的@Secured注释的方法。对于大约10-15个用户,我不想连接到数据库,并从那里获取用户及其权限/角色,而是将它们本地存储在特定于配置文件的application.yml文件中。 Spring Boot中有没有一个概念支持这个想法?所有我能找到到目前为止与基本安全驱动器('org.springframework.boot:spring-boot-starter-security')的作品,看起来像这样:在application.yml中定义基本安全用户,密码和角色

security: 
    basic: 
    enabled: true 
    user: 
    name: admin 
    password: admin 
    role: EXAMPLE 

不过,我仍然能够访问与@RolesAllowed("READ")注释的方法,即使我会假设用户管理不应该有权访问所述方法。我的SecurityConfiguration看起来像这样:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(jsr250Enabled = true) 
@Profile("secure") 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
       .anyRequest() 
       .fullyAuthenticated() 
       .and() 
       .httpBasic(); 

     http.sessionManagement() 
       .sessionFixation() 
       .newSession(); 

     http.csrf().disable(); 
     http.headers().frameOptions().disable(); 

    } 
} 

最终这可能是一个不同的问题,但也许这对我自己的理解很重要。

我想知道如何在我的application.yml中指定具有不同密码和不同角色的多个用户并注释方法以确保只有授权用户才能访问这些方法。

+0

您无法在您的公司中指定多个用户nfiguration。你需要为此自行构建一些东西。 –

+0

@ M.Deinum谢谢,我想出了一个非常简单的方法来实现它。 – user3105453

回答

2

它可以自定义ConfigurationProperties来实现:

@ConfigurationProperties("application") 
public class ApplicationClients { 

    private final List<ApplicationClient> clients = new ArrayList<>(); 

    public List<ApplicationClient> getClients() { 
     return this.clients; 
    } 

} 

public class ApplicationClient { 
    private String username; 
    private String password; 
    private String[] roles; 
} 

@Configuration 
@EnableConfigurationProperties(ApplicationClients.class) 
public class AuthenticationManagerConfig extends 
     GlobalAuthenticationConfigurerAdapter { 

    @Autowired 
    ApplicationClients application; 

    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
     for (ApplicationClient client : application.getClients()) { 
      auth.inMemoryAuthentication() 
        .withUser(client.getUsername()).password(client.getPassword()).roles(client.getRoles()); 
     } 
    } 

} 

然后你就可以在指定用户的application.yml

application: 
    clients: 
    - username: rw 
     password: rw 
     roles: READ,WRITE 
    - username: r 
     password: r 
     roles: READ 
    - username: w 
     password: w 
     roles: WRITE 

不要忘记添加spring-boot-configuration-processorbuild.gradle

compile 'org.springframework.boot:spring-boot-configuration-processor'