пружинная защита с интеграцией angularjs

0

У меня есть сервис-сервис jersey, который я использую для предоставления данных для приложения AngularJS. Я хочу сделать некоторые методы отдыха безопасными, как и все методы в этом шаблоне (myapp/data/**). У меня есть класс Spring @Repository, чтобы получить имена пользователей и пароли пользователей. Как я могу это достичь?

Я попытался сделать это так:

@Configuration
@Order(2147483636)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests()
            .antMatchers("/rest/**", "/").permitAll().anyRequest()
            .authenticated().and().csrf()
            .csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
            .userDetailsService(userService);
}

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                    .getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
}
}

но ничто не защищено, как без этого класса.

пример одного из методов rest, который я хочу быть безопасным:

@Path("/rest")
public class RestService {
@GET
@Path("/getEntity")
@Produces("application/json")
public Response getEntity(@QueryParam("id") int entityId) {
    Entity e = entityRepository.get(entityId);
    if (e != null) {
        Response.ok(ObjectUtils.toJson(entity), MediaType.APPLICATION_JSON).build();
    }
    return Response.serverError().entity("Entity + entityId + " not found").build();
}
Теги:
spring-security
spring
rest

1 ответ

0
Лучший ответ

Чтобы добавить SpringSecurityFilterChain в ваш контекст, вам необходимо создать класс SpringSecurityInitializer:

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
   //do nothing
}
  • 0
    спасибо за Ваш ответ

Ещё вопросы

Сообщество Overcoder
Наверх
Меню