0

Spring Security を使用して、Spring Data REST Web アプリケーションを AngularJS で保護しています。

私の SecurityConfig は次のように宣言されています。

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

  http
    .httpBasic().and()
    .authorizeRequests()
    
    // public ressources
    .antMatchers("/index.html", "/templates/public/**", "/js/**", "/").permitAll()
    .antMatchers(HttpMethod.GET, "/api/security/user").permitAll()
    .antMatchers("/api/**").hasAnyRole("ADMIN", "NORMALUSER")
    
    .anyRequest().authenticated()
    .and().exceptionHandling().authenticationEntryPoint(basicAuthenticationEntryPointHandler)
    
    .and().logout().logoutUrl("/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).deleteCookies("JSESSIONID").permitAll().and()
    .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}

私は通常、目標を達成するためにこのリンクをたどりました。

ここで、初めてログインすると、angular-request for return undefined$cookies.get("XSRF-TOKEN")が返され、データベースへのすべてのリクエストがブロックされません。

しかし、ログアウトして再度ログインすると、Cookie が返され、すべてのデータベース リクエストが許可されます。

そして、これは 2 回目のログインごとにのみ発生するため、次のようになります。

  1. 未定義

  2. クッキー

  3. 未定義

  4. クッキー

  5. 未定義

    ...

だから今、私の構造に深く入り込まずに私を助けてくれる人がいることを願っていますが、それが必要な場合はそうします.

前もって感謝します。

編集1:リクエストは次のとおりです。 ここに画像の説明を入力

プロセスに関連して: 私はトークンを CokieCsrfTokenRepository().loadToken() に記録しており、すべてのトークンが表示されています..

編集 2:ログインごとに呼び出す My Angular Service:

function authenticationService($rootScope, $http, $location, $filter, $cookies){    
    function authenticate(credentials, callback) {

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

        $http.get('api/security/user', {headers : headers}).success(function(data, status, get, header) {
            if (data.name) {
                $rootScope.authenticated = true;
                $rootScope.session = data;
                console.log($cookies.get("XSRF-TOKEN")) // -> returns every second login cookie
                
            } else {
                $rootScope.authenticated = false;
                $rootScope.session = null;
            }
            
            console.log($rootScope.session)
            
            callback && callback();
        }).error(function() {
            $rootScope.authenticated = false;
            
            callback && callback();
        });
        
    }
    
    return {
        authenticate: function(credentials){
            authenticate(credentials, function() {
                if ($rootScope.authenticated == true) {
                    $rootScope.authenticationError = false;
                    
                    if ($rootScope.session.principal.admin == true){
                        $location.path("/admin/manage");
                    } else{
                        $location.path("/user");
                    }
                } else {
                    $rootScope.authenticationError = true;
                    
                    $location.path("/login");
                }
            });
        },
        // called by refreshing browser
        checkLoggedIn: function(){
            authenticate();
        },
        
        logout: function(){
            $http.post('/logout', {})["finally"](function() {
                $rootScope.authenticated = false;
                $rootScope.session = null;
                $location.path("/login");
            });
        }
    };
}

編集 3: Cookie が定義されていない場合、このリンクのメソッド loadToken() は、ログアウトしてブラウザーを更新した後 (最初のログイン) にのみ呼び出されることを述べました。次に、トークンが表示され、再びログインします。しかし、毎秒試した後でも、うまく機能します..

編集 4:最初の禁止された POST 要求 (Edit3 では /logout) の後、トークンがテンプレートに到着することを認識しませんでした。ブラウザを更新すると、リクエストごとに Cookie が送信されるようになるため、すべてのリクエストが許可されます。しかし、これを修正する方法は?

4

1 に答える 1

-1

私の解決策:

//WebSecurityConfigurerAdapter:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    ....
    .addFilterAfter(new CsrfCustomFilter(), CsrfFilter.class).and()
    .csrf().csrfTokenRepository(csrfTokenRepository());
}

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

public class CsrfCustomFilter extends 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);
    }
}
于 2017-01-20T09:08:44.310 に答える