【问题标题】:Authorization and Authentication with Spring Security使用 Spring Security 进行授权和身份验证
【发布时间】:2017-05-10 05:37:54
【问题描述】:

我有一个基于 Spring 构建的 Web 服务。我目前正在使用 Spring Security 进行身份验证,如下所示:

@Configuration
@EnableGlobalMethodSecurity(securedEnabled=true)
@EnableWebSecurity

public class ServerSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Properties properties;

    private static final String ALL_URI = "/v1/**";
    private static final String HEALTH_URI = "/v1/healthCheck";

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(getFilter(), BasicAuthenticationFilter.class);
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests()
                .antMatchers(HEALTH_URI).permitAll()
                .anyRequest().authenticated();
        http.csrf().disable();
    }

    private AuthenticationFilter getFilter() {
        return new AuthenticationFilter( properties.getKey());
    }
}

我的AuthenticationFilter 类扩展AbstractAuthenticationProcessingFilter 并执行实际的身份验证。如果我想将授权添加到我的安全性中,我是否只需在 AuthenticationFilter 之外的 attemptAuthentication 方法中进行这些检查?或者有更好的方法吗?我理解的方式是授权和身份验证应该独立完成。您首先进行身份验证,然后验证权限。所以,我认为会有更好的方法在 Spring Security 中进行授权,而不仅仅是将其添加到 attemptAuthentication 方法中。

【问题讨论】:

    标签: java spring authentication spring-security authorization


    【解决方案1】:

    您需要AuthenticationProvider 进行身份验证,实现AuthenticationProvider 并覆盖authenticationsupports 方法,然后注入AuthenticationManager

    过滤器中attemptAuthentication的方法通常是获取authentication(例如UsernamePasswordFilter从请求中获取usernamepassword,然后构建一个UsernamePasswordAuthenticationTokenAuthenticationManager),

    supports 方法测试AuthenticationProvider 是否可以用来做身份验证。(例如DaoAuthenticationProvider 支持UsernamePasswordAuthenticationToken

    authenticate 方法用于进行身份验证(例如DaoAuthenticationProvider 通过用户名获取真实密码,然后与用户输入的密码进行比较),该方法应返回一个已通过身份验证的Authentication(例如UsernamePasswordAuthenticationToken) ,并且这个认证应该包含用户权限(这个可以用来hasRole('xxx')),或者使用detail等等。

    attemptAuthentication 成功后,Authentication 将设置为SecurityContextHolder。然后你可以使用hasRole('xx'),或者别的什么。

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2014-03-06
      • 2011-07-17
      • 2012-12-12
      • 2015-05-22
      • 2015-06-29
      • 2018-03-12
      • 2020-03-15
      • 2011-10-17
      相关资源
      最近更新 更多