【问题标题】:spring security angularjs forbidden 403春季安全 angularjs 禁止 403
【发布时间】:2016-10-27 09:11:32
【问题描述】:

我正在尝试向 angularjs 应用程序添加弹簧安全性。我正在关注本教程关于使用 Spring Security 保护单页应用程序:

https://spring.io/blog/2015/01/12/the-login-page-angular-js-and-spring-security-part-ii

不同之处在于我没有使用 spring boot 而是 spring mvc 用于此目的。我想我添加了我需要的所有东西,但由于某种原因,在输入 inMemory 凭据后,我得到了 403 禁止。

这是我的 spring 安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    System.out.println("initTT");
    auth
        .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {

  http
    .httpBasic()
  .and()
    .authorizeRequests()
      .antMatchers("/user").hasRole("USER")
      .anyRequest().authenticated()
   .and()
   .csrf().disable();
}


 @Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
         .antMatchers("/app/**"); 
  }

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

}

我使用了教程中的 authencate() 函数并将其添加到我的 app.js 文件中:

coursesApp.controller('loginController', function($rootScope, $scope, $http, $location) {


      var authenticate = function(credentials, callback) {
        var headers = credentials ? {authorization : "Basic "
            + btoa(credentials.username + ":" + credentials.password)
        } : {};


       console.log(headers);
        $http.get('/basic-web-app/user', {headers : headers}).success(function(data) {
          if (data.name) {
            $rootScope.authenticated = true;
          } else {
            $rootScope.authenticated = false;
          }
          callback && callback();
        }).error(function() {
          $rootScope.authenticated = false;
          callback && callback();
        });

      }

      authenticate();
      $scope.credentials = {};
      $scope.login = function() {
          console.log("login clicked!!!!!!!");
          authenticate($scope.credentials, function() {
            if ($rootScope.authenticated) {
              console.log("authenticated");
              $location.path("/");
              $scope.error = false;
            } else {
              console.log("not authenticated");
              $location.path("/login");
              $scope.error = true;
            }
          });
      };
    });

我有 UserController 和 /用户 教程中描述的端点。我正在用这个扫描包裹

 <context:component-scan base-package="com.courses.portal.controllers"/>

我还附上了 chrome 控制台的屏幕截图,以便清楚我在做什么:

web.xml 文件:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/business-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">
    <context:component-scan base-package="com.courses.portal.controllers"/>

    <mvc:resources mapping="/app/**" location="/app/build/"/>

    <mvc:annotation-driven/>

    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <security:global-method-security pre-post-annotations="enabled">
        <security:protect-pointcut expression="execution(* com.courses.portal.controllers.*.*(..))"
                                   access="ROLE_USER"/>
    </security:global-method-security>


</beans>

对不起,如果这是一个常见问题,但我在发布之前尝试在网络上找到任何有用的东西。谢谢!

【问题讨论】:

  • 看起来您正在发送正确的标头。您可以从服务器获取该请求的一些 DEBUG 日志吗?
  • 我从 mvc-dispatcher-servlet.xml 中删除了一些配置,现在它在控制台中打印出原理:org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4428690f:但是 chrome 开发者控制台说404 未找到:localhost:8087/basic-web-app/user 使用 web.xml 和 mvc-dispatcher-servlet.xml 文件更新了问题
  • 我肯定搞砸了配置。当我在 Web 浏览器中粘贴 localhost:8087/basic-web-app/user 时,它返回 HTTP 状态 404 - /basic-web-app/WEB-INF/jsp/user.jsp
  • 我认为问题出在视图解析器设置中,因为它正在尝试访问 /basic-web-app/WEB-INF/jsp/user.jsp
  • 也许你可以把你的整个项目放在 github 并在这里粘贴一个链接?

标签: java angularjs spring-mvc spring-security


【解决方案1】:

我的猜测(你还没有真正发布所有代码)是 /basic-web-app 是一个上下文根,它是一个 servlet API 构造 - 如果你正在创建绝对路径,你需要在客户端中使用它,但是它不知道 servlet,但是 Spring Security 是基于 servlet 的,所以它不需要前缀(我注意到你从 /app/** 配置中删除了静态资源)。尝试从安全配置路径中删除前缀。

【讨论】:

  • 我在 SecurityConfig 中的代码如下: ... .antMatchers("/user").hasRole("USER") .... 它不起作用。再次 403 禁止。这是我目前的代码,但是当我发布问题时,我粘贴了错误的 configure() 方法。因此,上下文根在一天前被排除在外。放入正确的状态。对不起。:/
  • 我无法找到您的 OAuth2 authserver 应用程序应在授权代码授予类型流程的步骤 C 中发送的状态信息。我正在尝试创建一个 node.js 客户端应用程序来代替您的 ui 示例应用程序。您是否愿意评论 node.js 客户端应该在哪里查找它需要在流程的步骤 C 和 D 之间处理的状态信息?这是链接:stackoverflow.com/questions/38133114/…
  • @DaveSyer 您的authserver 应用程序是否需要不同的配置才能为非spring 客户端(例如node.js 客户端)提供服务?即使是对此效果的评论也会极大地缩小为您的authserver 开发非弹簧客户端的工作。如果我知道 100% 的问题出在 oauth2 client 上,那么我就可以知道只关注客户端。请评论。 stackoverflow.com/questions/38018644/…
  • 服务器基本上是开箱即用的规范兼容,几乎可以肯定您的客户端是重点。
  • @DaveSyer 我用另外两个客户端应用程序进行了验证,以确认问题在于 Spring OAuth2 authserver 应用程序不符合 OAuth2,因为它无法验证非 Spring 客户端.问题可能出在令牌端点前面的过滤器链中。我创建了一个 GitHub 票证来总结问题,包括两个单独的示例客户端应用程序用于测试:github.com/spring-projects/spring-security-oauth/issues/806
猜你喜欢
  • 2017-09-19
  • 2013-12-22
  • 2014-02-02
  • 2012-12-13
  • 2017-11-30
  • 2021-05-12
  • 2019-03-31
相关资源
最近更新 更多