Spring应用程序中的每个请求的Spring安全授权(无登录表单)

时间:2015-10-31 23:12:20

标签: java spring spring-security

我的Spring项目中有类似这样的POST请求:

{"clientKey":"XXX", "accessKey":"ZZZ", ... }

我的后端工作在非常简单的范例中:从POST正文中获取clientKey(登录)和accessKey(密码)参数,检查它们在数据库中的持久性,然后执行一些业务逻辑。

我需要为每个传入请求使用Spring Security实现最小的安全检查逻辑(没有会话和令牌)。

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").hasRole("USER")
                .and().csrf().disable();
        http.addFilterBefore(new ApiAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

ApiAuthorizationFilter.java

public class ApiAuthorizationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
                    throws IOException, ServletException {
        //
        // always prints "{}", why?
        //
        Logger.getLogger("test").log(Level.INFO, request.getParameterMap().toString());

        //
        // Ok, I will make some manual auth operations for testing purposes.
        // Seems what it isn't work too..
        //
        Set<SimpleGrantedAuthority> authorities = new HashSet<>(1);
        authorities.add(new SimpleGrantedAuthority("USER"));
        Authentication auth = new UsernamePasswordAuthenticationToken(
                "94fc97a7b3fd2175472ec4a41bcb3b14",
                "746b2aa32fe90f0ba53e6efe7a8d1f1f", 
                authorities);
        SecurityContextHolder.getContext().setAuthentication(auth);

        chain.doFilter(request, response);
    }
}

我做错了什么? UsernamePasswordAuthenticationFilter在提交时是否仅适用于登录表单,或者我需要安全链中的其他过滤器?

0 个答案:

没有答案