限制安全身份验证以进行读取访问

时间:2018-11-20 16:29:05

标签: java spring spring-boot spring-security

我使用GitHub中的示例项目创建了一个Web应用程序。但是,它要求所有粗粒操作都进行身份验证。我想限制所有读取数据库操作的安全检查。我需要什么更改?

这些是相关的类:

protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                    .and()
                .csrf()
                    .disable()
                .exceptionHandling()
                    .authenticationEntryPoint(unauthorizedHandler)
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .authorizeRequests()
                    .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js")
                        .permitAll()
                    .antMatchers("/api/auth/**")
                        .permitAll()
                    .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                        .permitAll()
                    .antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
                        .permitAll()
                    .anyRequest()
                        .authenticated();

        // Add our custom JWT security filter
        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    }
}

2 个答案:

答案 0 :(得分:2)

据我所知,没有办法神奇地创建只读用户。但是,您可以创建诸如ROLE_UPDATE之类的角色,并通过执行来保护执行创建/更新/删除操作的所有方法。 @Secured("ROLE_UPDATE")。然后,如果未授予用户ROLE_UPDATE权限,则他们将无法调用任何“写入”方法,因此将仅限于调用“读取”方法。

答案 1 :(得分:1)

通常,Spring Security没有这种功能。您可以按照@Alien建议的方法创建角色(例如ROLE_WRITE,然后检查资源是否正在尝试访问资源的用户具有正确的角色

@PreAuthorize("hasRole('ROLE_WRITE')")
public String someWriteOperation() {
}

另一种方法(但仅在JPA框架允许您使用此功能时才适用),它是在春季创建Filter,然后在链中进一步处理您的请求之前,以只读方式创建事务:

@Component
@Order(1)
public class TransactionFilter implements Filter {

    @Override
    public void doFilterServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //Create read only transaction  
        // ex. if(isUserReadOnly(Security ....getUser())) {DBSession.setReadOnly(true);}
        //Remember it will work only if your JPA framework have the feature - explore your code/framework before

        chain.doFilter(request, response);
    }
}

记住过滤器顺序应在Spring Security过滤器之后

相关问题